diff --git a/apps/presentation/dashboard/smoke/compaction-memory-browser-smoke.mjs b/apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs
similarity index 68%
rename from apps/presentation/dashboard/smoke/compaction-memory-browser-smoke.mjs
rename to apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs
index 9e929b2566..5d3c9276f8 100644
--- a/apps/presentation/dashboard/smoke/compaction-memory-browser-smoke.mjs
+++ b/apps/presentation/dashboard/smoke/compaction-memory-retirement-browser-smoke.mjs
@@ -1,5 +1,5 @@
-// PR-scoped regression: a packaged switch uses real preview/apply/readback,
-// survives reload, rejects stale writes and removes its opt-in on disablement.
+// Retirement regression: a saved experimental opt-in stays inert and hidden;
+// sibling settings retain real preview/apply/readback and stale-write recovery.
// Isolated machine, empty registry, unavailable native host; no model calls.
import assert from "node:assert/strict";
import {spawn} from "node:child_process";
@@ -14,6 +14,12 @@ const root = await mkdtemp(join(tmpdir(), "loopx-compaction-preference-"));
const port = Number(process.env.LOOPX_COMPACTION_MEMORY_PORT ?? 5414);
const screenshots = process.env.LOOPX_COMPACTION_MEMORY_SCREENSHOTS;
const registry = join(root, "registry.json");
+await mkdir(join(root, "runtime", "machine"), {recursive: true});
+await writeFile(join(root, "runtime", "machine", "configuration.json"), JSON.stringify({
+ schema_version: "loopx_machine_configuration_v0", namespaces: {
+ compaction_memory: {schema_version: "compaction_memory_machine_defaults_v0", enabled: true},
+ },
+}));
await writeFile(registry, '{"goals":[]}');
await mkdir(join(root, "home"));
if (screenshots) await mkdir(screenshots, {recursive: true});
@@ -39,28 +45,24 @@ try {
});
const open = async () => {
await page.goto(`${base}/chat/?settings_scope=machine&settings_tab=capabilities`, {waitUntil: "networkidle"});
- await page.getByText("Compaction working memory (experimental)", {exact: true}).first().click();
+ await page.getByText("Progressive context", {exact: true}).first().click();
+ assert.equal(await page.getByText("Compaction working memory (experimental)", {exact: true}).count(), 0);
+ assert.equal(await page.getByRole("switch", {name: "Enable experimental compaction working memory"}).count(), 0);
};
- const toggle = page.getByRole("switch", {name: "Enable experimental compaction working memory"});
+ const progressive = page.getByRole("switch", {name: "Read context progressively"});
+ const delta = page.getByRole("switch", {name: "Use cross-turn delta automatically on supported hosts"});
const configuration = async () => (await (await page.request.get(`${base}/api/chat/machine-configuration`)).json()).machine_configuration;
const capture = async name => {
if (screenshots) await page.screenshot({path: join(screenshots, name)});
};
await open();
- assert.equal(await toggle.isChecked(), false);
- await capture("desktop-off.png");
- let beforeSave = workRequests.length;
- await toggle.click();
- await page.getByText("Compaction working memory preference saved.", {exact: true}).waitFor();
- assert.equal(workRequests.length, beforeSave, "Enabling does not create a conversation or Turn");
- assert.equal(await toggle.isChecked(), true);
- assert.equal((await configuration()).namespaces.compaction_memory.enabled, true);
- await open();
- assert.equal(await toggle.isChecked(), true, "Persisted readback survives a fresh page");
- await capture("desktop-on.png");
+ assert.equal(await progressive.isChecked(), true);
+ assert.equal(await delta.isChecked(), true);
+ assert.equal((await configuration()).namespaces.compaction_memory, undefined);
+ await capture("desktop-settings.png");
await page.setViewportSize({width: 430, height: 932});
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
- await capture("narrow-on.png");
+ await capture("narrow-settings.png");
await page.setViewportSize({width: 1440, height: 1000});
// Keep the actual backend and invalidate only the request's CAS expectation.
@@ -68,29 +70,12 @@ try {
await page.route(apply, route => route.continue({postData: JSON.stringify({
...route.request().postDataJSON(), expected_plan_revision: `sha256:${"0".repeat(64)}`,
})}));
- beforeSave = workRequests.length;
- await toggle.click();
+ await progressive.click();
await page.getByText(/machine-configuration plan revision changed/u).waitFor();
- assert.equal(workRequests.length, beforeSave, "A rejected setting starts no work");
- assert.equal(await toggle.isChecked(), true, "A rejected save must not look disabled");
- assert.equal((await configuration()).namespaces.compaction_memory.enabled, true);
+ assert.equal(await progressive.isChecked(), true, "A rejected save retains the confirmed value");
+ assert.equal((await configuration()).namespaces.context_delivery, undefined);
await capture("desktop-rejected.png");
await page.unroute(apply);
- beforeSave = workRequests.length;
- await toggle.click();
- await page.getByText("Compaction working memory preference saved.", {exact: true}).waitFor();
- assert.equal(workRequests.length, beforeSave, "Disabling starts no work");
- assert.equal(await toggle.isChecked(), false);
- assert.equal((await configuration())?.namespaces.compaction_memory, undefined, "Disable restores older-editor compatibility");
- await open();
- assert.equal(await toggle.isChecked(), false);
- // Exercise the shared save helper with the pre-existing switches while the
- // experiment is absent. Each setting preserves the other's confirmed value.
- await page.getByText("Progressive context", {exact: true}).first().click();
- const progressive = page.getByRole("switch", {name: "Read context progressively"});
- const delta = page.getByRole("switch", {name: "Use cross-turn delta automatically on supported hosts"});
- assert.equal(await progressive.isChecked(), true);
- assert.equal(await delta.isChecked(), true);
await progressive.click();
await page.getByText("Progressive reads preference saved.", {exact: true}).waitFor();
assert.equal((await configuration()).namespaces.context_delivery.mode, "off");
@@ -99,15 +84,18 @@ try {
await page.getByText("Cross-turn delta preference saved.", {exact: true}).waitFor();
assert.equal((await configuration()).namespaces.context_delivery.delta_delivery, "off");
assert.equal(await progressive.isChecked(), false);
+ await open();
+ assert.equal(await progressive.isChecked(), false);
+ assert.equal(await delta.isChecked(), false);
assert.equal((await configuration()).namespaces.compaction_memory, undefined);
await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "zh-CN"));
await page.reload({waitUntil: "networkidle"});
- await page.getByText("压缩工作记忆(实验)", {exact: true}).first().click();
- assert.equal(await page.getByRole("switch", {name: "启用实验性压缩工作记忆"}).isChecked(), false);
- await capture("chinese-off.png");
+ assert.equal(await page.getByText("压缩工作记忆(实验)", {exact: true}).count(), 0);
+ assert.equal(await page.getByRole("switch", {name: "启用实验性压缩工作记忆"}).count(), 0);
+ await capture("chinese-settings.png");
// Existing Workbench entry may create Session metadata; no Turn is dispatched.
assert.equal(workRequests.some(path => path.endsWith("/turns")), false);
- console.log("compaction working memory: packaged enable/reload/stale-save/disable/Chinese readback passed");
+ console.log("compaction memory retirement: legacy-on hidden; sibling save/reload/stale-write recovery passed");
} finally {
await browser?.close();
if (server.exitCode === null) {
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts
index 7ea0c17994..bb4d4f76dc 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts
+++ b/apps/presentation/dashboard/src/features/personal-workspace/capability-localization.ts
@@ -12,7 +12,6 @@ type FieldCopy = Record> = {
en: {
- compaction_memory: {displayName: "Compaction working memory (experimental)", description: "Restore source-backed work notes after context compaction."},
context_delivery: {displayName: "Progressive context", description: "Read current requirements before supporting material. Supported hosts can reuse unchanged context independently."},
codex_chat: {displayName: "Codex Goal conversation defaults", description: "Choose the native Codex profile, model, speed tier and reasoning effort for new Goal conversations. Existing conversations keep their original history. This does not start or reconfigure an active Agent Loop, worker or steward."},
decision_context: {displayName: "Find evidence", description: "Find advisory evidence with a temporary private profile. OpenViking and BM25 are retrieval implementations; this page does not save a binding or enable automatic memory."},
@@ -83,7 +82,6 @@ const capabilityCopy: Record> = {
},
},
"zh-CN": {
- compaction_memory: {displayName: "压缩工作记忆(实验)", description: "上下文压缩后恢复有来源的工作要点。"},
context_delivery: {displayName: "渐进上下文", description: "先展示当前目标与约束,按需读取材料;支持的宿主可独立复用跨轮上下文。"},
codex_chat: {displayName: "Codex Goal 对话默认值", description: "分别选择 Codex 配置来源、模型、速度档和推理强度,作用于本机的新 Goal 对话。已有对话保留原历史;不会启动或重配正在运行的 Agent Loop、工作 Agent 或管家。"},
decision_context: {displayName: "资料召回", description: "通过临时私有配置查找参考证据。OpenViking、BM25 是检索实现;本页不保存绑定,也不启用自动记忆。"},
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx b/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx
index 73481eb4f4..20730ae91d 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx
+++ b/apps/presentation/dashboard/src/features/personal-workspace/machine-configuration-settings.tsx
@@ -289,24 +289,15 @@ export function MachineConfigurationSettings({ section, onChanged }: {
await saveImmediatePreference(configuration, label);
}
- async function setCompactionMemory(enabled: boolean) {
- if (busy || !editorAvailable || selected?.capability_id !== "compaction_memory") return;
- // Removing the opt-in namespace also restores compatibility with older editors.
- await saveImmediatePreference(enabled ? {...selected.default, enabled: true} : null,
- locale === "zh-CN" ? "压缩工作记忆" : "Compaction working memory");
- }
-
- async function saveImmediatePreference(configuration: Record | null, label: string) {
+ async function saveImmediatePreference(configuration: Record, label: string) {
if (busy || !editorAvailable || !selected?.machine_namespace) return;
const namespace = selected.machine_namespace;
const generation = editorGeneration.current;
setBusy("apply"); setError(null); setNotice(null);
try {
- const plan = configuration === null ? await previewMachineConfigurationRemoval(namespace)
- : await previewMachineConfiguration(namespace, configuration);
+ const plan = await previewMachineConfiguration(namespace, configuration);
if (generation !== editorGeneration.current) return;
- if (configuration === null) await applyMachineConfigurationRemoval(namespace, plan.plan_revision);
- else await applyMachineConfiguration(namespace, configuration, plan.plan_revision);
+ await applyMachineConfiguration(namespace, configuration, plan.plan_revision);
if (generation !== editorGeneration.current) { onChanged?.(); return; }
setReadbackPending(selected.display_name);
const next = await fetchMachineConfiguration();
@@ -314,8 +305,7 @@ export function MachineConfigurationSettings({ section, onChanged }: {
setInspection(next);
setReadbackPending(null);
const saved = next.machine_configuration?.namespaces[namespace];
- if (next.status === "invalid" || (configuration === null ? saved !== undefined
- : Object.entries(configuration).some(([key, value]) => saved?.[key] !== value))) {
+ if (next.status === "invalid" || Object.entries(configuration).some(([key, value]) => saved?.[key] !== value)) {
throw new Error(locale === "zh-CN" ? "保存后的配置已变化,请刷新后重试。" : "The saved configuration changed. Refresh and retry.");
}
setNotice(locale === "zh-CN" ? `${label}偏好已保存。` : `${label} preference saved.`);
@@ -561,18 +551,7 @@ export function MachineConfigurationSettings({ section, onChanged }: {
? "渐进读取先提供当前要求,支持材料按需展开,适用于所有宿主。跨轮差分独立控制:仅在受支持的 POSIX Codex App/SSH、benchmark 心跳已保留完整旧上下文时自动使用,否则恢复完整当前输入。关闭偏好和实验显式关闭均继续生效。保存不会安装 hook、启动实验或证明当前会话已采用差分。"
: "Progressive reads present current requirements before expandable supporting material on every host. Cross-turn delta is independent: automatic reuse requires a supported POSIX Codex App/SSH or benchmark heartbeat and complete retained context; otherwise the current full input is restored. Saved off preferences and explicit experiment opt-outs remain effective. Saving installs no hook, starts no experiment and does not prove current-session delta use."}
: null}
- {selected.capability_id === "compaction_memory" ?
+ {editorAvailable && selected.capability_id !== "context_delivery" ? <>{editorMode === "json" || !selected.configuration_editor.fields.some((field) => field.key === "enabled" && field.input_kind === "boolean") ?
changeMode(editorMode === "guided" ? "json" : "guided")} type="button">
{t(editorMode === "guided" ? "machine.editJson" : "machine.backToForm")}
@@ -621,7 +600,7 @@ export function MachineConfigurationSettings({ section, onChanged }: {
) : null}
- {editorAvailable && selected.capability_id !== "context_delivery" && selected.capability_id !== "compaction_memory" ?
+ {editorAvailable && selected.capability_id !== "context_delivery" ?
{configured ? void createRemovalPreview()} type="button"> {t("machine.previewRemoval")} : null}
void createPreview()} type="button">{busy === "preview" ? t("common.loading") : t("machine.previewChanges")}
void applyPreview()} type="button">{busy === "apply" ? t("common.loading") : t("machine.applyPreview")}
diff --git a/docs/architecture/rfcs/README.md b/docs/architecture/rfcs/README.md
index bef95fcfc6..34dc50e1dd 100644
--- a/docs/architecture/rfcs/README.md
+++ b/docs/architecture/rfcs/README.md
@@ -212,14 +212,11 @@ Paired diffs do not certify translation accuracy.
remain unqualified; no runtime, default or experiment change.
- [Sparse Working Memory at Context Compaction v0](sparse-compaction-working-memory-v0.md)
([中文版](sparse-compaction-working-memory-v0.zh-CN.md))
- - **Delivery on merge:** Partial experimental implementation; independent
- machine opt-in, off by default, with a Workbench switch.
- - **Current boundary:** Deterministic exact selected-work notes and references,
- immutable private artifacts and additive native post-compaction restoration.
- Actual native model-input and packaged settings checks are recorded in the
- [ledger](ledger/sparse-compaction-working-memory-v0/2026-11-17-native-kernel-and-workbench.md).
- Conversation semantic extraction, broad retention, task benefit and total-cost
- reduction remain unqualified; no paid/task-benefit experiment starts here.
+ - **Retired:** Kernel execution and Workbench activation removed after the
+ requester withdrew the unqualified experiment. Strict saved-settings
+ compatibility and existing exact capture references remain; see the
+ [retirement ledger](ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.md).
+
- [TypeScript Control-Plane Migration v0](typescript-control-plane-migration-v0.md)
([中文版](typescript-control-plane-migration-v0.zh-CN.md))
- **Delivery on `main`:** Substantially implemented; active migration.
diff --git a/docs/architecture/rfcs/STATUS.md b/docs/architecture/rfcs/STATUS.md
index 39ea07253b..f3409dcff3 100644
--- a/docs/architecture/rfcs/STATUS.md
+++ b/docs/architecture/rfcs/STATUS.md
@@ -18,7 +18,7 @@ appendix may keep dated history, but no dated log heading may precede it.
[中文版](STATUS.zh-CN.md) is the semantic mirror of this file.
-## Accepted (53)
+## Accepted (52)
| RFC | Header status | Supersedes / closes | Ledger |
| --- | --- | --- | --- |
@@ -72,7 +72,6 @@ appendix may keep dated history, but no dated log heading may precede it.
| [RFC: Shared Goal Alignment and Governed Amendment Protocol (v0)](shared-goal-alignment-and-governed-amendment-v0.md) | Accepted | none | [2 entries](ledger/shared-goal-alignment-and-governed-amendment-v0/) |
| [RFC: LoopX Shared Control-Plane Authority and Pluggable State Providers (v0)](shared-goal-authority-state-provider-v0.md) | Accepted | none | [24 entries](ledger/shared-goal-authority-state-provider-v0/) |
| [RFC: Single-Owner Local Daemon (v0)](single-owner-local-daemon-v0.md) | Accepted | none | — |
-| [RFC: Sparse Working Memory at Context Compaction (v0)](sparse-compaction-working-memory-v0.md) | Accepted | none | [1 entry](ledger/sparse-compaction-working-memory-v0/) |
| [RFC: Joint Target, Yardstick and Stride Decisions (v0)](target-yardstick-stride-decisions-v0.md) | Accepted | none | — |
| [RFC: TypeScript Control-Plane Migration Direction v0](typescript-control-plane-migration-v0.md) | Accepted | none | [27 entries](ledger/typescript-control-plane-migration-v0/) |
@@ -82,6 +81,8 @@ appendix may keep dated history, but no dated log heading may precede it.
| --- | --- | --- | --- |
| [RFC: Personal Follow-through (v0)](personal-follow-through-v0.md) | Superseded | none; superseded by [Capable Agent Manager and Semantic Work Handoff](capable-manager-semantic-handoff-v0.md) | [1 entry](ledger/personal-follow-through-v0/) |
-## Retired (0)
+## Retired (1)
-_none_
+| RFC | Header status | Supersedes / closes | Ledger |
+| --- | --- | --- | --- |
+| [RFC: Sparse Working Memory at Context Compaction (v0)](sparse-compaction-working-memory-v0.md) | Retired | none | [2 entries](ledger/sparse-compaction-working-memory-v0/) |
diff --git a/docs/architecture/rfcs/STATUS.zh-CN.md b/docs/architecture/rfcs/STATUS.zh-CN.md
index 8f36023c58..cd61d9c972 100644
--- a/docs/architecture/rfcs/STATUS.zh-CN.md
+++ b/docs/architecture/rfcs/STATUS.zh-CN.md
@@ -15,7 +15,7 @@
[English](STATUS.md) 与本文互为语义镜像。
-## 已接受 (53)
+## 已接受 (52)
| RFC | 头部状态 | 替代 / 关闭 | Ledger |
| --- | --- | --- | --- |
@@ -69,7 +69,6 @@
| [RFC:共享 Goal 对齐与受治理 Amendment 协议(v0)](shared-goal-alignment-and-governed-amendment-v0.zh-CN.md) | 已接受 | 无 | [2 条](ledger/shared-goal-alignment-and-governed-amendment-v0/) |
| [RFC:LoopX 共享控制面权威与可插拔状态 Provider(v0)](shared-goal-authority-state-provider-v0.zh-CN.md) | 已接受 | 无 | [24 条](ledger/shared-goal-authority-state-provider-v0/) |
| [RFC: Single-Owner Local Daemon (v0)](single-owner-local-daemon-v0.md) | 已接受 | none | — |
-| [RFC:上下文压缩时的稀疏工作记忆(v0)](sparse-compaction-working-memory-v0.zh-CN.md) | 已接受 | 无 | [1 条](ledger/sparse-compaction-working-memory-v0/) |
| [RFC:Target、Yardstick 与 Stride 联合决策(v0)](target-yardstick-stride-decisions-v0.zh-CN.md) | 已接受 | none | — |
| [RFC:LoopX 控制面 TypeScript 渐进迁移方向 v0](typescript-control-plane-migration-v0.zh-CN.md) | 已接受 | 无 | [27 条](ledger/typescript-control-plane-migration-v0/) |
@@ -79,6 +78,8 @@
| --- | --- | --- | --- |
| [RFC:个人事项持续跟进(v0)](personal-follow-through-v0.zh-CN.md) | 已被替代 | 无; superseded by [Capable Agent Manager and Semantic Work Handoff](capable-manager-semantic-handoff-v0.md) | [1 条](ledger/personal-follow-through-v0/) |
-## 已退役(Retired 或 Rejected) (0)
+## 已退役(Retired 或 Rejected) (1)
-_无_
+| RFC | 头部状态 | 替代 / 关闭 | Ledger |
+| --- | --- | --- | --- |
+| [RFC:上下文压缩时的稀疏工作记忆(v0)](sparse-compaction-working-memory-v0.zh-CN.md) | 已退役 | 无 | [2 条](ledger/sparse-compaction-working-memory-v0/) |
diff --git a/docs/architecture/rfcs/ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.md b/docs/architecture/rfcs/ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.md
new file mode 100644
index 0000000000..2601b4a8fc
--- /dev/null
+++ b/docs/architecture/rfcs/ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.md
@@ -0,0 +1,51 @@
+# Retire the compaction working memory experiment
+
+- **Date:** 2026-11-17
+- **RFC:** [Sparse Working Memory at Context Compaction](../../sparse-compaction-working-memory-v0.md)
+- **Language mirror:** [中文版](2026-11-17-retirement.zh-CN.md)
+- **Baseline:** `68fe1788518e7edbf912638dcc421e17b0c9bc31` (main).
+
+## Decision and result
+
+The requester withdrew the experiment after its task and complete-cost benefit
+remained unqualified. This is a product retirement decision, not evidence that
+structured memory is ineffective in every setting. Preserve the original design,
+implementation ledger and evaluation evidence; no new model experiment is needed
+for this removal and no private evaluation traces are published here.
+
+Remove the TypeScript sparse-view operation, native capture/restore adapter,
+CLI hook branch, Workbench editor and switch, activation guide and its obsolete
+screenshots. Mark the RFC retired and correct the pending release guide.
+
+Retain a strict saved-settings decoder at the existing machine-configuration
+composition boundary. A prior true or false value remains part of the stored
+revision and transaction backup but is omitted from active catalogs and public
+projections. Namespace updates are rejected; sibling updates and rollback retain
+the old document without reactivating the experiment. Reads perform no migration.
+Unknown namespaces and malformed old settings remain fail-closed. An older
+implementation can still reactivate its saved opt-in after a downgrade.
+
+Keep ordinary native lifecycle/recovery, Progressive/Delta delivery and exact
+capture readers. Existing immutable files and sources are not cleaned up.
+Reintroduction requires a new proposal and qualification evidence.
+
+## Validation and limits
+
+- Python configuration, API, Goal-default and context tests: 139 passed,
+ 10 skipped; the independent historical-reference reader test also passed.
+- Actual native Codex compaction against loopback inference: two cases passed
+ with prior false/true settings. No experimental memory was injected or created;
+ original source bytes were retained. No paid model calls were made.
+- TypeScript context delivery, native lifecycle and Turn-envelope tests:
+ 101 passed; control-plane type checking and the frontend build passed.
+- Packaged Workbench with the real isolated backend: old enabled value absent
+ from the catalog in English/Chinese; sibling saves, reload and stale-write
+ rejection/recovery passed at desktop and narrow widths. No Turn was dispatched.
+- Digest ownership guard: head has 16 passing checks and one pre-existing
+ consumer-registration failure for `settlement_readback.ts`. The same frozen
+ main has 15 passing checks and two failures; deleting the retired view removes
+ its private digest matcher. This does not certify the unrelated failing check.
+- Scoped Python typing reports one existing `no-any-return` error in untouched
+ `goal_storage.py:57`; the frozen main reproduces the same error.
+- Quick premerge and scoped lint passed. Packaged validation does not establish
+ installed behavior; deployment and merge require their existing owners.
diff --git a/docs/architecture/rfcs/ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.zh-CN.md b/docs/architecture/rfcs/ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.zh-CN.md
new file mode 100644
index 0000000000..8b27fc7757
--- /dev/null
+++ b/docs/architecture/rfcs/ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.zh-CN.md
@@ -0,0 +1,41 @@
+# 撤回压缩工作记忆实验
+
+- **日期:** 2026-11-17
+- **RFC:** [上下文压缩时的稀疏工作记忆](../../sparse-compaction-working-memory-v0.zh-CN.md)
+- **语言镜像:** [English](2026-11-17-retirement.md)
+- **基线:** `68fe1788518e7edbf912638dcc421e17b0c9bc31`(main)。
+
+## 决定与结果
+
+任务效果与完整成本收益仍未资格化,用户明确要求撤回实验。这是产品退役决定,
+不证明结构化记忆在所有场景均无效。保留原设计、实现账本与评测证据;此次移除无需
+新开模型实验,此处不发布私有评测轨迹。
+
+移除 TypeScript 稀疏视图操作、原生捕获/恢复适配器、CLI hook 分支、工作台编辑器
+与开关、启用指南及过期截图。RFC 标记退役,修正待发布说明。
+
+只在现有机器配置组合边界保留严格的旧配置解码。此前的 true/false 值仍参与存储
+revision 与事务备份,但不出现在活动目录或公共投影;拒绝该命名空间的更新,其他
+设置的更新与回滚保留原文档而不重新激活实验。读取不做迁移,未知命名空间与格式
+错误的旧值继续失败关闭。降级到仍实现实验的旧版可能重新启用此前保存的开启值。
+
+普通原生生命周期/恢复、Progressive/Delta 与精确 capture 读取继续保留,不清理
+已有不可变文件或原始来源。重新引入须另提方案与资格化证据。
+
+## 验证与边界
+
+- Python 配置、API、Goal 默认值及上下文测试:139 通过、10 跳过;独立的历史
+ 引用读取测试也通过。
+- 实际原生 Codex 压缩对接本地回环推理:旧配置 false/true 两例通过,均未注入
+ 或创建实验记忆,原始源字节保留。没有付费模型调用。
+- TypeScript 上下文分发、原生生命周期和 Turn-envelope 测试:101 通过;控制面
+ 类型检查与前端构建通过。
+- 打包工作台连接真实隔离后端:旧开启值不出现在中英文目录;其他设置的保存、
+ 重载、过期写入拒绝及恢复通过,检查桌面和窄屏;没有派发 Turn。
+- digest 单一所有权检查:本分支 16 通过、1 个既有失败,属于
+ `settlement_readback.ts` 的消费者登记;同一冻结 main 为 15 通过、2 失败。
+ 删除退役视图消除了它的私有 digest 匹配器,不认证另一个失败项。
+- 定向 Python 类型检查在未修改的 `goal_storage.py:57` 报告一个既有
+ `no-any-return` 错误,同一冻结 main 复现相同错误。
+- quick premerge 与定向 lint 通过。打包验证不代表安装态,部署与合并仍由原有
+ 负责人和权限边界控制。
diff --git a/docs/architecture/rfcs/sparse-compaction-working-memory-v0.md b/docs/architecture/rfcs/sparse-compaction-working-memory-v0.md
index 83d8030244..8701e03806 100644
--- a/docs/architecture/rfcs/sparse-compaction-working-memory-v0.md
+++ b/docs/architecture/rfcs/sparse-compaction-working-memory-v0.md
@@ -1,9 +1,9 @@
# RFC: Sparse Working Memory at Context Compaction (v0)
-- **RFC status:** Accepted (upon merge)
+- **RFC status:** Retired
- **Supersedes / closes:** none
-- **Delivery maturity:** Partial: deterministic native restoration and Workbench opt-in; semantic consolidation and task benefit unqualified.
-- **Feature status:** Experimental; independently opt-in and off by default.
+- **Delivery maturity:** Experiment: retired; task benefit unqualified.
+- **Feature status:** Retired; kernel execution and Workbench activation removed.
- **Authors / owners:** AI-assisted proposal; context presentation, native-host, history-working-set and T02 maintainers.
- **Created:** 2026-11-16
- **Last normative revision:** 2026-11-17
@@ -13,7 +13,9 @@
## Document map and maintenance contract
-Sections 1–12 define this bounded design; §4 records preimplementation code facts and §5.5 defines the implemented first profile. Accepted status takes effect only upon merge; it does not certify task benefit or product promotion. Execution evidence lives in the [ledger](ledger/sparse-compaction-working-memory-v0/2026-11-17-native-kernel-and-workbench.md), following the [ledger contract](ledger/README.md); maintain both language mirrors together.
+This RFC is retired. Sections 1–12 remain the historical experimental design, not an active feature or implementation plan. Preserve the [original implementation ledger](ledger/sparse-compaction-working-memory-v0/2026-11-17-native-kernel-and-workbench.md) and the [retirement decision](ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.md); maintain both language mirrors together.
+
+**Current decision:** Task effectiveness and complete-cost benefit remain unqualified, and the requester explicitly withdrew the experiment. Remove sparse-view generation, compaction save/restore branches and the Workbench entry. Retain only strict compatibility decoding of saved `compaction_memory` settings: old values are neither advertised nor editable and trigger no execution; sibling settings remain readable, writable and transactionally restorable. Reads do not rewrite old files. Existing immutable memories, original sources and their exact readers retain their original lifetime; no automatic deletion is introduced. Reintroducing the experiment requires a new proposal and qualification evidence.
**Request versus proposal:** The requester asks to retain LoopX-recognizable structured information during context compaction, expects a sparser representation, identifies **FSoft-AI4Code/CodeWiki** as a reference, raises Manus's use of compression as memory as a research lead, confirms an **experimental feature**, and authorizes kernel implementation with a Workbench switch. Concrete design choices remain AI-selected implementation proposals pending review; that authorization does not certify the schema or benefit. “Compaction” here means conversation-context reduction, not model-weight compression.
diff --git a/docs/architecture/rfcs/sparse-compaction-working-memory-v0.zh-CN.md b/docs/architecture/rfcs/sparse-compaction-working-memory-v0.zh-CN.md
index d76f6c9675..e28ed8e8c1 100644
--- a/docs/architecture/rfcs/sparse-compaction-working-memory-v0.zh-CN.md
+++ b/docs/architecture/rfcs/sparse-compaction-working-memory-v0.zh-CN.md
@@ -1,9 +1,9 @@
# RFC:上下文压缩时的稀疏工作记忆(v0)
-- **RFC status:** Accepted (upon merge)
+- **RFC status:** Retired
- **替代 / 关闭:** 无
-- **Delivery maturity:** Partial:确定性原生恢复与工作台开关已实现;语义整理与任务收益未资格化。
-- **功能状态:** 实验性;独立显式开启,默认关闭。
+- **Delivery maturity:** Experiment:实验已撤回,任务收益未资格化。
+- **功能状态:** 已撤回;内核执行路径与工作台开关移除。
- **作者 / 负责人:** AI 辅助提案;上下文呈现、原生宿主、历史工作集与 T02 维护者。
- **创建日期:** 2026-11-16
- **最近规范修订:** 2026-11-17
@@ -13,7 +13,9 @@
## 文档地图与维护契约
-第 1–12 节定义本次有界设计;第 4 节记录实现前代码事实,第 5.5 节定义已实现的首个 profile。Accepted 仅在合入时生效,不认证任务收益或产品晋升。执行证据位于[账本](ledger/sparse-compaction-working-memory-v0/2026-11-17-native-kernel-and-workbench.zh-CN.md),遵循[账本契约](ledger/README.zh-CN.md),中英镜像同步维护。
+本 RFC 已退役。第 1–12 节保留为历史实验设计,不再作为当前功能或实施计划。原实现证据保留于[原账本](ledger/sparse-compaction-working-memory-v0/2026-11-17-native-kernel-and-workbench.zh-CN.md),撤回决定与兼容边界记录于[撤回账本](ledger/sparse-compaction-working-memory-v0/2026-11-17-retirement.zh-CN.md),中英镜像同步维护。
+
+**当前决定:** 任务效果与完整成本收益仍未资格化,用户明确要求下掉实验。移除稀疏视图生成、压缩保存/恢复分支和工作台入口。只保留旧 `compaction_memory` 配置的严格只读兼容解码:旧值不公开、不提供更新入口,也不触发执行;同一份配置中的其他设置仍可读取、保存与事务回滚。读取不改写旧文件。已有不可变记忆文件、原始来源及其精确读取路径继续遵循原有生命周期,不自动删除。恢复实验需要重新提出方案与资格化证据。
**用户方向与 AI 方案:** 用户希望在上下文压缩时保留 LoopX 可识别的结构化信息,预期表示更稀疏;明确参考 **FSoft-AI4Code/CodeWiki**,提出 Manus 将压缩作为记忆的研究线索,确认这是**实验性功能**,并授权实现到内核、为工作台提供开关。具体设计仍为 AI 选定、待评审的实现方案;该授权不认证 schema 或收益。“压缩”指对话上下文缩减,不指模型权重压缩。
diff --git a/docs/product/releases/v2.4.0.md b/docs/product/releases/v2.4.0.md
index a65df2acb0..9d9d5a51f4 100644
--- a/docs/product/releases/v2.4.0.md
+++ b/docs/product/releases/v2.4.0.md
@@ -68,7 +68,7 @@ loopx authority-archive upgrade --all-known --require-current
- Saved Research results retain their original answer when reopened, including historical answers whose complete snapshot must be read from its original source. [#8868](https://github.com/loopx-project/loopx/pull/8868), [#8863](https://github.com/loopx-project/loopx/pull/8863)
- The packaged workspace supplies the draft, confirmation and readback for conversational Goal creation. Its existing runtime readiness and access checks govern the authorized operation. [#8780](https://github.com/loopx-project/loopx/pull/8780)
- The material lifecycle capability can preview an evidence-bounded rerank in waves through its existing CLI. Applying a ranking remains a separately authorized owner operation. [#8579](https://github.com/loopx-project/loopx/pull/8579)
-- An experimental device switch can retain sourced work context around compaction in existing supported native root sessions. It defaults to off and adds to ordinary recovery; outcome and total-cost gains remain unverified. [#8872](https://github.com/loopx-project/loopx/pull/8872)
+- The unqualified compaction working memory experiment is retired: its kernel path and Workbench switch are removed. Saved settings remain read-compatible and inert; sibling settings and exact historical capture readers remain available. An older implementation can reactivate its saved opt-in after downgrade. See the [retirement reference](https://github.com/loopx-project/loopx/blob/v2.4.0/docs/reference/required-work-context.md#experimental-compaction-working-memory).
## Quality & Testing
@@ -212,22 +212,6 @@ loopx extension disable loopx-lark --execute --format json
uv run --extra test python -m pytest -q tests/control_plane/test_cli_source_activation_readback.py
```
-### Experimental compaction working memory
-
-**Activation:** Default off. In Workbench, open Settings → This device → Capability Center → Compaction working memory (experimental), then enable Keep work context at compaction. Existing supported native root sessions must already have context recovery and a Goal/Agent-bound source capture. Saving the preference installs no hooks and starts no work. [#8872](https://github.com/loopx-project/loopx/pull/8872)
-
-**Validation:** Reload the setting to confirm its persisted value, or inspect `machine_configuration.namespaces.compaction_memory.enabled` with the command below; `status: absent` or an absent namespace means off. At the next supported native compaction, inspect the source-bound memory reference delivered with ordinary recovery. Missing, changed, unsafe or oversized sources fall back to ordinary recovery; saving the switch alone does not prove session adoption. Unsupported hosts and child sessions retain their existing paths.
-
-**Disable / rollback:** Turn the switch off before using an older full-settings editor. This removes the experiment namespace and stops new memory preparation/restoration. Previously emitted immutable references remain subject to their original capture lifetime and access rules.
-
-**Authority boundary:** Memory preserves sourced short work facts and navigation without an additional model call. It grants no authority, read receipt, accepted result or Delta continuity, and removes no original input. Current requirements, stops and pending reads remain binding; outcome and complete-cost benefits have not been qualified.
-
-**Docs:** [Experimental compaction working memory](https://github.com/loopx-project/loopx/blob/v2.4.0/docs/reference/required-work-context.md#experimental-compaction-working-memory)
-
-```bash
-loopx --format json machine-config inspect
-```
-
### Private backup inspection
**Activation:** In Settings → Capability Center → device defaults → Configuration backup and recovery, choose Full archive inspection for the original archive and matching external manifest. Unsupported services/platforms leave the operation unavailable. The CLI operations below are per-command. Preview a private full-state backup for the project and the selected configuration cohort before creating it. Retain the matching archive, external manifest and compatible package. [#8864](https://github.com/loopx-project/loopx/pull/8864)
@@ -316,7 +300,7 @@ loopx extension doctor --all-enabled --execute
### 能力与工作流
-- 实验性本机开关可为既有受支持原生根会话保存有来源的压缩工作上下文。默认关闭,恢复内容在原恢复路径上追加,任务效果与完整成本收益尚未验证。 [#8872](https://github.com/loopx-project/loopx/pull/8872)
+- 未取得收益资格的压缩工作记忆实验已退役,内核路径与工作台开关移除。旧配置兼容读取且不生效,其他设置及历史 capture 精确读取仍可用;降级到旧实现可能重新启用此前保存的开启值。参见[撤回说明](https://github.com/loopx-project/loopx/blob/v2.4.0/docs/reference/required-work-context.md#experimental-compaction-working-memory)。
- 研究结果重开后保留原回答;历史回答的完整快照按其原来源读取。 [#8868](https://github.com/loopx-project/loopx/pull/8868), [#8863](https://github.com/loopx-project/loopx/pull/8863)
- 打包工作台交付 Goal 草稿、确认与读回流程。材料能力提供分波排序预览,应用排序仍经过材料 owner 的授权操作。 [#8780](https://github.com/loopx-project/loopx/pull/8780), [#8579](https://github.com/loopx-project/loopx/pull/8579)
@@ -462,22 +446,6 @@ loopx extension disable loopx-lark --execute --format json
uv run --extra test python -m pytest -q tests/control_plane/test_cli_source_activation_readback.py
```
-#### Experimental compaction working memory
-
-**启用:** 默认关闭。在工作台“设置 → 本机 → 能力中心 → 压缩工作记忆(实验)”开启“压缩时保留工作上下文”。既有受支持原生根会话须已启用上下文恢复,并有绑定 Goal/Agent 的源捕获。保存不安装 hook,不启动工作。 [#8872](https://github.com/loopx-project/loopx/pull/8872)
-
-**验证:** 重载设置核对持久值,或用下方命令检查 `machine_configuration.namespaces.compaction_memory.enabled`;`status: absent` 或没有该命名空间表示关闭。下一次受支持的原生压缩发生后,查看随原恢复返回、绑定来源的记忆引用。来源缺失、变化、不安全或超出上限时退回普通恢复。保存开关不证明当前会话已采用;不支持的 Host 和子会话沿用原路径。
-
-**停用 / 回退:** 使用旧版完整设置编辑器前关闭开关。这会移除实验命名空间,停止新的记忆准备与恢复。此前发出的不可变引用仍遵循原 capture 的生命周期与访问规则。
-
-**权限边界:** 记忆保存有来源的简短工作事实和导航,不额外调用模型,不授予权限、已读回执、验收结论或 Delta 连续性,也不移除原输入。当前要求、Stop 与未完成必读仍有效,任务效果和完整成本收益尚未取得资格。
-
-**文档:** [实验性压缩工作记忆](https://github.com/loopx-project/loopx/blob/v2.4.0/docs/reference/required-work-context.md#experimental-compaction-working-memory)
-
-```bash
-loopx --format json machine-config inspect
-```
-
#### Private backup inspection
**启用:** 在 Settings → Capability Center → device defaults → Configuration backup and recovery 选择 Full archive inspection,提供原归档及匹配的外部 manifest。不支持的服务或平台保持不可用。下方 CLI 按次调用。先预览项目及所选配置范围的私有完整备份,再在现有授权内创建;保留匹配的 archive、外部 manifest 和兼容版本。 [#8864](https://github.com/loopx-project/loopx/pull/8864)
diff --git a/docs/reference/assets/compaction-memory-narrow.png b/docs/reference/assets/compaction-memory-narrow.png
deleted file mode 100644
index d1be5ea259..0000000000
Binary files a/docs/reference/assets/compaction-memory-narrow.png and /dev/null differ
diff --git a/docs/reference/assets/compaction-memory-off.png b/docs/reference/assets/compaction-memory-off.png
deleted file mode 100644
index 8f2e4b9ba4..0000000000
Binary files a/docs/reference/assets/compaction-memory-off.png and /dev/null differ
diff --git a/docs/reference/assets/compaction-memory-on.png b/docs/reference/assets/compaction-memory-on.png
deleted file mode 100644
index af878be80e..0000000000
Binary files a/docs/reference/assets/compaction-memory-on.png and /dev/null differ
diff --git a/docs/reference/required-work-context.md b/docs/reference/required-work-context.md
index e39deda748..7aea4ee2c9 100644
--- a/docs/reference/required-work-context.md
+++ b/docs/reference/required-work-context.md
@@ -679,76 +679,23 @@ transport flag does not restore the old exact Todo schema.
## Experimental compaction working memory
-**Default: off.** In Workbench, open **Settings → This device → Capability Center →
-Compaction working memory (experimental)** and use **Keep work context at compaction**.
-The switch saves through the existing preview/apply/readback transaction; a failed
-save keeps the confirmed setting and displays the error. Reload to inspect the
-persisted value. It is a device preference, independent of Progressive/Delta;
-Goals cannot override it. Saving installs no hooks and dispatches no work.
-
-The initial disabled state and an enabled saved state:
-
-
-
-
-On a narrow screen the same setting appears below the capability selector:
-
-
-
-The registered machine namespace is `compaction_memory`, with the exact shape
-`{"schema_version":"compaction_memory_machine_defaults_v0","enabled":true}`.
-Absence means disabled. Existing supported native root sessions must already
-have context recovery enabled and a Goal/Agent-bound immutable source capture.
-The existing `codex_app_heartbeat`, `codex_app_ssh_goal` and
-`codex_benchmark_heartbeat` scenario restrictions remain in force. Other hosts,
-child sessions and a lone context-delivery off keep their ordinary paths.
-An explicit off/Delta-auto pair still qualifies the existing full-document native
-recovery path; the independent memory opt-in also applies there.
-The switch neither qualifies a new native version nor proves current-session use.
-
-After ordinary PreCompact/PostCompact lifecycle handling, the TypeScript context
-owner selects exact short selected-Todo title/note facts and original JSON
-pointers. Canonical matching Todo detail takes precedence over its display view.
-Titles over 512 UTF-8 bytes and notes over 1,024 bytes remain source references;
-they are not truncated into a new conclusion. Unknown material stays in the
-original capture. This first profile does not extract conversation semantics or
-make any additional model call.
-
-The private IO adapter publishes `memory-.json` with
-`schema_version:loopx_compaction_memory_v0`, original Goal/Agent/session/profile
-binding, source/recovery path and byte digest, exact inline-field `coverage`,
-optional `focus`, sourced `frontier` and `needed_reads` navigation. If an original
-Turn exists, its identity is preserved. The separate `compaction-memory.json`
-locator can change; emitted artifact references cannot. The existing exact
-capture reader opens the artifact through the command supplied with its ref.
-Pointers in the document resolve against its original `source`; they are not
-shell commands or independent evidence of reading.
-
-At SessionStart(source=compact), the adapter validates the current source,
-recovery, session and memory bytes before adding the short structure to ordinary
-recovery. Oversized views, missing/changed/unreadable sources, stale locators and
-unsafe files fall back to ordinary recovery. The artifact and restored structure
-are each bounded to 12,000 bytes; existing native delivery limits still apply.
-Memory grants no authority, read receipt, accepted result or Delta continuity.
-Current requirements, stops and original pending-read obligations remain binding.
-No original input is removed: restoration is additive, so smaller artifacts do
-not establish lower total input, better outcomes or lower total cost.
-
-**Disable / downgrade:** turn the switch off. Workbench removes the experiment
-namespace, stopping new memory preparation/restoration and restoring compatibility
-with older full-settings editors. Older scoped context readers already ignore
-this separate namespace; older full-settings editors reject it while present.
-Existing immutable files and references are retained, subject to the original
-capture lifetime and access/deletion rules. There is no cross-machine retention,
-automatic source GC or migration. See the [RFC](../architecture/rfcs/sparse-compaction-working-memory-v0.md)
-for remaining semantic, retention and outcome experiments.
-
-中文:工作台 **设置 → 本机 → 能力中心 → 压缩工作记忆(实验)** 提供独立开关,默认关闭。
-仅对已有上下文恢复的受支持原生根会话生效;保存不安装 hook、不启动工作。
-压缩时保存有来源的工作标题、短注记和引用,随后验证来源并恢复;不额外调用模型,
-不省略当前必读要求,不代表任务已完成或 Delta 连续性恢复。保存失败保持已确认状态;
-关闭会移除实验命名空间以支持旧版编辑器,已发出的文件引用仍按原来源生命周期保留。
-首版为增量恢复,任务效果与完整成本收益尚未验证。
+This experiment is retired. The kernel no longer prepares or restores its sparse
+memory view, and Workbench no longer offers its switch. Task effectiveness and
+complete-cost benefit remained unqualified; see the [retired RFC](../architecture/rfcs/sparse-compaction-working-memory-v0.md).
+
+Saved `compaction_memory_machine_defaults_v0` values remain strictly readable
+for settings compatibility, including a prior `enabled: true`. They have no
+runtime effect or editor. Other device settings and their transaction rollback
+remain available; reading does not rewrite the saved configuration. Existing
+immutable memory/source files and exact capture references retain their original
+lifetime and access rules. This change performs no source cleanup. Installing an
+older release that still implements the experiment can restore its behavior;
+remove its saved namespace before such a downgrade if that behavior is unwanted.
+
+中文:实验已撤回,内核不再生成或恢复实验记忆,工作台开关已移除。
+旧配置只用于兼容读取,即使曾保存开启也不生效;其他本机设置仍可编辑和事务回滚。
+已有记忆文件、原始来源与精确读取路径保留,不自动清理。降级到仍实现该实验的旧版
+可能恢复其行为;若不希望恢复,应在降级前移除旧命名空间。
## Opt-in native reuse
diff --git a/loopx/capabilities/configuration_ui.py b/loopx/capabilities/configuration_ui.py
index 8c8c9d5760..e991c2d0e9 100644
--- a/loopx/capabilities/configuration_ui.py
+++ b/loopx/capabilities/configuration_ui.py
@@ -93,11 +93,6 @@ def capability_configuration_editor(
codex_profiles = codex_profile_options()
definitions: dict[str, dict[str, Any]] = {
- "compaction_memory": {
- "supported_scopes": ["machine"], "writable_scopes": ["machine"],
- "fields": [_field("enabled", "Compaction working memory (experimental)", "boolean", required=True,
- description="On this device, save and restore a small source-bound view in already-supported native root sessions. No model calls or hook installation.")],
- },
"context_delivery": {
"supported_scopes": ["machine"], "writable_scopes": ["machine"],
"fields": [
diff --git a/loopx/capabilities/machine_configuration/builtins.py b/loopx/capabilities/machine_configuration/builtins.py
index edbcac9fda..8e26aab087 100644
--- a/loopx/capabilities/machine_configuration/builtins.py
+++ b/loopx/capabilities/machine_configuration/builtins.py
@@ -11,11 +11,6 @@
# boundary: the generic contract does not depend on any consumer capability,
# and a reader loads only the namespaces it resolves.
_BUILTIN_NAMESPACES = (
- (
- "compaction_memory",
- "loopx.capabilities.machine_configuration.compaction_memory",
- "compaction_memory_machine_configuration_namespace",
- ),
(
"context_delivery",
"loopx.capabilities.machine_configuration.context_delivery",
@@ -80,7 +75,10 @@ def load() -> MachineConfigurationNamespace:
def build_builtin_machine_configuration_registry() -> MachineConfigurationRegistry:
+ from .compaction_memory import normalize_compaction_memory
+
registry = MachineConfigurationRegistry()
+ registry.register_retired("compaction_memory", normalize_compaction_memory)
for namespace, module, factory in _BUILTIN_NAMESPACES:
registry.register_deferred(namespace, _owner(module, factory))
return registry
diff --git a/loopx/capabilities/machine_configuration/compaction_memory.py b/loopx/capabilities/machine_configuration/compaction_memory.py
index 9a7459b140..781db3d5a2 100644
--- a/loopx/capabilities/machine_configuration/compaction_memory.py
+++ b/loopx/capabilities/machine_configuration/compaction_memory.py
@@ -1,12 +1,9 @@
-"""Independent, default-off preference for native compaction working memory."""
+"""Strict decoder for a retired experiment; no activation or runtime owner."""
from __future__ import annotations
from collections.abc import Mapping
-from pathlib import Path
from typing import Any
-from .contract import MachineConfigurationNamespace
-
COMPACTION_MEMORY_MACHINE_SCHEMA = "compaction_memory_machine_defaults_v0"
@@ -16,32 +13,3 @@ def normalize_compaction_memory(raw: Mapping[str, Any]) -> dict[str, Any]:
or type(raw.get("enabled")) is not bool):
raise ValueError("compaction_memory requires its schema_version and boolean enabled")
return {"schema_version": COMPACTION_MEMORY_MACHINE_SCHEMA, "enabled": raw["enabled"]}
-
-
-def compaction_memory_machine_configuration_namespace() -> MachineConfigurationNamespace:
- return MachineConfigurationNamespace(
- namespace="compaction_memory",
- schema_versions=frozenset({COMPACTION_MEMORY_MACHINE_SCHEMA}),
- normalize=normalize_compaction_memory,
- project_public=dict,
- apply_public_update=lambda current, update: {**dict(current or {}), **dict(update)},
- title="Compaction working memory (experimental)",
- description="Preserve a small source-bound working view at compaction on supported native sessions. No extra model calls.",
- documentation={"path": "docs/reference/required-work-context.md#experimental-compaction-working-memory"},
- default_configuration={"schema_version": COMPACTION_MEMORY_MACHINE_SCHEMA, "enabled": False},
- )
-
-
-def compaction_memory_enabled(runtime_root: Path) -> bool:
- """Read only this preference; an optional invalid setting cannot break recovery."""
- from .builtins import build_builtin_machine_configuration_registry
- from .store import read_machine_configuration
-
- try:
- value = read_machine_configuration(
- runtime_root, registry=build_builtin_machine_configuration_registry(),
- namespace_ids=("compaction_memory",),
- )
- return bool(value and value["namespaces"].get("compaction_memory", {}).get("enabled") is True)
- except (OSError, TypeError, ValueError):
- return False
diff --git a/loopx/capabilities/machine_configuration/contract.py b/loopx/capabilities/machine_configuration/contract.py
index 8e0ac56957..6ee32708a9 100644
--- a/loopx/capabilities/machine_configuration/contract.py
+++ b/loopx/capabilities/machine_configuration/contract.py
@@ -90,9 +90,10 @@ class MachineConfigurationRegistry:
def __init__(self) -> None:
self._namespaces: dict[str, MachineConfigurationNamespace] = {}
self._deferred: dict[str, Callable[[], MachineConfigurationNamespace]] = {}
+ self._retired: dict[str, Normalizer] = {}
def _reserve(self, namespace: str) -> None:
- if namespace in self._namespaces or namespace in self._deferred:
+ if namespace in self._namespaces or namespace in self._deferred or namespace in self._retired:
raise ValueError(
"machine-configuration namespace is already registered: " + namespace
)
@@ -143,6 +144,39 @@ def resolve(self, namespace: str) -> MachineConfigurationNamespace:
self._namespaces[namespace] = contract
return contract
+ def register_retired(
+ self, namespace: str, normalize: Normalizer
+ ) -> MachineConfigurationRegistry:
+ """Decode saved settings without advertising or reviving their owner.
+
+ Retired values remain in the normalized storage document so revisions,
+ sibling updates and exact rollback retain their existing meaning.
+ They have no editor, public projection or namespace update operation.
+ """
+ if not _NAMESPACE_RE.fullmatch(namespace):
+ raise ValueError("machine-configuration namespace is invalid")
+ self._reserve(namespace)
+ self._retired[namespace] = normalize
+ return self
+
+ def normalize_namespace(self, namespace: str, candidate: dict[str, Any]) -> dict[str, Any]:
+ retired = self._retired.get(namespace)
+ if retired is not None:
+ return retired(candidate)
+ contract = self.resolve(namespace)
+ schema_version = str(candidate.get("schema_version") or "").strip()
+ if schema_version not in contract.schema_versions:
+ raise ValueError(
+ f"machine_configuration namespace {namespace} has unsupported "
+ f"schema_version: {schema_version or 'missing'}"
+ )
+ value = contract.normalize(candidate)
+ if value.get("schema_version") != schema_version:
+ raise ValueError(
+ f"machine-configuration normalizer changed {namespace} schema_version"
+ )
+ return value
+
@property
def namespace_ids(self) -> tuple[str, ...]:
return tuple(sorted({*self._namespaces, *self._deferred}))
@@ -248,22 +282,10 @@ def normalize_machine_configuration(
selected.intersection_update(namespace_ids)
normalized: dict[str, Any] = {}
for namespace in sorted(selected):
- contract = registry.resolve(namespace)
candidate = _mapping(
namespaces[namespace], f"machine_configuration.namespaces.{namespace}"
)
- schema_version = str(candidate.get("schema_version") or "").strip()
- if schema_version not in contract.schema_versions:
- raise ValueError(
- f"machine_configuration namespace {namespace} has unsupported "
- f"schema_version: {schema_version or 'missing'}"
- )
- value = contract.normalize(candidate)
- if value.get("schema_version") != schema_version:
- raise ValueError(
- f"machine-configuration normalizer changed {namespace} schema_version"
- )
- normalized[namespace] = value
+ normalized[namespace] = registry.normalize_namespace(namespace, candidate)
return {
"schema_version": MACHINE_CONFIGURATION_SCHEMA,
"namespaces": normalized,
@@ -283,6 +305,8 @@ def project_machine_configuration(
normalized = normalize_machine_configuration(configuration, registry=registry)
projected: dict[str, Any] = {}
for namespace, value in normalized["namespaces"].items():
+ if namespace not in registry.namespace_ids:
+ continue
contract = registry.resolve(namespace)
public_value = contract.project_public(value)
if public_value.get("schema_version") != value.get("schema_version"):
diff --git a/loopx/cli_commands/quota_capture.py b/loopx/cli_commands/quota_capture.py
index a70fa328d2..78c95edb6d 100644
--- a/loopx/cli_commands/quota_capture.py
+++ b/loopx/cli_commands/quota_capture.py
@@ -1042,15 +1042,6 @@ def handle_native_context_command(args: argparse.Namespace, *, print_payload: Ca
"hookEventName": event["hook_event_name"],
"additionalContext": " ".join(filter(None, [existing_context, preparation_context])),
}
- if (event["hook_event_name"] in ("PreCompact", "PostCompact")
- or event["hook_event_name"] == "SessionStart" and event.get("source") == "compact"):
- from ..capabilities.machine_configuration.compaction_memory import compaction_memory_enabled
- from ..paths import effective_runtime_root
-
- if compaction_memory_enabled(effective_runtime_root(registry_path, runtime_root_arg)):
- from ..control_plane.turn_driver.compaction_memory import compaction_memory_hook
-
- payload = compaction_memory_hook(directory, event, payload, profile=activation["scenario"])
else:
payload = {}
except (OSError, RuntimeError, subprocess.SubprocessError, ValueError, TypeError, RecursionError):
diff --git a/loopx/control_plane/quota/compaction_memory.ts b/loopx/control_plane/quota/compaction_memory.ts
deleted file mode 100644
index bd5c7f72c0..0000000000
--- a/loopx/control_plane/quota/compaction_memory.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-/** Source-bound advisory working memory. Never edits work, reads or continuity. */
-import type {JsonObject} from "../effect_program.ts";
-import {jsonObject, requireJsonObject, requireNonEmptyString} from "../runtime_decode.ts";
-import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts";
-
-export const COMPACTION_MEMORY_SCHEMA = "loopx_compaction_memory_v0";
-const MAX_VIEW_BYTES = 12000;
-const text = (value: unknown, bytes: number): string | undefined =>
- typeof value === "string" && value.trim() && Buffer.byteLength(value) <= bytes ? value : undefined;
-const pointer = (path: (string | number)[]) => "/" + path.map(part => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/");
-
-export function prepareCompactionMemory(request: JsonObject): JsonObject {
- const context = requireJsonObject(request.context, "memory source");
- const scope = requireJsonObject(request.scope, "memory scope");
- const binding: JsonObject = {};
- for (const key of ["goal_id", "agent_id", "session_id", "profile"])
- binding[key] = requireNonEmptyString(scope[key], `memory ${key}`);
- if (scope.turn_instance_id !== undefined)
- binding.turn_instance_id = requireNonEmptyString(scope.turn_instance_id, "original memory Turn");
- if (context.goal_id !== undefined && context.goal_id !== binding.goal_id)
- throw new Error("memory source belongs to a different Goal");
- const sourceAgent = context.agent_id ?? jsonObject(context.agent_identity)?.agent_id;
- if (sourceAgent !== undefined && sourceAgent !== binding.agent_id)
- throw new Error("memory source belongs to a different Agent");
- const source = requireJsonObject(request.source, "memory source reference");
- const recovery = requireJsonObject(request.recovery, "original recovery reference");
- const reference = (value: JsonObject): JsonObject => {
- const sha256 = requireNonEmptyString(value.sha256, "memory source digest");
- if (!/^[a-f0-9]{64}$/.test(sha256)) throw new Error("invalid memory source digest");
- return {path: requireNonEmptyString(value.path, "memory source path"), sha256};
- };
- const document: JsonObject = {
- schema_version: COMPACTION_MEMORY_SCHEMA, binding,
- source: reference(source), recovery: reference(recovery),
- coverage: [], frontier: [], needed_reads: [],
- };
- const coverage = document.coverage as string[];
- const frontier = document.frontier as JsonObject[];
- const reads = document.needed_reads as string[];
- let selected = jsonObject(context.selected_todo);
- let selectedPath: (string | number)[] = ["selected_todo"];
- const agent = jsonObject(jsonObject(context.interaction_contract)?.agent_channel);
- const work = jsonObject(agent?.work_context);
- const sources = Array.isArray(work?.sources) ? work.sources : [];
- for (const [index, value] of sources.entries()) {
- const row = jsonObject(value), content = jsonObject(row?.content);
- if (!row || !content || content.ok === false || content.read_complete === false) continue;
- const path = ["interaction_contract", "agent_channel", "work_context", "sources", index];
- if (["goal_state", "goal_acceptance"].includes(String(row.source))) reads.push(pointer(path));
- if (row.source === "selected_todo") {
- const todo = jsonObject(content.todo);
- if (todo && typeof todo.todo_id === "string" && todo.todo_id === selected?.todo_id) {
- selected = todo;
- selectedPath = [...path, "content", "todo"];
- }
- }
- }
- if (typeof selected?.todo_id === "string" && selected.todo_id) {
- const focus: JsonObject = {todo_id: selected.todo_id, ref: pointer(selectedPath)};
- const title = text(selected.title, 512) ?? text(selected.text, 512);
- if (title) {
- focus.title = title;
- coverage.push(pointer([...selectedPath, selected.title === title ? "title" : "text"]));
- }
- document.focus = focus;
- if (typeof selected.note === "string" && selected.note.trim()) {
- const ref = pointer([...selectedPath, "note"]), note = text(selected.note, 1024);
- frontier.push({ref, ...(note ? {note} : {})});
- if (note) coverage.push(ref);
- }
- }
- if (Array.isArray(agent?.required_reads) && agent.required_reads.length)
- reads.push("/interaction_contract/agent_channel/required_reads");
- // The complete capture remains the source for unknown or omitted material.
- // No note, missing field or empty navigation clears the original read contract.
- if (!document.focus && !reads.length) reads.push("");
- if (Buffer.byteLength(JSON.stringify(document)) > MAX_VIEW_BYTES)
- return {available: false};
- return {available: true, revision: canonicalAuthoritySha256(document), document};
-}
diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts
index ff8886f87c..a3ffe17e47 100644
--- a/loopx/control_plane/quota/turn_envelope.ts
+++ b/loopx/control_plane/quota/turn_envelope.ts
@@ -14,7 +14,6 @@ import { BARE_SHA256_PATTERN, ENVELOPED_SHA256_PATTERN } from "../content_digest
import {omitUnboundExploreResultWriteback, referenceExploreResultWriteback} from "../capabilities/explore_turn_context.ts";
import {prepareContextDelivery, restoreContextDelivery} from "./context_delivery.ts";
import {updateNativeContextLifecycle} from "./native_context_lifecycle.ts";
-import {prepareCompactionMemory} from "./compaction_memory.ts";
import {contextProjectionChanges, contextProjectionIdentity, contextProjectionRetainFields,
contextSourceIdentity, projectQuotaDiagnostics, referenceQuotaSummaryLanes, resolveQuotaSummaryLanes,
type ProjectionSourceValues} from "./diagnostic_projection.ts";
@@ -2762,7 +2761,6 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject {
checkedContextPresentationPlan(request), readyWriteScope(requireJsonObject(request.context, "current projection")));
}
if (operation === "native_context_lifecycle") return updateNativeContextLifecycle(request);
- if (operation === "compaction_memory") return prepareCompactionMemory(request);
if (operation === "context_recovery") return restoreContextDelivery(request, LEGACY_QUOTA_CONTEXT_FIELDS);
if (operation === "bind_capture") return bindTurnDecisionCapture(request);
if (operation === "scoped_settlement_identity") return {identity: turnEnvelopeScopedSettlementIdentity(
diff --git a/loopx/control_plane/turn_driver/compaction_memory.py b/loopx/control_plane/turn_driver/compaction_memory.py
deleted file mode 100644
index 1fb000ae7a..0000000000
--- a/loopx/control_plane/turn_driver/compaction_memory.py
+++ /dev/null
@@ -1,129 +0,0 @@
-"""Private capture IO for the TypeScript-owned experimental memory view.
-
-Native lifecycle, admission and read observation remain outside this adapter.
-The latest locator is replaceable; every emitted reference pins immutable bytes.
-"""
-from __future__ import annotations
-
-import hashlib
-import json
-import os
-from pathlib import Path
-import re
-import subprocess
-from typing import Any
-
-from .codex_context import CONTEXT_DELIVERY_SCENARIOS, _locked, _state
-from .decision_capture import (
- _decision_json, context_capture_read_command, open_regular_capture,
- read_context_capture_file, write_decision_capture,
-)
-from ..quota.turn_envelope import _turn_envelope_result
-
-_LOCATOR = "compaction-memory.json"
-_REVISION = re.compile(r"[a-f0-9]{64}\Z")
-
-
-def _read_locator(root: Path) -> dict[str, Any] | None:
- try:
- descriptor = open_regular_capture(root / _LOCATOR)
- except FileNotFoundError:
- return None
- with os.fdopen(descriptor, "rb") as stream:
- info = os.fstat(stream.fileno())
- if info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_size > 4096:
- raise ValueError("memory locator must be a bounded private file")
- locator = json.loads(stream.read(4097))
- if not isinstance(locator, dict) or set(locator) != {"path", "sha256"}:
- raise ValueError("invalid memory locator")
- return locator
-
-
-def _prepare(state: dict[str, Any], event: dict[str, Any], profile: str) -> dict[str, Any] | None:
- if (state.get("session_id") != event.get("session_id") or state.get("cwd") != event.get("cwd")
- or event.get("agent_id")):
- return None
- recovery, source = state.get("recovery"), state.get("source_recovery")
- if not isinstance(recovery, dict) or not isinstance(source, dict):
- return None
- if not all(isinstance(recovery.get(key), str) and recovery[key] for key in ("goal_id", "agent_id")):
- return None
- _, _, context = read_context_capture_file(source.get("path"), source.get("sha256"), private=True)
- # Required-view loss must not leave a supposedly recoverable memory.
- read_context_capture_file(recovery.get("path"), recovery.get("sha256"), private=True)
- scope = {key: recovery[key] for key in ("goal_id", "agent_id")}
- scope.update(session_id=event["session_id"], profile=profile)
- preparation = recovery.get("execution_preparation")
- if isinstance(preparation, dict) and preparation.get("turn_instance_id"):
- scope["turn_instance_id"] = preparation["turn_instance_id"]
- result = _turn_envelope_result("compaction_memory", context=context, scope=scope,
- source={key: source[key] for key in ("path", "sha256")},
- recovery={key: recovery[key] for key in ("path", "sha256")})
- return result if result.get("available") is True else None
-
-
-def compaction_memory_hook(
- directory: str, event: dict[str, Any], payload: dict[str, Any], *, profile: str,
-) -> dict[str, Any]:
- """Called only after explicit enablement and the ordinary native hook.
-
- No mutation of session.json, canonical work, original captures or read proofs.
- Optional failures return the ordinary hook's exact result.
- """
- name = event.get("hook_event_name")
- compact = name in ("PreCompact", "PostCompact")
- restore = name == "SessionStart" and event.get("source") == "compact"
- if not (compact or restore) or event.get("agent_id") or profile not in CONTEXT_DELIVERY_SCENARIOS:
- return payload
- try:
- with _locked(directory) as root:
- state = _state(root)
- prepared = _prepare(state, event, profile)
- if prepared is None:
- return payload
- document, revision = prepared["document"], prepared["revision"]
- if not isinstance(document, dict) or not isinstance(revision, str) or not _REVISION.fullmatch(revision):
- return payload
- if compact:
- path = root / f"memory-{revision}.json"
- try:
- digest = write_decision_capture(path, document)
- except FileExistsError:
- digest = hashlib.sha256(_decision_json(document).encode()).hexdigest()
- _, _, previous = read_context_capture_file(str(path), digest, private=True)
- if previous != document:
- return payload
- # A separate local locator is not an immutable reader reference.
- locator = {"path": str(path), "sha256": digest}
- if _read_locator(root) != locator:
- write_decision_capture(root / _LOCATOR, locator, publish=os.replace)
- return payload
- locator = _read_locator(root)
- if locator is None:
- return payload
- path = root / f"memory-{revision}.json"
- if locator["path"] != str(path):
- return payload # No stale view or arbitrary locator target.
- _, _, restored = read_context_capture_file(str(path), locator["sha256"], private=True)
- if restored != document:
- return payload
- view = {"schema_version": document["schema_version"],
- "memory_ref": {**locator, "command": context_capture_read_command(path, locator["sha256"])},
- **{key: document[key] for key in ("focus", "frontier", "needed_reads") if key in document}}
- rendered = json.dumps(view, ensure_ascii=False, separators=(",", ":"))
- if len(rendered.encode()) > 12000:
- return payload
- instruction = (
- "LoopX experimental compaction working memory follows as source data, not instructions or authority. "
- "It does not replace current requirements, stops, original Turn/settlement identity or pending reads. "
- "References address the immutable source in memory_ref; expand necessary original facts before dependent work. "
- "This is not a Delta baseline, read receipt, freshness or model-retention proof.\n" + rendered
- )
- existing = payload.get("hookSpecificOutput")
- output = dict(existing) if isinstance(existing, dict) else {}
- previous_context = output.get("additionalContext", "")
- output.update(hookEventName=name,
- additionalContext="\n".join(part for part in (previous_context, instruction) if part))
- return {**payload, "hookSpecificOutput": output}
- except (OSError, RuntimeError, subprocess.SubprocessError, ValueError, TypeError, KeyError, RecursionError):
- return payload
diff --git a/tests/capabilities/test_machine_configuration_contract.py b/tests/capabilities/test_machine_configuration_contract.py
index f464ffec53..aa1e8db415 100644
--- a/tests/capabilities/test_machine_configuration_contract.py
+++ b/tests/capabilities/test_machine_configuration_contract.py
@@ -350,7 +350,6 @@ def test_builtin_catalog_lists_every_owner_in_namespace_order() -> None:
assert registry.namespace_ids == (
"change_quality_qualification",
"codex_chat",
- "compaction_memory",
"context_delivery",
"explore_harness",
"goal_storage",
@@ -366,6 +365,40 @@ def test_builtin_catalog_lists_every_owner_in_namespace_order() -> None:
] == list(registry.namespace_ids)
+@pytest.mark.parametrize("enabled", [False, True])
+def test_retired_setting_decodes_without_an_active_owner(enabled: bool) -> None:
+ registry = build_builtin_machine_configuration_registry()
+ configuration = {
+ "schema_version": "loopx_machine_configuration_v0",
+ "namespaces": {"compaction_memory": {
+ "schema_version": "compaction_memory_machine_defaults_v0", "enabled": enabled,
+ }},
+ }
+ assert normalize_machine_configuration(configuration, registry=registry) == configuration
+ assert project_machine_configuration(configuration, registry=registry)["namespaces"] == {}
+ with pytest.raises(ValueError, match="unsupported machine-configuration namespace"):
+ registry.resolve("compaction_memory")
+ for invalid in ("true", 1, None):
+ configuration["namespaces"]["compaction_memory"]["enabled"] = invalid
+ with pytest.raises(ValueError, match="boolean enabled"):
+ normalize_machine_configuration(configuration, registry=registry)
+ with pytest.raises(ValueError, match="unsupported machine-configuration namespace"):
+ normalize_machine_configuration({
+ "schema_version": "loopx_machine_configuration_v0",
+ "namespaces": {"unregistered": {"schema_version": "future_v0"}},
+ }, registry=registry)
+
+
+def test_retired_decoders_share_the_active_namespace_reservation() -> None:
+ with pytest.raises(ValueError, match="already registered: example"):
+ _registry().register_retired("example", _normalize_example)
+ registry = MachineConfigurationRegistry().register_retired("example", _normalize_example)
+ with pytest.raises(ValueError, match="already registered: example"):
+ registry.register(_example_namespace())
+ with pytest.raises(ValueError, match="already registered: example"):
+ registry.register_deferred("example", _example_namespace)
+
+
def test_builtin_registry_still_fails_closed_on_an_invalid_stored_sibling() -> None:
configuration = {
"schema_version": "loopx_machine_configuration_v0",
diff --git a/tests/control_plane/test_compaction_memory.py b/tests/control_plane/test_compaction_memory.py
deleted file mode 100644
index 00ce2c623e..0000000000
--- a/tests/control_plane/test_compaction_memory.py
+++ /dev/null
@@ -1,233 +0,0 @@
-"""Experimental memory crosses real private capture and native-hook CLI boundaries."""
-from __future__ import annotations
-
-import json
-import os
-from pathlib import Path
-import subprocess
-import sys
-
-import pytest
-
-from loopx.capabilities.machine_configuration.builtins import build_builtin_machine_configuration_registry
-from loopx.capabilities.machine_configuration.compaction_memory import compaction_memory_enabled
-from loopx.capabilities.machine_configuration.contract import MachineConfigurationRegistry, normalize_machine_configuration
-from loopx.capabilities.machine_configuration.context_delivery import context_delivery_machine_configuration_namespace
-from loopx.control_plane.turn_driver import codex_context as native
-from loopx.control_plane.turn_driver.compaction_memory import compaction_memory_hook
-from loopx.control_plane.turn_driver.decision_capture import read_context_capture_file
-
-REPO = Path(__file__).resolve().parents[2]
-NOTE = "R1 failed isolation. R2 targeted check passed; rollback remains unverified."
-PROFILE = "codex_app_heartbeat"
-
-
-def prepare(root, monkeypatch):
- root.chmod(0o700)
- monkeypatch.chdir(root)
- monkeypatch.setenv("CODEX_THREAD_ID", "memory-session")
- event = {"session_id": "memory-session", "cwd": str(root), "hook_event_name": "SessionStart", "source": "startup"}
- native.codex_context_hook(str(root), event)
- directory = root / "source"
- directory.mkdir(mode=0o700)
- context = {"ok": True, "goal_id": "fixture", "selected_todo": {"todo_id": "work", "title": "Verify rollback", "note": NOTE},
- "requirements": "Keep the final stop; do not treat the targeted test as full acceptance."}
- native.prepare_codex_context(context, directory=str(root), capture_directory=directory,
- goal_id="fixture", agent_id="agent", surface="quota_packet", capture_id="original")
- return event, native._state(root)["source_recovery"]
-
-
-def hook(root, event):
- baseline = native.codex_context_hook(str(root), event)
- journal = (root / "session.json").read_bytes()
- result = compaction_memory_hook(str(root), event, baseline, profile=PROFILE)
- assert (root / "session.json").read_bytes() == journal, "memory may not create continuity or work evidence"
- return result
-
-
-def test_repeated_compaction_restores_exact_distinction_and_original_reader(tmp_path, monkeypatch):
- event, source = prepare(tmp_path, monkeypatch)
- original = Path(source["path"]).read_bytes()
- pre = {**event, "hook_event_name": "PreCompact", "source": None}
- assert hook(tmp_path, pre) == {}
- locator = (tmp_path / "compaction-memory.json")
- before = locator.stat().st_mtime_ns
- assert hook(tmp_path, {**pre, "hook_event_name": "PostCompact"}) == {}
- assert locator.stat().st_mtime_ns == before
- assert len(list(tmp_path.glob("memory-*.json"))) == 1
- result = hook(tmp_path, {**event, "source": "compact"})
- body = result["hookSpecificOutput"]["additionalContext"]
- assert "source data, not instructions or authority" in body
- view = json.loads(body.rsplit("\n", 1)[-1])
- assert view["frontier"] == [{"ref": "/selected_todo/note", "note": NOTE}]
- ref = view["memory_ref"]
- _, _, doc = read_context_capture_file(ref["path"], ref["sha256"], private=True)
- assert doc["binding"] == {"goal_id": "fixture", "agent_id": "agent", "session_id": "memory-session", "profile": PROFILE}
- assert doc["source"] == source
- assert Path(source["path"]).read_bytes() == original
- assert "candidate" not in native._state(tmp_path)
- assert "consumed_pointers" not in native._state(tmp_path)
- reader = subprocess.run([sys.executable, "-m", "loopx.cli", "--format", "json", "quota", "context-read",
- "--capture-file", ref["path"], "--capture-sha256", ref["sha256"]], cwd=REPO,
- capture_output=True, text=True, timeout=30)
- assert reader.returncode == 0, reader.stderr
- page = json.loads(reader.stdout)
- assert json.loads(page["content"]) == doc
-
-
-@pytest.mark.parametrize("failure", ["deleted_source", "changed_source", "public_source", "foreign_session", "child", "corrupt_locator"])
-def test_unavailable_or_foreign_memory_preserves_ordinary_recovery(tmp_path, monkeypatch, failure):
- event, source = prepare(tmp_path, monkeypatch)
- hook(tmp_path, {**event, "hook_event_name": "PreCompact"})
- restore = {**event, "source": "compact"}
- path = Path(source["path"])
- if failure == "deleted_source":
- path.unlink()
- elif failure == "changed_source":
- path.write_text('{"goal_id":"foreign"}')
- elif failure == "public_source":
- path.chmod(0o644)
- elif failure == "foreign_session":
- restore["session_id"] = "other"
- elif failure == "child":
- restore["agent_id"] = "child"
- else:
- (tmp_path / "compaction-memory.json").write_text("not json")
- baseline = {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": "Original recovery remains binding."}}
- before = (tmp_path / "session.json").read_bytes()
- assert compaction_memory_hook(str(tmp_path), restore, baseline, profile=PROFILE) is baseline
- assert (tmp_path / "session.json").read_bytes() == before
-
-
-def test_unsafe_existing_memory_is_rejected_without_following_or_repairing_it(tmp_path, monkeypatch):
- event, source = prepare(tmp_path, monkeypatch)
- pre = {**event, "hook_event_name": "PreCompact"}
- hook(tmp_path, pre)
- memory = next(tmp_path.glob("memory-*.json"))
- memory.unlink()
- memory.symlink_to(source["path"])
- original = Path(source["path"]).read_bytes()
- assert hook(tmp_path, pre) == {}
- assert hook(tmp_path, {**event, "source": "compact"})["hookSpecificOutput"]["additionalContext"].find("experimental compaction") == -1
- assert Path(source["path"]).read_bytes() == original and memory.is_symlink()
-
-
-def test_separate_namespace_is_off_by_default_and_old_scoped_context_read_is_unchanged(tmp_path):
- assert compaction_memory_enabled(tmp_path) is False
- registry = build_builtin_machine_configuration_registry()
- assert registry.resolve("compaction_memory").public_descriptor()["configuration_template"]["enabled"] is False
- context = {"schema_version": "context_delivery_machine_defaults_v1", "mode": "on", "delta_delivery": "auto"}
- payload = {"schema_version": "loopx_machine_configuration_v0", "namespaces": {
- "context_delivery": context, "compaction_memory": {"schema_version": "compaction_memory_machine_defaults_v0", "enabled": True}}}
- older = MachineConfigurationRegistry().register(context_delivery_machine_configuration_namespace())
- assert normalize_machine_configuration(payload, registry=older, namespace_ids=("context_delivery",))["namespaces"] == {"context_delivery": context}
- with pytest.raises(ValueError, match="unsupported machine-configuration namespace"):
- normalize_machine_configuration(payload, registry=older)
- path = tmp_path / "machine" / "configuration.json"
- path.parent.mkdir()
- path.write_text(json.dumps(payload))
- assert compaction_memory_enabled(tmp_path) is True
- payload["namespaces"]["compaction_memory"]["enabled"] = "true"
- path.write_text(json.dumps(payload))
- assert compaction_memory_enabled(tmp_path) is False
-
-
-@pytest.mark.parametrize("enabled,delivery,delta", [
- (False, "on", None), (True, "on", None), (True, "off", None), (True, "off", "auto"),
-])
-def test_real_hook_cli_resolves_the_persisted_independent_gate(tmp_path, monkeypatch, enabled, delivery, delta):
- event, _ = prepare(tmp_path, monkeypatch)
- runtime = tmp_path / "runtime"
- config = runtime / "machine" / "configuration.json"
- config.parent.mkdir(parents=True)
- config.write_text(json.dumps({"schema_version": "loopx_machine_configuration_v0", "namespaces": {
- "compaction_memory": {"schema_version": "compaction_memory_machine_defaults_v0", "enabled": enabled}}}))
- registry = tmp_path / "registry.json"
- registry.write_text('{"goals": []}')
- command = [sys.executable, "-m", "loopx.cli", "--registry", str(registry), "--runtime-root", str(runtime),
- "--format", "json", "quota", "context-hook", "--context-delivery", delivery, "--codex-app", "--codex-context-dir", str(tmp_path)]
- if delta is not None:
- command.extend(["--delta-delivery", delta])
- for value in ({**event, "hook_event_name": "PreCompact"}, {**event, "source": "compact"}):
- result = subprocess.run(command, input=json.dumps(value), capture_output=True, text=True,
- cwd=tmp_path, env={**os.environ, "PYTHONPATH": str(REPO)}, timeout=30)
- assert result.returncode == 0, result.stderr
- response = json.loads(result.stdout)
- active = enabled and (delivery == "on" or delta == "auto")
- assert (tmp_path / "compaction-memory.json").exists() is active
- context = response.get("hookSpecificOutput", {}).get("additionalContext", "")
- assert ("loopx_compaction_memory_v0" in context) is active
-
-
-def test_unsupported_profile_is_inert_before_any_capture_io(tmp_path):
- event = {"hook_event_name": "PreCompact"}
- baseline = {"ordinary": True}
- assert compaction_memory_hook(str(tmp_path / "absent"), event, baseline, profile="unknown") is baseline
- assert not (tmp_path / "absent").exists()
-
-
-@pytest.mark.skipif(not os.environ.get("LOOPX_NATIVE_CHECKPOINT_BIN"), reason="Explicit native Codex; loopback inference only")
-@pytest.mark.parametrize("enabled", [False, True])
-def test_actual_native_compaction_delivers_the_production_memory_view(tmp_path, enabled):
- """Only initial work data is a fixture; post-compaction delivery is production IO."""
- from tests.control_plane.codex_checkpoint_fixture import local_inference_provider
- from tests.control_plane.test_codex_context_boundary import (
- _app_server, _configure_provider, _input_text, _native_fixture, _response, _usage,
- )
-
- binary, env, workspace, home = _native_fixture(tmp_path)
- root, runtime = tmp_path / "native-context", tmp_path / "runtime"
- root.mkdir(mode=0o700)
- configuration = runtime / "machine" / "configuration.json"
- configuration.parent.mkdir(parents=True)
- configuration.write_text(json.dumps({"schema_version": "loopx_machine_configuration_v0", "namespaces": {
- "compaction_memory": {"schema_version": "compaction_memory_machine_defaults_v0", "enabled": enabled}}}))
- registry = tmp_path / "registry.json"
- registry.write_text('{"goals": []}')
- source = {"ok": True, "goal_id": "fixture", "selected_todo": {"todo_id": "work", "title": "Verify rollback", "note": NOTE},
- "requirements": "Preserve the original stop and unfinished rollback check."}
- command = [sys.executable, "-m", "loopx.cli", "--registry", str(registry), "--runtime-root", str(runtime),
- "--format", "json", "quota", "context-hook", "--context-delivery", "on", "--codex-app", "--codex-context-dir", str(root)]
- wrapper = home / "hook.py"
- wrapper.write_text(f'''import json, os, pathlib, subprocess, sys
-event = json.load(sys.stdin)
-env = {{**os.environ, "PYTHONPATH": {str(REPO)!r}, "CODEX_THREAD_ID": event["session_id"]}}
-result = subprocess.run({command!r}, input=json.dumps(event), capture_output=True, text=True, env=env, timeout=20)
-assert result.returncode == 0, result.stderr
-payload = json.loads(result.stdout)
-if event["hook_event_name"] == "SessionStart" and event.get("source") == "startup":
- os.environ.update(env)
- sys.path.insert(0, {str(REPO)!r})
- from loopx.control_plane.turn_driver import codex_context as native
- directory = pathlib.Path({str(root / 'source')!r})
- directory.mkdir(mode=0o700)
- native.prepare_codex_context({source!r}, directory={str(root)!r}, capture_directory=directory,
- goal_id="fixture", agent_id="agent", surface="quota_packet", capture_id="original")
- payload = {{"hookSpecificOutput": {{"hookEventName": "SessionStart",
- "additionalContext": "Synthetic initial work data: " + json.dumps({source!r})}}}}
-print(json.dumps(payload))
-''')
- import shlex
-
- handler = {"type": "command", "command": shlex.join([sys.executable, str(wrapper)]), "timeout": 10}
- # Keep production defaults; do not bypass a lossy native output limit.
- (home / "hooks.json").write_text(json.dumps({"hooks": {
- name: [{"hooks": [handler]}] for name in native.CONTEXT_LIFECYCLE_HOOKS}}))
- with local_inference_provider(_response, _usage) as (url, calls, requests):
- _configure_provider(home, url)
- _app_server(binary, env, workspace, home, True, turn_timeout_sec=60, allow_managed_hooks=True)
- assert len(calls) == 4
- first, warm, _, restored = map(_input_text, requests)
- assert NOTE in first and NOTE in warm
- if enabled:
- assert NOTE in restored and "loopx_compaction_memory_v0" in restored
- locator = json.loads((root / "compaction-memory.json").read_text())
- _, _, document = read_context_capture_file(locator["path"], locator["sha256"], private=True)
- view = {"schema_version": document["schema_version"], "memory_ref": {
- **locator, "command": native.context_capture_read_command(Path(locator["path"]), locator["sha256"])},
- **{key: document[key] for key in ("focus", "frontier", "needed_reads") if key in document}}
- # Exact complete short structure, not just a head/tail preview or file.
- assert json.dumps(view, ensure_ascii=False, separators=(",", ":")) in restored
- else:
- assert NOTE not in restored and not list(root.glob("memory-*.json"))
- assert json.loads((root / "source" / "projection.json").read_text()) == source
diff --git a/tests/control_plane/test_compaction_memory_retirement.py b/tests/control_plane/test_compaction_memory_retirement.py
new file mode 100644
index 0000000000..9506bc84d3
--- /dev/null
+++ b/tests/control_plane/test_compaction_memory_retirement.py
@@ -0,0 +1,138 @@
+"""Retired settings cannot revive compaction work; original recovery stays intact."""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+from loopx.control_plane.turn_driver import codex_context as native
+
+REPO = Path(__file__).resolve().parents[2]
+NOTE = "R1 failed isolation. R2 targeted check passed; rollback remains unverified."
+
+
+def test_retired_memory_reference_remains_readable_with_the_original_digest(tmp_path):
+ from loopx.control_plane.turn_driver.decision_capture import write_decision_capture
+
+ document = {"schema_version": "loopx_compaction_memory_v0",
+ "binding": {"goal_id": "fixture", "agent_id": "agent", "session_id": "original-session", "profile": "codex_app_heartbeat"},
+ "frontier": [{"ref": "/selected_todo/note", "note": NOTE}]}
+ memory = tmp_path / "memory-original.json"
+ digest = write_decision_capture(memory, document)
+ before = memory.read_bytes()
+ command = [sys.executable, "-m", "loopx.cli", "--format", "json", "quota", "context-read",
+ "--capture-file", str(memory), "--capture-sha256", digest]
+ result = subprocess.run(command, cwd=REPO, capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, result.stderr
+ assert json.loads(json.loads(result.stdout)["content"]) == document
+ assert memory.read_bytes() == before
+ rejected = subprocess.run([*command[:-1], "0" * 64], cwd=REPO, capture_output=True, text=True, timeout=30)
+ assert rejected.returncode != 0
+ assert memory.read_bytes() == before
+
+
+@pytest.mark.parametrize("delivery,delta", [("on", None), ("off", None), ("off", "auto")])
+def test_real_hook_cli_has_parity_with_absent_false_and_true_retired_values(tmp_path, monkeypatch, delivery, delta):
+ monkeypatch.setenv("CODEX_THREAD_ID", "recovery-session")
+ monkeypatch.chdir(tmp_path)
+ tmp_path.chmod(0o700)
+ event = {"session_id": "recovery-session", "cwd": str(tmp_path), "hook_event_name": "SessionStart", "source": "startup"}
+ native.codex_context_hook(str(tmp_path), event)
+ source = tmp_path / "source"
+ source.mkdir(mode=0o700)
+ context = {"ok": True, "goal_id": "fixture", "selected_todo": {"todo_id": "work", "title": "Verify rollback", "note": NOTE}}
+ native.prepare_codex_context(context, directory=str(tmp_path), capture_directory=source,
+ goal_id="fixture", agent_id="agent", surface="quota_packet", capture_id="original")
+ capture = (source / "projection.json").read_bytes()
+ journal = tmp_path / "session.json"
+ initial = journal.read_bytes()
+ runtime = tmp_path / "runtime"
+ configuration = runtime / "machine" / "configuration.json"
+ configuration.parent.mkdir(parents=True)
+ registry = tmp_path / "registry.json"
+ registry.write_text('{"goals": []}')
+ command = [sys.executable, "-m", "loopx.cli", "--registry", str(registry), "--runtime-root", str(runtime),
+ "--format", "json", "quota", "context-hook", "--context-delivery", delivery, "--codex-app", "--codex-context-dir", str(tmp_path)]
+ if delta is not None:
+ command.extend(["--delta-delivery", delta])
+ baseline = None
+ for enabled in (None, False, True):
+ journal.write_bytes(initial)
+ if enabled is not None:
+ configuration.write_text(json.dumps({"schema_version": "loopx_machine_configuration_v0", "namespaces": {
+ "compaction_memory": {"schema_version": "compaction_memory_machine_defaults_v0", "enabled": enabled}}}))
+ outputs = []
+ for hook_event in ({**event, "hook_event_name": "PreCompact"}, {**event, "hook_event_name": "PostCompact"}, {**event, "source": "compact"}):
+ result = subprocess.run(command, input=json.dumps(hook_event), capture_output=True, text=True,
+ cwd=tmp_path, env={**os.environ, "PYTHONPATH": str(REPO)}, timeout=30)
+ assert result.returncode == 0, result.stderr
+ outputs.append(json.loads(result.stdout))
+ if baseline is None:
+ baseline = outputs
+ assert outputs == baseline
+ assert not (tmp_path / "compaction-memory.json").exists()
+ assert not list(tmp_path.glob("memory-*.json"))
+ assert (source / "projection.json").read_bytes() == capture
+
+
+@pytest.mark.skipif(not os.environ.get("LOOPX_NATIVE_CHECKPOINT_BIN"), reason="Explicit native Codex; loopback inference only")
+@pytest.mark.parametrize("enabled", [False, True])
+def test_actual_native_compaction_ignores_retired_opt_in(tmp_path, enabled):
+ """Only initial work data is a fixture; post-compaction delivery is production IO."""
+ from tests.control_plane.codex_checkpoint_fixture import local_inference_provider
+ from tests.control_plane.test_codex_context_boundary import (
+ _app_server, _configure_provider, _input_text, _native_fixture, _response, _usage,
+ )
+
+ binary, env, workspace, home = _native_fixture(tmp_path)
+ root, runtime = tmp_path / "native-context", tmp_path / "runtime"
+ root.mkdir(mode=0o700)
+ configuration = runtime / "machine" / "configuration.json"
+ configuration.parent.mkdir(parents=True)
+ configuration.write_text(json.dumps({"schema_version": "loopx_machine_configuration_v0", "namespaces": {
+ "compaction_memory": {"schema_version": "compaction_memory_machine_defaults_v0", "enabled": enabled}}}))
+ registry = tmp_path / "registry.json"
+ registry.write_text('{"goals": []}')
+ source = {"ok": True, "goal_id": "fixture", "selected_todo": {"todo_id": "work", "title": "Verify rollback", "note": NOTE},
+ "requirements": "Preserve the original stop and unfinished rollback check."}
+ command = [sys.executable, "-m", "loopx.cli", "--registry", str(registry), "--runtime-root", str(runtime),
+ "--format", "json", "quota", "context-hook", "--context-delivery", "on", "--codex-app", "--codex-context-dir", str(root)]
+ wrapper = home / "hook.py"
+ wrapper.write_text(f'''import json, os, pathlib, subprocess, sys
+event = json.load(sys.stdin)
+env = {{**os.environ, "PYTHONPATH": {str(REPO)!r}, "CODEX_THREAD_ID": event["session_id"]}}
+result = subprocess.run({command!r}, input=json.dumps(event), capture_output=True, text=True, env=env, timeout=20)
+assert result.returncode == 0, result.stderr
+payload = json.loads(result.stdout)
+if event["hook_event_name"] == "SessionStart" and event.get("source") == "startup":
+ os.environ.update(env)
+ sys.path.insert(0, {str(REPO)!r})
+ from loopx.control_plane.turn_driver import codex_context as native
+ directory = pathlib.Path({str(root / 'source')!r})
+ directory.mkdir(mode=0o700)
+ native.prepare_codex_context({source!r}, directory={str(root)!r}, capture_directory=directory,
+ goal_id="fixture", agent_id="agent", surface="quota_packet", capture_id="original")
+ payload = {{"hookSpecificOutput": {{"hookEventName": "SessionStart",
+ "additionalContext": "Synthetic initial work data: " + json.dumps({source!r})}}}}
+print(json.dumps(payload))
+''')
+ import shlex
+
+ handler = {"type": "command", "command": shlex.join([sys.executable, str(wrapper)]), "timeout": 10}
+ # Keep production defaults; do not bypass a lossy native output limit.
+ (home / "hooks.json").write_text(json.dumps({"hooks": {
+ name: [{"hooks": [handler]}] for name in native.CONTEXT_LIFECYCLE_HOOKS}}))
+ with local_inference_provider(_response, _usage) as (url, calls, requests):
+ _configure_provider(home, url)
+ _app_server(binary, env, workspace, home, True, turn_timeout_sec=60, allow_managed_hooks=True)
+ assert len(calls) == 4
+ first, warm, _, restored = map(_input_text, requests)
+ assert NOTE in first and NOTE in warm
+ assert NOTE not in restored and "loopx_compaction_memory_v0" not in restored
+ assert not (root / "compaction-memory.json").exists()
+ assert not list(root.glob("memory-*.json"))
+ assert json.loads((root / "source" / "projection.json").read_text()) == source
diff --git a/tests/control_plane_ts/compaction_memory.test.ts b/tests/control_plane_ts/compaction_memory.test.ts
deleted file mode 100644
index 0fbc3f91ff..0000000000
--- a/tests/control_plane_ts/compaction_memory.test.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-import {prepareCompactionMemory} from "../../loopx/control_plane/quota/compaction_memory.ts";
-
-const scope = {goal_id: "goal", agent_id: "agent", session_id: "native", profile: "codex_app_heartbeat"};
-const source = {path: "/runtime/original.json", sha256: "a".repeat(64)};
-const recovery = {path: "/runtime/required.json", sha256: "b".repeat(64)};
-const note = "R1 failed isolation. R2 passed the targeted test; rollback remains unverified.";
-const context = {goal_id: "goal", selected_todo: {todo_id: "work", title: "Check isolation", note},
- interaction_contract: {agent_channel: {required_reads: ["Read the unchanged original requirements."]}},
- unknown_evidence: {failed: true, instruction: "Do not infer acceptance."}};
-
-test("memory preserves sourced negative distinctions without editing the source or inventing authority", () => {
- const before = structuredClone(context);
- const result = prepareCompactionMemory({context, scope, source, recovery});
- assert.equal(result.available, true);
- const doc = result.document as Record;
- assert.deepEqual(doc.frontier, [{ref: "/selected_todo/note", note}]);
- assert.deepEqual(doc.coverage, ["/selected_todo/title", "/selected_todo/note"]);
- assert.deepEqual(doc.needed_reads, ["/interaction_contract/agent_channel/required_reads"]);
- assert.deepEqual(doc.binding, scope);
- assert.equal(doc.binding.context_epoch, undefined);
- assert.equal(doc.binding.turn_instance_id, undefined);
- assert.equal(doc.complete, undefined);
- assert.equal(doc.authority, undefined);
- assert.deepEqual(context, before);
- assert.deepEqual(prepareCompactionMemory({context, scope, source, recovery}), result);
-});
-
-test("long notes remain exact original pointers, never silently truncated memories", () => {
- const result = prepareCompactionMemory({context: {...context, selected_todo: {...context.selected_todo, note: note.repeat(80)}},
- scope, source, recovery});
- const doc = result.document as Record;
- assert.deepEqual(doc.frontier, [{ref: "/selected_todo/note"}]);
- assert.deepEqual(doc.coverage, ["/selected_todo/title"]);
- assert.equal(doc.source.sha256, source.sha256);
-});
-
-test("scope and exact source changes cannot reuse an old memory revision", () => {
- for (const patch of [{goal_id: "foreign"}, {agent_id: "foreign"}])
- assert.throws(() => prepareCompactionMemory({context: {...context, ...patch}, scope, source, recovery}));
- const initial = prepareCompactionMemory({context, scope, source, recovery});
- const later = prepareCompactionMemory({context, scope, source: {...source, sha256: "c".repeat(64)}, recovery});
- assert.notEqual(initial.revision, later.revision);
- const withTurn = prepareCompactionMemory({context, scope: {...scope, turn_instance_id: "original"}, source, recovery});
- assert.equal((withTurn.document as Record).binding.turn_instance_id, "original");
-});
-
-test("canonical selected note uses its own exact location; a foreign work row is ignored", () => {
- const todo = {todo_id: "work", title: "Verify rollback", note};
- const row = {source: "selected_todo", content: {ok: true, todo}};
- const result = prepareCompactionMemory({context: {...context,
- interaction_contract: {agent_channel: {work_context: {sources: [row]}}}}, scope, source, recovery});
- const doc = result.document as Record;
- assert.deepEqual(doc.frontier, [{ref: "/interaction_contract/agent_channel/work_context/sources/0/content/todo/note", note}]);
- const other = prepareCompactionMemory({context: {...context,
- interaction_contract: {agent_channel: {work_context: {sources: [{...row, content: {todo: {...todo, todo_id: "other"}}}]}}}},
- scope, source, recovery});
- assert.equal((other.document as Record).frontier[0].ref, "/selected_todo/note");
-});
diff --git a/tests/control_plane_ts/turn_envelope.test.ts b/tests/control_plane_ts/turn_envelope.test.ts
index 022fa8ad54..b60c8be8bd 100644
--- a/tests/control_plane_ts/turn_envelope.test.ts
+++ b/tests/control_plane_ts/turn_envelope.test.ts
@@ -1533,12 +1533,14 @@ test("signature document fails closed to the canonical signed dimensions", () =>
});
test("unsupported facade operation is rejected", () => {
- assert.throws(
- () => evaluateTurnEnvelope({ operation: "leaf_helper" }),
- (error: unknown) =>
- error instanceof EffectRuntimeRequestError &&
- error.message === "turn envelope operation is unsupported",
- );
+ for (const operation of ["leaf_helper", "compaction_memory"]) {
+ assert.throws(
+ () => evaluateTurnEnvelope({ operation }),
+ (error: unknown) =>
+ error instanceof EffectRuntimeRequestError &&
+ error.message === "turn envelope operation is unsupported",
+ );
+ }
});
test("transaction boundary rejects malformed prepared facts", () => {
diff --git a/tests/test_chat_machine_configuration_api.py b/tests/test_chat_machine_configuration_api.py
index ec76b75d6d..637008efa0 100644
--- a/tests/test_chat_machine_configuration_api.py
+++ b/tests/test_chat_machine_configuration_api.py
@@ -341,7 +341,6 @@ def test_inspection_lists_registered_namespaces_without_local_refs(
assert response["available_namespaces"] == [
"change_quality_qualification",
"codex_chat",
- "compaction_memory",
"context_delivery",
"explore_harness",
"goal_storage",
@@ -448,7 +447,7 @@ def test_machine_catalog_discovers_goal_features_without_granting_machine_writes
)
# Machine-only capabilities are the ones a Goal cannot override: the
# manager profile, native host defaults, steward executor and storage target.
- assert set(machine) - {"manager_runtime", "steward_executor", "goal_storage", "codex_chat", "context_delivery", "compaction_memory"} == {
+ assert set(machine) - {"manager_runtime", "steward_executor", "goal_storage", "codex_chat", "context_delivery"} == {
feature["feature_id"] for feature in goal["features"]
}
assert machine["pull_request_review"]["available_scopes"] == ["machine", "goal"]
@@ -464,7 +463,7 @@ def test_machine_catalog_discovers_goal_features_without_granting_machine_writes
for capability_id, item in machine.items():
assert "current" not in item
assert "commands" not in item
- if capability_id in {"manager_runtime", "steward_executor", "goal_storage", "codex_chat", "context_delivery", "compaction_memory"}:
+ if capability_id in {"manager_runtime", "steward_executor", "goal_storage", "codex_chat", "context_delivery"}:
assert item["available_scopes"] == ["machine"]
assert item["machine_namespace"] == capability_id
assert item["configuration_editor"]["writable_scopes"] == ["machine"]
@@ -558,6 +557,55 @@ def test_preview_apply_inspect_and_rollback_are_revision_locked(tmp_path: Path)
assert final_handler.responses[0]["status"] == "absent"
+@pytest.mark.parametrize("enabled", [False, True])
+def test_retired_setting_preserves_inspection_sibling_update_and_rollback(tmp_path: Path, enabled: bool) -> None:
+ from loopx.capabilities.machine_configuration.builtins import build_builtin_machine_configuration_registry
+
+ configuration = _configuration()
+ configuration["namespaces"]["compaction_memory"] = {
+ "schema_version": "compaction_memory_machine_defaults_v0", "enabled": enabled,
+ }
+ path = tmp_path / "machine" / "configuration.json"
+ path.parent.mkdir()
+ path.write_text(json.dumps(configuration))
+ before = path.read_bytes()
+ handler = _Handler(tmp_path)
+ handler._machine_configuration_inspect()
+ inspection = handler.responses[0]
+ assert inspection["status"] == "configured"
+ assert "compaction_memory" not in inspection["available_namespaces"]
+ assert "compaction_memory" not in inspection["machine_configuration"]["namespaces"]
+ assert all(row["capability_id"] != "compaction_memory" for row in inspection["capability_catalog"]["capabilities"])
+ assert path.read_bytes() == before
+
+ rejected = _Handler(tmp_path, {"namespace": "compaction_memory", "namespace_configuration": configuration["namespaces"]["compaction_memory"]})
+ rejected._machine_configuration_update(execute=True)
+ assert rejected.responses[0]["ok"] is False
+ assert path.read_bytes() == before
+
+ update = {"namespace": "periodic_report", "namespace_configuration": _namespace(enabled=False)}
+ preview = _Handler(tmp_path, update)
+ preview._machine_configuration_update(execute=False)
+ plan = preview.responses[0]
+ assert plan["changed_namespaces"] == ["periodic_report"]
+ apply = _Handler(tmp_path, {**update, "expected_plan_revision": plan["plan_revision"]})
+ apply._machine_configuration_update(execute=True)
+ receipt = apply.responses[0]
+ assert receipt["readback_verified"] is True
+ registry = build_builtin_machine_configuration_registry()
+ saved = read_machine_configuration(tmp_path, registry=registry)
+ assert saved["namespaces"]["compaction_memory"] == configuration["namespaces"]["compaction_memory"]
+ assert saved["namespaces"]["periodic_report"]["enabled"] is False
+
+ rollback_preview = _Handler(tmp_path, {"transaction_id": receipt["transaction_id"], "execute": False})
+ rollback_preview._machine_configuration_rollback()
+ rollback = _Handler(tmp_path, {"transaction_id": receipt["transaction_id"], "execute": True,
+ "expected_plan_revision": rollback_preview.responses[0]["plan_revision"]})
+ rollback._machine_configuration_rollback()
+ assert rollback.responses[0]["readback_verified"] is True
+ assert read_machine_configuration(tmp_path, registry=registry) == configuration
+
+
def test_the_steward_executor_namespace_is_editable_and_read_back(
tmp_path: Path,
) -> None: