@staix/agent-hub 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +12 -11
  3. package/docs/adding-an-ai-tool.md +1 -0
  4. package/docs/agent-notes/adapters.md +35 -6
  5. package/docs/agent-notes/budget.md +2 -1
  6. package/docs/agent-notes/daemon.md +5 -1
  7. package/docs/agent-notes/local-worker.md +1 -1
  8. package/docs/agent-notes/security-review.md +3 -2
  9. package/docs/agent-notes/tasks.md +6 -2
  10. package/docs/agent-notes/tests.md +4 -3
  11. package/docs/design/adapters.md +20 -2
  12. package/docs/design/agent-hub-architecture.md +12 -0
  13. package/docs/design/agent-hub.md +1 -1
  14. package/docs/design/cli-output.md +2 -0
  15. package/docs/design/roadmap.md +158 -4
  16. package/docs/design/supervision.md +21 -1
  17. package/docs/design/task-board.md +32 -4
  18. package/docs/dogfood.md +28 -4
  19. package/docs/events.md +7 -3
  20. package/docs/influences.md +7 -0
  21. package/docs/memory.md +4 -4
  22. package/docs/operations.md +151 -36
  23. package/docs/quickstart.md +16 -4
  24. package/docs/research.md +16 -0
  25. package/docs/roadmap.json +4 -0
  26. package/docs/roadmap.md +9 -0
  27. package/docs/sdlc.md +15 -3
  28. package/docs/security.md +9 -7
  29. package/docs/smoke.md +1 -1
  30. package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
  31. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  32. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  33. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  34. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  35. package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
  36. package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
  37. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  38. package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
  39. package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
  40. package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
  41. package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
  42. package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
  43. package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
  44. package/docs/verification/2026-11-23-0.46.0.md +44 -0
  45. package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
  46. package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
  47. package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
  48. package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
  49. package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
  50. package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
  51. package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
  52. package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
  53. package/docs/verified.json +33 -27
  54. package/package.json +3 -2
  55. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  56. package/plugins/agent-hub/kimi-hook.js +4743 -4048
  57. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  58. package/plugins/agent-hub/server.js +1641 -1265
  59. package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
  60. package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
  61. package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
  62. package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
  63. package/scripts/check-docs.mjs +9 -1
  64. package/src/adapters/acp.ts +11 -1
  65. package/src/adapters/claude-channel.ts +2 -1
  66. package/src/adapters/compat.ts +15 -14
  67. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  68. package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
  69. package/src/adapters/definitions/native-cli-doctor.ts +8 -5
  70. package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
  71. package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
  72. package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
  73. package/src/adapters/definitions/native-cli-skills.ts +29 -0
  74. package/src/adapters/definitions/native-context.ts +10 -0
  75. package/src/adapters/jcode.ts +10 -0
  76. package/src/adapters/local-worker.ts +3 -2
  77. package/src/adapters/pi.ts +15 -4
  78. package/src/cli/claude-profile-hook.ts +40 -3
  79. package/src/cli/console-state.ts +58 -27
  80. package/src/cli/console-usage.ts +5 -3
  81. package/src/cli/console.ts +35 -4
  82. package/src/cli/help.ts +17 -10
  83. package/src/cli/identity.ts +4 -2
  84. package/src/cli/instruction-hook.ts +28 -0
  85. package/src/cli/jcode-mcp.ts +2 -1
  86. package/src/cli/main.js +8 -0
  87. package/src/cli/main.ts +149 -23
  88. package/src/cli/output-standard.ts +3 -55
  89. package/src/cli/output.ts +8 -2
  90. package/src/cli/recovery-package.ts +62 -13
  91. package/src/cli/roadmap-write.ts +59 -0
  92. package/src/cli/roadmap.ts +115 -4
  93. package/src/cli/sdlc-output.ts +4 -0
  94. package/src/cli/setup-homes.ts +1 -0
  95. package/src/cli/setup.ts +1 -1
  96. package/src/cli/skills-install.ts +463 -0
  97. package/src/cli/task-output.ts +1 -1
  98. package/src/cli/upgrade-presentation-flags.ts +1 -1
  99. package/src/cli/upgrade-runtime.ts +10 -6
  100. package/src/hub/agent-mem-range.ts +43 -0
  101. package/src/hub/board.ts +144 -5
  102. package/src/hub/budget-projection.ts +99 -0
  103. package/src/hub/check-runner.ts +25 -1
  104. package/src/hub/claude-launch-proof.ts +5 -1
  105. package/src/hub/conductor.ts +8 -3
  106. package/src/hub/config-apply.ts +6 -3
  107. package/src/hub/config-tier.ts +1 -1
  108. package/src/hub/config-trust.ts +1 -1
  109. package/src/hub/context-window.ts +1 -1
  110. package/src/hub/control-client.ts +9 -2
  111. package/src/hub/cost-governance.ts +11 -7
  112. package/src/hub/daemon.ts +707 -53
  113. package/src/hub/dogfood-read.ts +4 -2
  114. package/src/hub/edit-guard.ts +100 -0
  115. package/src/hub/events.ts +80 -9
  116. package/src/hub/execution-budget.ts +29 -8
  117. package/src/hub/facts.ts +57 -4
  118. package/src/hub/hub-tools.ts +3 -1
  119. package/src/hub/inference.ts +1 -1
  120. package/src/hub/instances.ts +10 -1
  121. package/src/hub/instructed-exact.ts +95 -0
  122. package/src/hub/instructed-intent.ts +64 -0
  123. package/src/hub/instructed-ipc.ts +33 -0
  124. package/src/hub/instructed-runtime.ts +19 -0
  125. package/src/hub/instruction-receipt.ts +218 -0
  126. package/src/hub/lifecycle.ts +6 -1
  127. package/src/hub/log-rotation.ts +130 -0
  128. package/src/hub/manager.ts +46 -3
  129. package/src/hub/memory-profile.ts +137 -21
  130. package/src/hub/no-writes.ts +1 -0
  131. package/src/hub/operational-authority.ts +3 -2
  132. package/src/hub/operational-settings.ts +2 -2
  133. package/src/hub/recovery-store.ts +49 -21
  134. package/src/hub/registry.ts +1 -1
  135. package/src/hub/research-experiments.ts +132 -0
  136. package/src/hub/research-quality.ts +8 -2
  137. package/src/hub/research-record.ts +35 -0
  138. package/src/hub/research.ts +128 -28
  139. package/src/hub/roadmap-check.ts +65 -0
  140. package/src/hub/roadmap-decompose.ts +139 -0
  141. package/src/hub/roadmap-export.ts +27 -0
  142. package/src/hub/roadmap-sync.ts +97 -0
  143. package/src/hub/roadmap.ts +59 -1
  144. package/src/hub/routing.ts +18 -1
  145. package/src/hub/runtime-capture-prune.ts +2 -1
  146. package/src/hub/sdlc-branch-ci.ts +128 -0
  147. package/src/hub/sdlc-merge.ts +6 -3
  148. package/src/hub/sdlc-metrics.ts +19 -5
  149. package/src/hub/sdlc.ts +73 -5
  150. package/src/hub/settings.ts +3 -1
  151. package/src/hub/snapshots.ts +13 -1
  152. package/src/hub/startup-event-seeds.ts +21 -15
  153. package/src/hub/startup-timing.ts +3 -1
  154. package/src/hub/supervision-proposals.ts +10 -2
  155. package/src/hub/supervision-rules.ts +26 -3
  156. package/src/hub/supervision.ts +7 -0
  157. package/src/hub/task-pr.ts +47 -0
  158. package/src/hub/task-worktree.ts +18 -11
  159. package/src/hub/tasks.ts +694 -44
  160. package/src/hub/ui.ts +6 -2
  161. package/src/hub/usage-rollup.ts +77 -22
  162. package/src/local/tools.ts +13 -1
  163. package/src/memory/client.ts +3 -2
  164. package/src/pi/extension.ts +15 -3
  165. package/src/pi/tool-receipts.ts +26 -0
  166. package/src/ui/index.html +342 -8
  167. package/src/ui/plugin.ts +6 -2
  168. package/src/ui/roadmap-model.ts +70 -0
@@ -85,10 +85,50 @@ function removeManifest(home: string, instanceId: string) {
85
85
  rmSync(files(home).token, { force: true });
86
86
  }
87
87
 
88
+ /** #1483 R5: one project's public roadmap summary for `ahub ui --all`. `partial` means the hub could not answer, so the counts are a floor, not a zero. */
89
+ export interface ProjectRoadmapSummary { total: number; byHorizon: Record<string, number>; byState: Record<string, number>; drift: number; partial: boolean }
90
+ /** Lanes and states come from the milestone rows' own fields, so an unknown value is counted under its own name instead of dropped. */
91
+ export function roadmapSummary(milestones: readonly Record<string, unknown>[], drift = 0): ProjectRoadmapSummary {
92
+ const byHorizon: Record<string, number> = {}, byState: Record<string, number> = {};
93
+ for (const milestone of milestones) {
94
+ const horizon = String(milestone.horizon ?? "later"), state = String(milestone.state ?? "proposed");
95
+ byHorizon[horizon] = (byHorizon[horizon] ?? 0) + 1;
96
+ byState[state] = (byState[state] ?? 0) + 1;
97
+ }
98
+ return { total: milestones.length, byHorizon, byState, drift, partial: false };
99
+ }
100
+
88
101
  /** The manager's project listing and forwarding (#935): shared by `ahub ui --all` and the acon plugin, never widened for either. */
89
- export function projectConsole(options: { registry: Registry; lifecycle: Lifecycle; home: string; stopping?: () => boolean; forwardTimeoutMs?: ManagerOptions["forwardTimeoutMs"]; afterStart?: ManagerOptions["afterStart"] }) {
102
+ export function projectConsole(options: { registry: Registry; lifecycle: Lifecycle; home: string; stopping?: () => boolean; forwardTimeoutMs?: ManagerOptions["forwardTimeoutMs"]; afterStart?: ManagerOptions["afterStart"]; roadmap?: boolean }) {
90
103
  const { registry, lifecycle, home } = options;
91
104
  const aliases = new Map<string, { at: number; names: string[] }>();
105
+ // #1483 R5: a project's roadmap is read once a minute, because the manager's page polls this listing every three seconds.
106
+ // It is opt-in, so the acon plugin's listing pays nothing for a field it does not show, and the whole read is bounded.
107
+ const roadmaps = new Map<string, { at: number; instanceId: string | null; summary: ProjectRoadmapSummary }>();
108
+ const roadmap = async (project: { id: string; root: string; stateDir: string }, instanceId: string | null): Promise<ProjectRoadmapSummary> => {
109
+ const cached = roadmaps.get(project.id);
110
+ if (cached && cached.instanceId === instanceId && Date.now() - cached.at < 60_000) return cached.summary;
111
+ const unavailable: ProjectRoadmapSummary = { total: 0, byHorizon: {}, byState: {}, drift: 0, partial: true };
112
+ let summary = unavailable, client: ControlClient | undefined;
113
+ try {
114
+ client = await bounded(ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root }, 3000), 4000);
115
+ const listed = await bounded(client.request({ t: "task", op: "hub_roadmap_list", args: {} }, 5000), 6000);
116
+ if (listed && listed.ok !== false) {
117
+ let report: any;
118
+ try { report = JSON.parse(String(listed.text ?? "")); } catch { report = undefined; }
119
+ if (Array.isArray(report?.milestones)) {
120
+ // The drift read is the hub's own findings count; a refusal only drops the count, never the milestones.
121
+ const checked = await bounded(client.request({ t: "task", op: "hub_roadmap_check", args: {} }, 15_000), 16_000).catch(() => undefined);
122
+ let drift = 0;
123
+ if (checked && checked.ok !== false) { try { const findings = JSON.parse(String(checked.text ?? ""))?.findings; drift = Array.isArray(findings) ? findings.length : 0; } catch { drift = 0; } }
124
+ summary = roadmapSummary(report.milestones, drift);
125
+ }
126
+ }
127
+ } catch { summary = unavailable; }
128
+ finally { client?.close(); }
129
+ roadmaps.set(project.id, { at: Date.now(), instanceId, summary });
130
+ return summary;
131
+ };
92
132
  const list = async () => {
93
133
  const projects = registry.list();
94
134
  for (const p of projects) if (!aliases.has(p.id) || Date.now() - aliases.get(p.id)!.at > 60_000) {
@@ -100,9 +140,12 @@ export function projectConsole(options: { registry: Registry; lifecycle: Lifecyc
100
140
  catch (error) { result = { state: "unavailable", error: safeError(error) }; }
101
141
  const names = aliases.get(project.id)!.names;
102
142
  const shared = projects.some((other) => other.id !== project.id && aliases.get(other.id)!.names.some((name) => names.includes(name)));
143
+ const instanceId = result.state === "running" ? result.status?.instanceId ?? null : null;
103
144
  return { id: project.id, root: project.root, state: result.state,
104
- instanceId: result.state === "running" ? result.status?.instanceId ?? null : null,
145
+ instanceId,
105
146
  peers: result.status?.peers ?? {}, tasks: result.status?.tasks ?? {},
147
+ // #1483 R5: a running project answers with its own public roadmap summary; a stopped one has none to read.
148
+ ...(instanceId && options.roadmap ? { roadmap: await roadmap(project, instanceId) } : {}),
106
149
  ...(shared ? { warning: "Native memory aliases are shared with another registered project." } : {}),
107
150
  ...(result.error ? { error: result.error } : {}) };
108
151
  }));
@@ -327,7 +370,7 @@ export async function startManager(options: ManagerOptions = {}): Promise<Manage
327
370
  try { publicationRegistry.runtimeCaptureLocked(() => {
328
371
  assertExecutableRuntimeRoot(realPath(resolve(import.meta.dir, "../..")));
329
372
  owner = claimOwner(f.owner, instanceId, pidSignature);
330
- const { list, act } = projectConsole({ registry, lifecycle, home, stopping: () => stopping, forwardTimeoutMs: options.forwardTimeoutMs, ...(options.afterStart && !options.liveTest ? { afterStart: options.afterStart } : {}) });
373
+ const { list, act } = projectConsole({ registry, lifecycle, home, roadmap: true, stopping: () => stopping, forwardTimeoutMs: options.forwardTimeoutMs, ...(options.afterStart && !options.liveTest ? { afterStart: options.afterStart } : {}) });
331
374
  dashboard = startDashboard({ projects: list, snapshot: (after, input = {}) => act({ ...input, action: "snapshot", after }), action: act });
332
375
  server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 1024,
333
376
  async fetch(req) {
@@ -1,12 +1,13 @@
1
- import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";
2
3
  import { basename, dirname, join, resolve } from "node:path";
3
4
  import {
4
- CandidateStore, MemoryStore, realPath, memoryHome, memoryProjectKey, openShardStore, readShardedSelection, resolveAlias, resolveProfile, resolveShardProfile,
5
+ CandidateStore, MemoryStore, aliasLogPath, realPath, memoryHome, memoryProjectKey, openShardStore, readShardedSelection, resolveAlias, resolveProfile,
6
+ resolveShardProfile, shardKeyHash,
5
7
  type BoundProfile, type ProfileInput, type StoreOptions,
6
8
  } from "@staix/agent-mem";
7
- import packageJson from "../../package.json";
8
-
9
- const EXPECTED_AGENT_MEM_VERSION = packageJson.dependencies["@staix/agent-mem"];
9
+ import * as agentMemExports from "@staix/agent-mem";
10
+ import { AGENT_MEM_HOST_API_RANGE, AGENT_MEM_RANGE, agentMemHostApiOk, agentMemVersionInRange } from "./agent-mem-range.ts";
10
11
 
11
12
  /**
12
13
  * Whether a curated store directory holds a derived index. agent-mem names the file per index version (`index.db` through 0.24.0, `index-v4.db` from 0.25.0, a later release its own), and
@@ -16,15 +17,17 @@ export function memoryIndexExists(memoryDir: string): boolean {
16
17
  try { return readdirSync(memoryDir).some(name => /^index(-v\d+)?\.db$/.test(name)); } catch { return false; }
17
18
  }
18
19
 
19
- /** Validate metadata located through the actual imported entry, never the hub pin alone. */
20
- export function assertAgentMemVersion(metadata: unknown, expectedVersion = EXPECTED_AGENT_MEM_VERSION): string {
21
- if (!metadata || typeof metadata !== "object") throw new Error("cannot attest loaded agent-mem version");
22
- const value = metadata as { name?: unknown; version?: unknown };
23
- if (value.name !== "@staix/agent-mem" || typeof value.version !== "string"
24
- || !/^\d+\.\d+\.\d+$/.test(value.version) || value.version !== expectedVersion) {
25
- throw new Error("loaded agent-mem version does not match the exact dependency pin");
20
+ /** Validate metadata located through the actual imported entry, never the declared range alone. */
21
+ export function assertAgentMemVersion(metadata: unknown, range: string = AGENT_MEM_RANGE, hostApi?: { min?: unknown; version?: unknown }): string {
22
+ const value = (metadata ?? {}) as { name?: unknown; version?: unknown };
23
+ if (value.name !== "@staix/agent-mem" || !agentMemVersionInRange(value.version, range)) {
24
+ const loaded = typeof value.version === "string" ? value.version : "unknown";
25
+ throw new Error(`the loaded agent-mem ${loaded} is not a plain release inside the declared range ${range}; install a release in that range with \`bun install --frozen-lockfile\`, or raise the range in package.json with a compatibility review`);
26
+ }
27
+ if (hostApi && !agentMemHostApiOk(hostApi.min, hostApi.version)) {
28
+ throw new Error(`the loaded agent-mem ${value.version as string} declares host API ${String(hostApi.min)}..${String(hostApi.version)}, which does not intersect the supported ${AGENT_MEM_HOST_API_RANGE[0]}..${AGENT_MEM_HOST_API_RANGE[1]} (or HOST_API_MIN and HOST_API_VERSION are missing or invalid); install a release that exports a compatible host API with \`bun install --frozen-lockfile\`, or review the hub for the new host API`);
26
29
  }
27
- return value.version;
30
+ return value.version as string;
28
31
  }
29
32
 
30
33
  const loadedAgentMem = (() => {
@@ -37,14 +40,18 @@ const loadedAgentMem = (() => {
37
40
  const metadata: unknown = JSON.parse(readFileSync(new URL("../package.json", entry), "utf8"));
38
41
  const actual = metadata && typeof metadata === "object" && typeof (metadata as { version?: unknown }).version === "string"
39
42
  ? (metadata as { version: string }).version : "unknown";
40
- try { return { version: assertAgentMemVersion(metadata), valid: true }; }
41
- catch { return { version: actual, valid: false }; }
42
- } catch { return { version: "unknown", valid: false }; }
43
+ // Read through the namespace, never a named import: a package without the constants must refuse with a cause, not fail at module link.
44
+ const exported = agentMemExports as unknown as { HOST_API_MIN?: unknown; HOST_API_VERSION?: unknown };
45
+ try { return { version: assertAgentMemVersion(metadata, AGENT_MEM_RANGE, { min: exported.HOST_API_MIN, version: exported.HOST_API_VERSION }), valid: true, reason: undefined }; }
46
+ catch (error) { return { version: actual, valid: false, reason: (error as Error).message }; }
47
+ } catch (error) { return { version: "unknown", valid: false, reason: `the loaded agent-mem could not be attested: ${(error as Error).message}` }; }
43
48
  })();
44
49
  export const AGENT_MEM_VERSION = loadedAgentMem.version;
45
50
  function assertLoadedAgentMem(): void {
46
- if (!loadedAgentMem.valid) throw new Error("cannot attest loaded agent-mem version against the exact dependency pin");
51
+ if (!loadedAgentMem.valid) throw new Error(loadedAgentMem.reason ?? `the loaded agent-mem ${AGENT_MEM_VERSION} is not usable`);
47
52
  }
53
+ /** #1611: why the loaded agent-mem is refused (version or host API, loaded and supported ranges, next step); undefined when it is usable. */
54
+ export const AGENT_MEM_REFUSAL: string | undefined = loadedAgentMem.valid ? undefined : loadedAgentMem.reason;
48
55
  export const MEMORY_PROFILE_UNAVAILABLE = "memory profile unavailable; inspect the selector and generation state, run ahub memory profile-check; use amem migrate --deactivate only to stop using the selected generation";
49
56
  const UNAVAILABLE = MEMORY_PROFILE_UNAVAILABLE;
50
57
  /** agent-mem#15 T2: a split marker that is not active (captured, malformed) is never read as an empty or legacy store. */
@@ -117,6 +124,74 @@ function receipt(profile: BoundProfile, state: MemoryProfileReceipt["state"], sk
117
124
  };
118
125
  }
119
126
 
127
+ /** One stat tuple: the identity a metadata object carries between two reads. `follow` resolves a configured home's symlinks. */
128
+ function statStamp(path: string, follow = false): string {
129
+ const stat = follow
130
+ ? statSync(path, { bigint: true, throwIfNoEntry: false })
131
+ : lstatSync(path, { bigint: true, throwIfNoEntry: false });
132
+ if (!stat) return "absent";
133
+ const kind = stat.isDirectory() ? "d" : stat.isFile() ? "f" : stat.isSymbolicLink() ? "l" : "o";
134
+ return `${kind}:${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
135
+ }
136
+
137
+ /**
138
+ * Every metadata object `assertCurrent()` resolves, in a fixed order: the selector pair and machine identity, the alias log,
139
+ * the public-prune and placement markers, this project's shard descriptor and generation files. A stamped directory covers a
140
+ * child created, removed or renamed inside it; an append to an existing placement journal changes no identity the version
141
+ * reads, and the next full fence sees it.
142
+ * ponytail: a stat tuple per call is the whole change signal. A filesystem with a coarser mtime tick could hide an in-place
143
+ * rewrite of the same size within one tick; agent-mem's own placement-binding memo accepts the same ceiling (agent-mem 0.30.0,
144
+ * `readActivePlacementBinding`). Upgrade to a kernel-sequenced revision if a target filesystem loses nanosecond stamps.
145
+ */
146
+ function fenceObjects(home: string, profile: BoundProfile, project: string | undefined, projectKey: string | undefined): string[] {
147
+ const paths = [
148
+ home,
149
+ join(home, "profile.json"), join(home, "shards.json"), join(home, "machine.json"),
150
+ join(home, "public-prune-view.intent.json"), join(home, "profile.lock"),
151
+ join(home, "sync-placement"), join(home, "sync-placement", "active.json"), join(home, "sync-placement-activation.json"),
152
+ ];
153
+ if (projectKey !== undefined) paths.push(aliasLogPath(home));
154
+ if (profile.pruneInputSetHash !== undefined) {
155
+ paths.push(join(home, "public-prune-input-sets"), join(home, "public-prune-input-sets", `${profile.pruneInputSetHash}.json`));
156
+ }
157
+ if (profile.placementHead !== undefined) {
158
+ const epochs = join(home, "sync-placement", "epochs"), epoch = join(epochs, profile.placementHead);
159
+ paths.push(epochs, epoch, join(epoch, "epoch.json"), join(epoch, "activation.json"));
160
+ }
161
+ if (profile.sharded === true && project !== undefined) {
162
+ const projects = join(home, "projects"), descriptor = join(projects, shardKeyHash(project));
163
+ paths.push(projects, descriptor, join(descriptor, "project.json"));
164
+ }
165
+ if (profile.kind === "generation" && profile.sharded !== true) paths.push(join(home, "generations"));
166
+ paths.push(profile.dir);
167
+ for (const name of ["generation.json", "generation-seal.json", "migration-sources.json", "machine.json", "project.json", "prune-translations.jsonl"]) {
168
+ paths.push(join(profile.dir, name));
169
+ }
170
+ for (const name of ["legacy", "legacy-main"]) paths.push(join(profile.dir, name));
171
+ return paths;
172
+ }
173
+
174
+ /**
175
+ * The memory sync policy version. `changeKey` is cheap (fence stat tuples plus the policy inputs) and is taken on every call;
176
+ * `read` resolves the profile and is reached only when that key moved. A key that moved without the policy inputs changing
177
+ * recomputes the same version, so a rewrite that keeps the identity does not abort an in-flight pass.
178
+ */
179
+ export function createMemoryPolicyVersion(
180
+ changeKey: () => string,
181
+ read: () => { profile: MemoryProfileReceipt | "unbound"; inputs: readonly unknown[] },
182
+ ): () => string {
183
+ let last: { key: string; version: string } | undefined;
184
+ return () => {
185
+ const key = changeKey();
186
+ if (last?.key === key) return last.version;
187
+ const { profile, inputs } = read();
188
+ const identity = profile === "unbound" ? "unbound" : [profile.state, profile.profile, profile.generation, profile.selectorRevision];
189
+ const version = createHash("sha256").update(JSON.stringify([identity, ...inputs])).digest("hex");
190
+ last = { key, version };
191
+ return version;
192
+ };
193
+ }
194
+
120
195
  /**
121
196
  * The project key agent-mem's own CLI binds: memoryProjectKey(cwd) through the person-reviewed alias log of the
122
197
  * canonical memory home. The daemon and `ahub memory`/`ahub goal` use it so both open the same shard and rows.
@@ -174,15 +249,37 @@ export class MemoryProfileBinding {
174
249
  this.directMemoryDir = directMemoryDir;
175
250
  this.project = opts.project;
176
251
  this.projectKey = opts.projectKey;
177
- this.home = directMemoryDir === undefined ? homeFor(this.options) : canonicalHome(directMemoryDir);
252
+ this.home = this.resolvedHome();
178
253
  this.profile = Object.freeze({ ...currentProfile(this.home, this.project) });
179
254
  this.explicitProfile = this.profile.kind === "shared-v1" ? "shared-v1" : Object.freeze({ generation: this.profile.generation! });
180
255
  }
181
256
 
257
+ /**
258
+ * The memory dir `assertCurrent()` compares against, by the same resolution: the whole string is the change signal for the
259
+ * home itself, so every input agent-mem's resolution reads shows when it moves - `AMEM_HOME` (canonicalized to its target,
260
+ * which a stamp of the old target cannot see), the machine config's `home` key inside the default home, and the
261
+ * `AGENTHUB_HOME` default with its `memory` child. Cost: one resolution, no profile, shard or alias parse.
262
+ */
263
+ private resolvedHome(): string {
264
+ return this.directMemoryDir === undefined ? homeFor(this.options) : canonicalHome(this.directMemoryDir);
265
+ }
266
+
267
+ /**
268
+ * The home's own change signal. An explicit home is a fixed string, so its followed tuple already sees every retarget
269
+ * below it (a link swap changes the containing directory's tuple) and costs one stat. The environment home is not fixed:
270
+ * agent-mem canonicalizes `AMEM_HOME` to its target and reads the default home's config pointer, so there the resolution
271
+ * itself is the signal.
272
+ */
273
+ private homeSignal(): string {
274
+ if (this.directMemoryDir !== undefined) return statStamp(this.directMemoryDir, true);
275
+ if (this.options.home !== undefined) return statStamp(this.options.home, true);
276
+ return this.resolvedHome();
277
+ }
278
+
182
279
  assertCurrent(): void {
183
280
  if (this.unavailable) throw new Error(UNAVAILABLE);
184
281
  try {
185
- const currentHome = this.directMemoryDir === undefined ? homeFor(this.options) : canonicalHome(this.directMemoryDir);
282
+ const currentHome = this.resolvedHome();
186
283
  const current = currentProfile(currentHome, this.project);
187
284
  if (currentHome !== this.home || !sameProfile(current, this.profile)) throw new Error(UNAVAILABLE);
188
285
  if (this.projectKey !== undefined && resolveAlias(currentHome, this.projectKey) !== this.project) throw new Error(UNAVAILABLE);
@@ -204,10 +301,29 @@ export class MemoryProfileBinding {
204
301
  try { this.onUnavailable?.(UNAVAILABLE); } catch { /* Observer failures cannot undo the latch. */ }
205
302
  }
206
303
 
207
- status(store?: MemoryStore): MemoryProfileReceipt {
304
+ /**
305
+ * The cheap change signal for `assertCurrent()`: `homeSignal()` plus the stat tuple of every metadata object it resolves,
306
+ * or `unavailable` once the fence latched. It never parses a profile, shard or alias file, so a caller may poll it per
307
+ * fence check.
308
+ * A stat can still throw where `assertCurrent()` would have latched (ENOTDIR once a metadata directory became a file,
309
+ * EACCES on a directory that lost read permission), and callers poll this unguarded on a peer's turn: every stat error
310
+ * latches the binding unavailable and returns `unavailable`, the same fail-closed result the fence gives.
311
+ */
312
+ fenceStamp(): string {
313
+ if (this.unavailable) return "unavailable";
314
+ try {
315
+ const anchor = this.homeSignal();
316
+ return [anchor, ...fenceObjects(this.home, this.profile, this.project, this.projectKey).map(path => statStamp(path))].join("|");
317
+ } catch {
318
+ this.invalidate();
319
+ return "unavailable";
320
+ }
321
+ }
322
+
323
+ status(store?: MemoryStore, opts: { skippedRows?: boolean } = {}): MemoryProfileReceipt {
208
324
  try { this.assertCurrent(); } catch { /* Report the latched state without exposing metadata errors. */ }
209
325
  let skippedRows = 0;
210
- if (!this.unavailable && store) {
326
+ if (opts.skippedRows !== false && !this.unavailable && store) {
211
327
  try { skippedRows = store.bridgeStatus()?.skippedRows ?? 0; } catch { this.invalidate(); }
212
328
  }
213
329
  return receipt(this.profile, this.unavailable ? "unavailable" : "ready", skippedRows);
@@ -41,6 +41,7 @@ const OWNER_TOOL_EFFECTS = new Set(["hub_task_propose", "hub_task_decline", "hub
41
41
  OWNER_TOOL_EFFECTS.add("hub_survey_report");
42
42
  OWNER_TOOL_EFFECTS.add("hub_roadmap_edit");
43
43
  OWNER_TOOL_EFFECTS.add("hub_roadmap_triage");
44
+ OWNER_TOOL_EFFECTS.add("hub_roadmap_decompose");
44
45
  /** A read does not prove progress; failed/pending mutations are handled conservatively by the host. */
45
46
  export function ownerToolEffect(op: string, input: Record<string, unknown> | undefined): boolean {
46
47
  if (op === "hub_survey_report" && input?.show === true) return false;
@@ -33,7 +33,7 @@ export const conductorLocalAction = (value:unknown): value is ConductorLocalActi
33
33
  /** Daemon-authorized labels. Recovery labels pass the initial role check, then require their separate per-operation proof. */
34
34
  export const CONDUCTOR_DAEMON_OPERATIONS = ["roster add","roster remove","stop","queue show","queue resolve","queue discard","settings set","doctor orphans kill","logs","export",
35
35
  "sdlc configure",
36
- "board import","intake approve","schedule run","schedule pause","schedule resume","goal link","task unassign","guidance probe register","guidance probe start","guidance probe show","guidance probe receipts","guidance probe cancel","restart","upgrade","recovery resume","recovery abort","sdlc survey start","sdlc survey show","sdlc audit start","sdlc audit show"] as const;
36
+ "board import","intake approve","schedule run","schedule pause","schedule resume","goal link","task unassign","roadmap sync","roadmap export","guidance probe register","guidance probe start","guidance probe show","guidance probe receipts","guidance probe cancel","restart","upgrade","recovery resume","recovery abort","sdlc survey start","sdlc survey show","sdlc audit start","sdlc audit show"] as const;
37
37
  /**
38
38
  * #933: forms whose effect runs in the CLI process itself (local files). The daemon admits and audits them once at the handshake (`admit`),
39
39
  * after the CLI has validated their arguments. Recovery-bearing restart/upgrade forms use the separate source-issued continuation proof.
@@ -72,6 +72,7 @@ function restartOrUpgrade(command: string, args: readonly string[]): "restart" |
72
72
  export function conductorOperation(command:string,args:readonly string[]): ConductorOperation | undefined {
73
73
  const words=args.filter(arg=>!arg.startsWith("--"));
74
74
  const sub=words[0];
75
+ if (command === "roadmap" && args.includes("--apply") && (sub === "sync" || sub === "export")) return `roadmap ${sub}`;
75
76
  if (command === "sdlc" && args[0] === "survey" && (args[1] === "start" || args[1] === "show")) return `sdlc survey ${args[1]}`;
76
77
  if (command === "sdlc" && args[0] === "audit" && (args[1] === "start" || args[1] === "show")) return `sdlc audit ${args[1]}`;
77
78
  if (command === "restart" || command === "upgrade") return restartOrUpgrade(command, args);
@@ -119,7 +120,7 @@ export function operationalRefusal(peer:string,command:string):string {
119
120
  return `${peer} cannot run ahub ${command}; ${OPERATIONAL_PERSON_GUIDANCE}; this operation requires the explicit conductor role`;
120
121
  }
121
122
  /** #933: the console task ops the conductor may now run, by audit label. The daemon admits each through `admitOperational` before Tasks sees it. */
122
- export const CONDUCTOR_TASK_OPS: Readonly<Record<string,ConductorOperation>> = {github_import:"board import",intake_approve:"intake approve",schedule_run:"schedule run",schedule_pause:"schedule pause",schedule_resume:"schedule resume",task_unassign:"task unassign"};
123
+ export const CONDUCTOR_TASK_OPS: Readonly<Record<string,ConductorOperation>> = {github_import:"board import",intake_approve:"intake approve",schedule_run:"schedule run",schedule_pause:"schedule pause",schedule_resume:"schedule resume",task_unassign:"task unassign",roadmap_sync_apply:"roadmap sync",roadmap_export_apply:"roadmap export"};
123
124
  /** Fixed labels only; refused requests never put argument text in the audit. */
124
125
  export function operationalRequestLabel(value:unknown):string|undefined {
125
126
  if(!value || typeof value!=="object" || Array.isArray(value))return undefined;
@@ -117,8 +117,8 @@ export const RECOVERY_TERMINAL_IDLE_WAIT_SETTING = recoveryNumber({
117
117
 
118
118
  const adapterNumber = <const T extends Omit<OperationalNumberSetting, "group" | "store" | "risk" | "applies" | "type">>(def: T) => ({ group: "Start", store: "config", risk: "raises", applies: "next use", type: "integer", ...def }) as const satisfies OperationalNumberSetting;
119
119
  export const ACP_TOOL_CEILING_SETTING = adapterNumber({
120
- key: "adapter_timing.acp_tool_ceiling_min", path: ["adapter_timing", "acp_tool_ceiling_min"], label: "Next ACP launch: open-tool ceiling (minutes, at least the watchdog)",
121
- min: 1, max: 30, defaultValue: 30, unit: "minutes", inventory: "src/adapters/acp.ts:TOOL_CEILING_MS",
120
+ key: "adapter_timing.acp_tool_ceiling_min", path: ["adapter_timing", "acp_tool_ceiling_min"], label: "Next ACP launch: open-tool ceiling (minutes, at least the watchdog; 60 covers a documented 50-minute gate wait)",
121
+ min: 1, max: 120, defaultValue: 60, unit: "minutes", inventory: "src/adapters/acp.ts:TOOL_CEILING_MS",
122
122
  });
123
123
  export const ACP_ACTIVITY_BATCH_SETTING = adapterNumber({
124
124
  key: "adapter_timing.acp_activity_batch_ms", path: ["adapter_timing", "acp_activity_batch_ms"], label: "Next ACP launch: activity display batch delay (milliseconds)",
@@ -265,8 +265,19 @@ export async function stopSignedRunner(id: string, home = hubHome(), waitMs = 50
265
265
  return false;
266
266
  }
267
267
 
268
- /** An exclusive runner claim. Never steal a live or uncertain owner on resume. */
269
- export function claimRunner(id: string, home = hubHome()): () => void {
268
+ /** One operation's runner claim: `release` gives the slot back and leaves the db, `retire` removes the db (#329). */
269
+ interface RunnerClaim {
270
+ /** The row leaves and the handle closes, so the db survives for the next owner. */
271
+ release(): void;
272
+ /**
273
+ * #329/#1541: close the handle and remove the db while this process's row still names it, so no pass can claim the freed slot
274
+ * in between and have the file unlinked under its own handle (SQLITE_READONLY_DBMOVED). False when the db could not be
275
+ * removed: the row then keeps refusing a new owner until this process exits and a later claim replaces the stale one.
276
+ */
277
+ retire(): boolean;
278
+ }
279
+
280
+ function openRunnerClaim(id: string, home: string): RunnerClaim {
270
281
  const path = `${operationPath(id, home)}.runner.db`;
271
282
  const nonce = randomUUID();
272
283
  const db = new Database(path, { create: true });
@@ -291,12 +302,25 @@ export function claimRunner(id: string, home = hubHome()): () => void {
291
302
  db.query("INSERT OR REPLACE INTO runner (slot, pid, nonce, signature) VALUES (1, ?, ?, ?)").run(process.pid, nonce, signature);
292
303
  }).immediate();
293
304
  } catch (error) { db.close(); throw error; }
294
- return () => {
295
- db.query("DELETE FROM runner WHERE slot = 1 AND nonce = ?").run(nonce);
296
- db.close();
305
+ return {
306
+ release: () => {
307
+ // A db another pass already removed cannot be written; the caller reports `kept` instead of throwing out of its pass.
308
+ try { db.query("DELETE FROM runner WHERE slot = 1 AND nonce = ?").run(nonce); } finally { db.close(); }
309
+ },
310
+ retire: () => {
311
+ // #329: the row stays until the file is gone, so the freed slot can never be claimed between a release and an unlink.
312
+ try { db.close(); } catch { return false; }
313
+ try { rmSync(path, { force: true }); return true; } catch { return false; }
314
+ },
297
315
  };
298
316
  }
299
317
 
318
+ /** An exclusive runner claim. Never steal a live or uncertain owner on resume. */
319
+ export function claimRunner(id: string, home = hubHome()): () => void {
320
+ const claim = openRunnerClaim(id, home);
321
+ return () => claim.release();
322
+ }
323
+
300
324
  /**
301
325
  * True when any machine or project recovery hold exists, or the coordination state cannot be read: unknown is held.
302
326
  * `nonBlocking` bounds how long a locked project-locks.db may block the caller to 1 ms: a startup path passes it so a busy database is a
@@ -313,29 +337,33 @@ export function anyRecoveryHold(home = hubHome(), nonBlocking = false): boolean
313
337
 
314
338
  /**
315
339
  * #1541: remove one terminal receipt and its runner db. The exclusive runner claim is the only mutual exclusion: a live or
316
- * unidentifiable runner keeps the receipt, a dead one is replaced by `claimRunner` in its own transaction, so two retirers
340
+ * unidentifiable runner keeps the receipt, a dead one is replaced by `openRunnerClaim` in its own transaction, so two retirers
317
341
  * on the same stale claim cannot both proceed. Under the claim `confirm` sees the receipt as it is now; the receipt leaves
318
- * first, then the claim row is released, then the runner db. An interruption between them leaves only a runner db without
319
- * a receipt, which the next call settles through the ENOENT branch (a later claimant re-reads the receipt, finds none and
320
- * fails). A runner db whose receipt is gone is settled the same way (`settled`, `confirm` never called); only the call that
321
- * removed the receipt answers `retired`.
342
+ * first, then the runner db, and this process's claim row leaves with that file, never before it (#329): a pass therefore
343
+ * cannot claim the freed slot in between and have the file unlinked under its own handle (SQLITE_READONLY_DBMOVED). An
344
+ * interruption leaves only a runner db without a receipt, which the next call settles through the ENOENT branch (a later
345
+ * claimant re-reads the receipt, finds none and fails). A runner db whose receipt is gone is settled the same way
346
+ * (`settled`, `confirm` never called); only the call that removed the receipt answers `retired`, and a db this call cannot
347
+ * remove answers `kept` so the next pass settles it.
322
348
  */
323
- export function retireOperation(id: string, home: string, confirm: (record: unknown) => boolean, hooks: { betweenPair?: () => void } = {}): "retired" | "settled" | "kept" {
349
+ export function retireOperation(id: string, home: string, confirm: (record: unknown) => boolean, hooks: { betweenPair?: () => void; beforeRunnerRemoval?: () => void } = {}): "retired" | "settled" | "kept" {
324
350
  const file = operationPath(id, home);
325
- let release: () => void;
326
- try { release = claimRunner(id, home); } catch { return "kept"; }
327
- let result: "retired" | "settled" = "settled";
351
+ let claim: RunnerClaim;
352
+ try { claim = openRunnerClaim(id, home); } catch { return "kept"; }
353
+ // Giving the claim back is best effort: a pass only reaches here with the receipt still present, so the answer is `kept`.
354
+ const giveUp = (): "kept" => { try { claim.release(); } catch { /* the db another pass already moved */ } return "kept"; };
355
+ let removed = false;
328
356
  try {
329
- let record: unknown, removed = false;
357
+ let record: unknown;
330
358
  try { record = readOperation(id, home); }
331
- catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return "kept"; }
359
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return giveUp(); }
332
360
  if (record !== undefined) {
333
- if (!confirm(record)) return "kept";
361
+ if (!confirm(record)) return giveUp();
334
362
  rmSync(file); removed = true;
335
363
  hooks.betweenPair?.();
336
364
  }
337
- result = removed ? "retired" : "settled";
338
- } finally { release(); }
339
- rmSync(`${file}.runner.db`, { force: true });
340
- return result;
365
+ } catch (error) { giveUp(); throw error; }
366
+ // The seam where a second pass used to claim the slot the release had just freed, and then lose the file to this unlink.
367
+ hooks.beforeRunnerRemoval?.();
368
+ return claim.retire() ? (removed ? "retired" : "settled") : "kept";
341
369
  }
@@ -38,7 +38,7 @@ export function projectFromRow(raw: Record<string, unknown>): Project {
38
38
  return project;
39
39
  }
40
40
 
41
- const idFor = (root: string) => `p_${createHash("sha256").update(root).digest("hex").slice(0, 24)}`;
41
+ export const idFor = (root: string) => `p_${createHash("sha256").update(root).digest("hex").slice(0, 24)}`;
42
42
  // Preserve the original identifier of missing legacy checkouts as a reservation.
43
43
  const legacyRoot = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } };
44
44
  const canonicalState = canonicalPath;
@@ -2,6 +2,9 @@ import { createHash } from "node:crypto";
2
2
  import { types } from "node:util";
3
3
  import { looksSecret } from "@staix/agent-mem";
4
4
  import { canonicalJson } from "./packs.ts";
5
+ import { latestTaskRecords, type TaskRecord } from "./research.ts";
6
+ import { isModelEvidence } from "./events.ts";
7
+ import { safeModelLabel } from "../omniroute/usage.ts";
5
8
  import { parseAttemptReceipt, runnerSealing, type AttemptReceiptV1 } from "./research-runner.ts";
6
9
  import { parseDeliverableClaims, parseDeliverableRecords, deliverableId, DELIVERABLE_LIMITS, type DeliverableClaim, type DeliverableRecord } from "./deliverables.ts";
7
10
 
@@ -472,3 +475,132 @@ export function protocolApprovalBindingMatches(protocol: ExperimentProtocolContr
472
475
  return record.protocolHash === hash && record.evaluatorHash === evaluator;
473
476
  } catch { return false; }
474
477
  }
478
+
479
+ /** #1556 T4: these labels describe preregistered groups; this module never selects or starts an arm. */
480
+ export const EDIT_EXPERIMENT_ARMS = ["baseline", "soft_guidance", "route_guard", "occ_guard", "combined_guard"] as const;
481
+ export type EditExperimentArm = (typeof EDIT_EXPERIMENT_ARMS)[number];
482
+ export interface EditRates {
483
+ arm: EditExperimentArm | null;
484
+ tasks: number;
485
+ editTotal: number | null;
486
+ shellTotal: number | null;
487
+ editBlindOrStale: number | null;
488
+ shellBlindOrStale: number | null;
489
+ p: number | null;
490
+ bE: number | null;
491
+ bS: number | null;
492
+ B: number | null;
493
+ dBdp: number | null;
494
+ dBdbS: number | null;
495
+ }
496
+
497
+ /** A null, malformed, overflowed or missing count remains unknown; it is never silently omitted or made zero. */
498
+ export function editRates(blocks: readonly (import("./research-record.ts").EditGovernanceBlock | undefined)[]): EditRates {
499
+ const sum = (pick: (block: import("./research-record.ts").EditGovernanceBlock) => unknown): number | null => {
500
+ if (!blocks.length) return null;
501
+ let total = 0;
502
+ for (const block of blocks) {
503
+ if (!block) return null;
504
+ const value = pick(block);
505
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || !Number.isSafeInteger(total + value)) return null;
506
+ total += value;
507
+ }
508
+ return total;
509
+ };
510
+ const arms = new Set(blocks.map(block => block?.policyArm));
511
+ const only = arms.size === 1 ? [...arms][0] : undefined;
512
+ const arm = typeof only === "string" && (EDIT_EXPERIMENT_ARMS as readonly string[]).includes(only) ? only as EditExperimentArm : null;
513
+ const e = sum(block => block.editTool?.total), s = sum(block => block.shellRoute?.total);
514
+ const eb = sum(block => block.editTool?.blindOrStale), sb = sum(block => block.shellRoute?.blindOrStale);
515
+ const unattributed = sum(block => block.unattributedTreeWrites);
516
+ const gradeComplete = (route: "editTool" | "shellRoute") => blocks.every(block => {
517
+ const counts = block?.[route];
518
+ if (!counts) return false;
519
+ const values = [counts.total, counts.verifiedFullRead, counts.partialReadOnly, counts.blindOrStale];
520
+ if (values.some(value => typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)) return false;
521
+ const graded = counts.verifiedFullRead! + counts.partialReadOnly! + counts.blindOrStale!;
522
+ return Number.isSafeInteger(graded) && graded === counts.total;
523
+ });
524
+ const total = e !== null && s !== null && Number.isSafeInteger(e + s) ? e + s : null;
525
+ const p = unattributed === 0 && total !== null && total > 0 ? s! / total : null;
526
+ const bE = unattributed === 0 && gradeComplete("editTool") && e !== null && e > 0 && eb !== null && eb <= e ? eb / e : null;
527
+ const bS = unattributed === 0 && gradeComplete("shellRoute") && s !== null && s > 0 && sb !== null && sb <= s ? sb / s : null;
528
+ const B = p !== null && bE !== null && bS !== null && unattributed === 0 ? (1 - p) * bE + p * bS : null;
529
+ return { arm, tasks: blocks.length, editTotal: e, shellTotal: s, editBlindOrStale: eb, shellBlindOrStale: sb,
530
+ p, bE, bS, B, dBdp: bE !== null && bS !== null ? bS - bE : null, dBdbS: p };
531
+ }
532
+
533
+ /** Descriptive 2x2 contrast; callers must separately establish a comparable experimental design. */
534
+ export function editFactorial(baseline: EditRates, route: EditRates, occ: EditRates, combined: EditRates) {
535
+ if (baseline.arm !== "baseline" || route.arm !== "route_guard" || occ.arm !== "occ_guard" || combined.arm !== "combined_guard" || [baseline.B, route.B, occ.B, combined.B].some(value => value === null || !Number.isFinite(value))) return { routeReduction: null, occReduction: null, combinedReduction: null, subAdditive: null };
536
+ const routeReduction = baseline.B! - route.B!, occReduction = baseline.B! - occ.B!, combinedReduction = baseline.B! - combined.B!;
537
+ return { routeReduction, occReduction, combinedReduction, subAdditive: combinedReduction < routeReduction + occReduction };
538
+ }
539
+
540
+ /** Group only rows with unambiguous owner, model and family; ambiguous/private rows are counted, never guessed or duplicated. */
541
+ export function groupEditRates(records: readonly TaskRecord[], familyOf: (peer: string) => string | undefined) {
542
+ const groups = new Map<string, { family: string; ownerModel: string; taskClass: string; arm: EditExperimentArm; modelEvidence: Set<string>; blocks: import("./research-record.ts").EditGovernanceBlock[] }>();
543
+ let withheld = 0, unknown = 0;
544
+ for (const record of latestTaskRecords(records)) {
545
+ if (record.pii !== false) { withheld++; continue; }
546
+ const owners = Array.isArray(record.owners) ? [...new Set(record.owners)] : [], models = Array.isArray(record.ownerModels) ? record.ownerModels : [], block = record.edits;
547
+ let family: string | undefined;
548
+ try { family = owners.length === 1 && typeof owners[0] === "string" ? familyOf(owners[0]) : undefined; } catch { /* unavailable family is unknown */ }
549
+ const model = models[0], safeFamily = safeModelLabel(family), safeModel = safeModelLabel(model?.model), safeClass = safeModelLabel(record.class);
550
+ if (!safeFamily || safeFamily.toLowerCase() === "unknown" || models.length !== 1 || !safeModel || safeModel.toLowerCase() === "unknown" || !isModelEvidence(model?.evidence) || !safeClass || !block || !(EDIT_EXPERIMENT_ARMS as readonly string[]).includes(block.policyArm)) { unknown++; continue; }
551
+ const arm = block.policyArm as EditExperimentArm, key = JSON.stringify([safeFamily, safeModel, safeClass, arm]);
552
+ let group = groups.get(key);
553
+ if (!group) { group = { family: safeFamily, ownerModel: safeModel, taskClass: safeClass, arm, modelEvidence: new Set(), blocks: [] }; groups.set(key, group); }
554
+ group.modelEvidence.add(model!.evidence); group.blocks.push(block);
555
+ }
556
+ return { groups: [...groups.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, group]) => ({ family: group.family, ownerModel: group.ownerModel, taskClass: group.taskClass, armEvidence: "last_observed" as const, modelEvidence: [...group.modelEvidence].sort(), ...editRates(group.blocks) })), withheld, unknown };
557
+ }
558
+
559
+ /** One externally evidenced component total over an identical set of task identities. */
560
+ export interface EditCostComponent { amount: number; unit: string; tasks: readonly string[]; evidence: string }
561
+ export interface VerifiedSuccesses { tasks: readonly string[]; evidence: string }
562
+ export interface EditSuccessCost { unit: string; verifiedSuccesses: number; execution: number; verification: number; rework: number; human: number; total: number }
563
+
564
+ /** No TaskRecord aggregate is converted to cost: all four same-unit component totals and a verified-success set are required. */
565
+ export function editSuccessCost(costs: { execution?: EditCostComponent; verification?: EditCostComponent; rework?: EditCostComponent; human?: EditCostComponent }, verified: VerifiedSuccesses | undefined): EditSuccessCost | null {
566
+ const components = [costs.execution, costs.verification, costs.rework, costs.human];
567
+ const validText = (value: unknown): value is string => typeof value === "string" && !!value.trim() && value === value.trim();
568
+ const taskSet = (value: unknown): string[] | undefined => {
569
+ if (!Array.isArray(value) || !value.length || value.some(item => !validText(item)) || new Set(value).size !== value.length) return undefined;
570
+ return [...value].sort();
571
+ };
572
+ const success = taskSet(verified?.tasks);
573
+ if (!success || !validText(verified?.evidence)) return null;
574
+ let scope: string[] | undefined, unit: string | undefined;
575
+ for (const component of components) {
576
+ if (!component || !Number.isFinite(component.amount) || component.amount < 0 || !validText(component.unit) || !validText(component.evidence)) return null;
577
+ const tasks = taskSet(component.tasks); if (!tasks) return null;
578
+ if (scope && (scope.length !== tasks.length || scope.some((task, index) => task !== tasks[index])) || unit !== undefined && unit !== component.unit) return null;
579
+ scope = tasks; unit = component.unit;
580
+ }
581
+ if (!scope || !unit) return null;
582
+ const inScope = new Set(scope);
583
+ if (success.some(task => !inScope.has(task))) return null;
584
+ const [execution, verification, rework, human] = components.map(component => component!.amount / success.length);
585
+ const total = execution! + verification! + rework! + human!;
586
+ if (!Number.isFinite(total)) return null;
587
+ return { unit, verifiedSuccesses: success.length, execution: execution!, verification: verification!, rework: rework!, human: human!, total };
588
+ }
589
+
590
+ /** Descriptive net-benefit arithmetic only; costs, deltas and penalties are supplied by the caller, never inferred. */
591
+ export function editMarginalBenefit(rates: EditRates, input: { reworkCost: number | null; deltaP: number | null; deltaBE: number | null; deltaBS: number | null; routePenalty: number | null; occPenalty: number | null }) {
592
+ const finite = (value: number | null): value is number => value !== null && Number.isFinite(value);
593
+ const cost = finite(input.reworkCost) && input.reworkCost >= 0 ? input.reworkCost : null;
594
+ const route = cost !== null && finite(rates.dBdp) && finite(input.deltaP) && finite(input.routePenalty) && input.routePenalty >= 0
595
+ ? cost * rates.dBdp * input.deltaP - input.routePenalty : null;
596
+ const occ = cost !== null && finite(rates.p) && rates.p >= 0 && rates.p <= 1 && finite(input.deltaBE) && finite(input.deltaBS) && finite(input.occPenalty) && input.occPenalty >= 0
597
+ ? cost * (rates.p * input.deltaBS + (1 - rates.p) * input.deltaBE) - input.occPenalty : null;
598
+ return { route: route !== null && Number.isFinite(route) ? route : null, occ: occ !== null && Number.isFinite(occ) ? occ : null };
599
+ }
600
+
601
+ /** A grouped contrast never combines different family, model or task-class identities. */
602
+ export function editFactorialGroup(baseline: ReturnType<typeof groupEditRates>["groups"][number], route: ReturnType<typeof groupEditRates>["groups"][number], occ: ReturnType<typeof groupEditRates>["groups"][number], combined: ReturnType<typeof groupEditRates>["groups"][number]) {
603
+ const identity = (row: typeof baseline) => JSON.stringify([row.family, row.ownerModel, row.taskClass]);
604
+ if ([route, occ, combined].some(row => identity(row) !== identity(baseline))) return { routeReduction: null, occReduction: null, combinedReduction: null, subAdditive: null };
605
+ return editFactorial(baseline, route, occ, combined);
606
+ }