@aiwg/cli 2026.10.14 → 2026.10.16

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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,34 @@
1
+ export interface HostResourceSample {
2
+ supported: boolean; reason?: string; availMemGb?: number; load1?: number; cores?: number;
3
+ loadRatio?: number; memPsiAvg10?: number; memPsiAvg60?: number; memPsiAvg300?: number;
4
+ workerGroups?: Record<string, number>;
5
+ workers?: number; hostCliProcesses?: Record<string, number>; workerUnits?: number; freeDiskGb?: number;
6
+ workerCountingSource?: 'systemd-units-and-marked-processes' | 'owned-process-fallback';
7
+ }
8
+ export interface WorkerCensus {
9
+ byGroup?: Record<string, number>;
10
+ total: number; hostCliProcesses?: Record<string, number>; units?: number;
11
+ source?: HostResourceSample['workerCountingSource'];
12
+ }
13
+ export interface HostResourceReaders {
14
+ readText?: (path: string) => string;
15
+ readDir?: (path: string) => string[];
16
+ uid?: number;
17
+ groupNames?: string[];
18
+ coreCount?: () => number;
19
+ countWorkers?: () => number | undefined | WorkerCensus;
20
+ countWorkerUnits?: () => number | undefined;
21
+ listWorkerUnits?: () => string[] | undefined;
22
+ statfs?: () => { bavail: number | bigint; bsize: number | bigint };
23
+ statfsPath?: (path: string) => { bavail: number | bigint; bsize: number | bigint };
24
+ paths?: string[];
25
+ }
26
+ export function readLiveHostResources(readers?: HostResourceReaders): HostResourceSample;
27
+ export function countWorkerProcesses(readers?: HostResourceReaders): WorkerCensus | undefined;
28
+ export function defaultCountWorkers(readers?: HostResourceReaders): number | undefined;
29
+ export function countWorkerUnits(options?: { spawn?: (...args: any[]) => any }): number | undefined;
30
+ export function listWorkerUnits(options?: { spawn?: (...args: any[]) => any }): string[] | undefined;
31
+ export function parseMemAvailableGb(text: unknown): number | undefined;
32
+ export function parseMemoryPsi(text: unknown): { avg10: number; avg60: number; avg300: number } | null;
33
+ export function parseLoadAverages(text: unknown): { load1: number; load5: number; load15: number } | null;
34
+ export function evaluateDispatchGate(live: HostResourceSample, thresholds: any): { ok: boolean; failures: any[]; thresholds: any };
@@ -0,0 +1,293 @@
1
+ // Linux host measurements shared by dispatch preflight and resource reports.
2
+ import { readFileSync, readdirSync, statfsSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { WORKER_INVOCATION_MARKER } from './worker-invocation-marker.mjs';
6
+ const BYTES_PER_GB = 1024 ** 3;
7
+
8
+ /**
9
+ * Parse MemAvailable (kB) from /proc/meminfo text. Returns GiB or undefined
10
+ * when the field is absent/unparsable. Pure: tests feed synthetic fixtures.
11
+ */
12
+ function parseMemAvailableGb(meminfoText) {
13
+ if (typeof meminfoText !== 'string') return undefined;
14
+ const match = meminfoText.match(/^MemAvailable:\s+(\d+)\s+kB$/m);
15
+ if (!match) return undefined;
16
+ const gib = Number(match[1]) / 1024 / 1024;
17
+ return Number.isFinite(gib) ? gib : undefined;
18
+ }
19
+
20
+ /**
21
+ * Parse memory pressure from /proc/pressure/memory text. Returns
22
+ * `{ avg10, avg60, avg300 }` from the `some` line, or null when no `some`
23
+ * line parses. Pure: tests feed synthetic fixtures.
24
+ */
25
+ function parseMemoryPsi(pressureText) {
26
+ if (typeof pressureText !== 'string') return null;
27
+ for (const line of pressureText.split('\n')) {
28
+ if (!line.startsWith('some')) continue;
29
+ const values = {};
30
+ for (const part of line.split(/\s+/)) {
31
+ const [key, raw] = part.split('=');
32
+ if ((key === 'avg10' || key === 'avg60' || key === 'avg300') && raw !== undefined) {
33
+ const value = Number(raw);
34
+ if (Number.isFinite(value)) values[key] = value;
35
+ }
36
+ }
37
+ if (values.avg10 !== undefined && values.avg60 !== undefined && values.avg300 !== undefined) return values;
38
+ return null;
39
+ }
40
+ return null;
41
+ }
42
+
43
+ /**
44
+ * Parse /proc/loadavg text. Returns `{ load1, load5, load15 }` or null.
45
+ * Pure: tests feed synthetic fixtures.
46
+ */
47
+ function parseLoadAverages(loadavgText) {
48
+ if (typeof loadavgText !== 'string') return null;
49
+ const parts = loadavgText.trim().split(/\s+/);
50
+ const loads = parts.slice(0, 3).map(Number);
51
+ if (loads.length !== 3 || loads.some(value => !Number.isFinite(value))) return null;
52
+ return { load1: loads[0], load5: loads[1], load15: loads[2] };
53
+ }
54
+
55
+ /** List active current-user launcher units, retaining identity for deduplication. */
56
+ function listWorkerUnits({ spawn = spawnSync } = {}) {
57
+ try {
58
+ const result = spawn('systemctl', ['--user', 'list-units', '--type=service',
59
+ '--state=running,activating', '--no-legend', '--plain', 'aiwg-worker-*'],
60
+ { encoding: 'utf8', timeout: 1000 });
61
+ if (result.error || result.status !== 0) return undefined;
62
+ return [...new Set(String(result.stdout ?? '').split('\n')
63
+ .map(line => /^(aiwg-worker-[^\s]+\.service)\s/.exec(line.trim())?.[1]).filter(Boolean))];
64
+ } catch { return undefined; }
65
+ }
66
+
67
+ function countWorkerUnits(options) {
68
+ return listWorkerUnits(options)?.length;
69
+ }
70
+
71
+ /** Count owned invocations once; CLI comm counts are informational only. */
72
+ function countWorkerProcesses({
73
+ readDir = readdirSync,
74
+ readText = path => readFileSync(path, 'utf8'),
75
+ uid = process.getuid?.(),
76
+ groupNames = [],
77
+ listWorkerUnits: readUnitList,
78
+ countWorkerUnits: readUnitCount,
79
+ } = {}) {
80
+ if (process.platform !== 'linux' || uid === undefined) return undefined;
81
+ let units, unitNames;
82
+ try {
83
+ const listed = readUnitList ? readUnitList() : readUnitCount ? readUnitCount() : listWorkerUnits();
84
+ if (Array.isArray(listed)) unitNames = new Set(listed);
85
+ const counted = unitNames ? unitNames.size : listed;
86
+ if (Number.isInteger(counted) && counted >= 0) units = counted;
87
+ } catch { /* Owned-process scanning remains available. */ }
88
+ const source = units === undefined ? 'owned-process-fallback' : 'systemd-units-and-marked-processes';
89
+ // Reuse existing identities; UUID-only IDs carry no group evidence.
90
+ const identify = value => new Set(groupNames.filter(name => value === name || value.startsWith(`${name}-`)));
91
+ const unitGroups = new Map([...(unitNames ?? [])].map(unit =>
92
+ [unit, identify(unit.slice('aiwg-worker-'.length, -'.service'.length))]));
93
+ let entries, procUnavailable = false;
94
+ try { entries = readDir('/proc'); }
95
+ catch {
96
+ if (units === undefined) return undefined;
97
+ entries = []; procUnavailable = true;
98
+ }
99
+ const hostCliProcesses = { codex: 0, muse: 0 };
100
+ const invocations = new Set(), unitInvocations = new Set();
101
+ const invocationGroups = new Map();
102
+ const merge = (target, evidence) => { for (const name of evidence) target.add(name); };
103
+ for (const entry of entries) {
104
+ if (!/^\d+$/.test(entry)) continue;
105
+ try {
106
+ const status = readText(`/proc/${entry}/status`);
107
+ const owner = status.match(/^Uid:\s+(\d+)/m);
108
+ if (!owner || Number(owner[1]) !== uid) continue;
109
+ const optional = field => {
110
+ try { return readText(`/proc/${entry}/${field}`); } catch { return ''; }
111
+ };
112
+ const comm = optional('comm').trim();
113
+ if (comm === 'codex') hostCliProcesses.codex += 1;
114
+ if (comm === 'muse-bin' || comm === 'muse') hostCliProcesses.muse += 1;
115
+ const marker = optional('environ').split('\0').find(field => field.startsWith(`${WORKER_INVOCATION_MARKER}=`));
116
+ const invocation = marker?.slice(WORKER_INVOCATION_MARKER.length + 1);
117
+ if (!invocation) continue;
118
+ invocations.add(invocation);
119
+ if (!invocationGroups.has(invocation)) invocationGroups.set(invocation, identify(invocation));
120
+ const cgroupUnits = optional('cgroup').match(/aiwg-worker-[^/\s]+\.service(?=\/|\s|$)/g) ?? [];
121
+ if (cgroupUnits.some(unit => unitNames ? unitNames.has(unit) : units > 0)) unitInvocations.add(invocation);
122
+ for (const unit of cgroupUnits.filter(unit => unitGroups.has(unit))) {
123
+ merge(unitGroups.get(unit), invocationGroups.get(invocation));
124
+ }
125
+ } catch { /* Processes may exit during the scan. */ }
126
+ }
127
+ const byGroup = {};
128
+ for (const evidence of [...unitGroups.values(), ...[...invocationGroups]
129
+ .filter(([id]) => !unitInvocations.has(id)).map(([, evidence]) => evidence)]) {
130
+ if (evidence.size === 1) {
131
+ const [name] = evidence;
132
+ byGroup[name] = (byGroup[name] ?? 0) + 1;
133
+ }
134
+ }
135
+ return { ...(groupNames.length ? { byGroup } : {}), total: (units ?? 0) + [...invocations].filter(id => !unitInvocations.has(id)).length,
136
+ ...(procUnavailable ? {} : { hostCliProcesses }), units, source };
137
+ }
138
+
139
+ function defaultCountWorkers(options) {
140
+ return countWorkerProcesses(options)?.total;
141
+ }
142
+
143
+ /**
144
+ * Sample live host signals. All inputs are injectable so tests use synthetic
145
+ * meminfo/pressure/loadavg fixtures instead of the real /proc:
146
+ * `{ readText, coreCount, countWorkers }`. Non-Linux hosts report
147
+ * `{ supported: false }`; the gate turns that into an explicit diagnostic
148
+ * (MVP qualifies Linux per NFR-OG-008) rather than an implicit pass.
149
+ */
150
+ /**
151
+ * Convert one statfs result to GiB. Non-finite or negative samples are
152
+ * rejected (fail closed): a NaN/Infinity/-1 reading must never become a
153
+ * passing number downstream.
154
+ */
155
+ function toFreeDiskGb(disk) {
156
+ const gb = (Number(disk?.bavail) * Number(disk?.bsize)) / BYTES_PER_GB;
157
+ return Number.isFinite(gb) && gb >= 0 ? gb : undefined;
158
+ }
159
+
160
+ /**
161
+ * Sample free disk on the caller-supplied filesystem(s): `readers.paths`
162
+ * names the actual evidence root and worktree, and the gate takes the
163
+ * minimum across them. Any unreadable, non-finite or negative sample — or
164
+ * no supplied filesystem at all — yields undefined so the gate fails closed
165
+ * instead of admitting on the conductor's process-cwd filesystem.
166
+ * `readers.statfs` (zero-arg) and `readers.statfsPath` (per-path) stay as
167
+ * injectable test seams; there is no process.cwd() fallback.
168
+ */
169
+ function sampleFreeDiskGb(readers) {
170
+ if (Array.isArray(readers.paths)) {
171
+ if (readers.paths.length === 0) return undefined;
172
+ const statOne = typeof readers.statfsPath === 'function' ? readers.statfsPath : (path) => statfsSync(path);
173
+ let minimum;
174
+ for (const path of readers.paths) {
175
+ let sample;
176
+ try {
177
+ sample = toFreeDiskGb(statOne(path));
178
+ } catch {
179
+ return undefined;
180
+ }
181
+ if (sample === undefined) return undefined;
182
+ minimum = minimum === undefined ? sample : Math.min(minimum, sample);
183
+ }
184
+ return minimum;
185
+ }
186
+ if (typeof readers.statfs === 'function') {
187
+ try {
188
+ return toFreeDiskGb(readers.statfs());
189
+ } catch {
190
+ return undefined;
191
+ }
192
+ }
193
+ return undefined;
194
+ }
195
+
196
+ function readLiveHostResources(readers = {}) {
197
+ const readText = readers.readText ?? (path => readFileSync(path, 'utf8'));
198
+ const coreCount = readers.coreCount ?? (() => os.cpus().length);
199
+ const countWorkers = readers.countWorkers ?? (() => countWorkerProcesses(readers));
200
+ // 08 disk-pressure admission: free disk sampled through the same injectable
201
+ // resolver path as every other live signal, so tests feed synthetic values.
202
+ // Callers supply the evidence/worktree filesystems via `readers.paths`
203
+ // (threaded through `checkWorkerDispatch({ paths })`); without them free
204
+ // disk is unknown and the gate fails closed.
205
+ if (process.platform !== 'linux' && readers.readText === undefined) {
206
+ return { supported: false, reason: `live dispatch signals require Linux /proc (this host: ${process.platform})` };
207
+ }
208
+ const readOptional = (path) => {
209
+ try {
210
+ return readText(path);
211
+ } catch {
212
+ return undefined;
213
+ }
214
+ };
215
+ const cores = coreCount();
216
+ const load = parseLoadAverages(readOptional('/proc/loadavg') ?? '');
217
+ const psi = parseMemoryPsi(readOptional('/proc/pressure/memory') ?? '');
218
+ let workers;
219
+ try {
220
+ workers = countWorkers();
221
+ } catch {
222
+ workers = undefined;
223
+ }
224
+ return {
225
+ supported: true,
226
+ availMemGb: parseMemAvailableGb(readOptional('/proc/meminfo') ?? ''),
227
+ load1: load?.load1,
228
+ cores: Number.isFinite(cores) && cores > 0 ? cores : undefined,
229
+ loadRatio: load && cores ? load.load1 / cores : undefined,
230
+ memPsiAvg10: psi?.avg10,
231
+ memPsiAvg60: psi?.avg60,
232
+ memPsiAvg300: psi?.avg300,
233
+ workers: typeof workers === 'object' ? workers?.total : workers,
234
+ ...(typeof workers === 'object' ? { hostCliProcesses: workers?.hostCliProcesses, workerUnits: workers?.units,
235
+ workerCountingSource: workers?.source, workerGroups: workers?.byGroup } : {}),
236
+ freeDiskGb: sampleFreeDiskGb(readers),
237
+ };
238
+ }
239
+
240
+ /**
241
+ * Evaluate sampled live signals against thresholds. Every breach becomes a
242
+ * BLOCK failure naming its signal. Unknown-but-required signals (threshold
243
+ * configured, signal undetectable) fail closed with reason 'not detectable'.
244
+ */
245
+ function evaluateDispatchGate(live, thresholds) {
246
+ const failures = [];
247
+ if (!live || live.supported === false) {
248
+ return {
249
+ ok: false,
250
+ failures: [{ signal: 'platform', reason: live?.reason ?? 'live host signals unavailable' }],
251
+ thresholds,
252
+ };
253
+ }
254
+ const breach = (signal, actual, threshold, reason) => failures.push({ signal, actual, threshold, reason });
255
+ if (live.availMemGb === undefined) breach('avail-mem', undefined, thresholds.min_avail_mem_gb, 'MemAvailable not detectable on this host');
256
+ else if (live.availMemGb < thresholds.min_avail_mem_gb) {
257
+ breach('avail-mem', live.availMemGb, thresholds.min_avail_mem_gb, `available ${live.availMemGb.toFixed(1)}GB < ${thresholds.min_avail_mem_gb}GB`);
258
+ }
259
+ if (live.loadRatio === undefined) breach('load', undefined, thresholds.max_load_ratio, 'load average not detectable on this host');
260
+ else if (live.loadRatio > thresholds.max_load_ratio) {
261
+ breach('load', live.loadRatio, thresholds.max_load_ratio, `load ratio ${live.loadRatio.toFixed(2)} > ${thresholds.max_load_ratio}`);
262
+ }
263
+ if (live.memPsiAvg10 === undefined) breach('mem-psi-avg10', undefined, thresholds.max_mem_psi_avg10, '/proc/pressure/memory not detectable on this host');
264
+ else if (live.memPsiAvg10 > thresholds.max_mem_psi_avg10) {
265
+ breach('mem-psi-avg10', live.memPsiAvg10, thresholds.max_mem_psi_avg10, `memory PSI avg10 ${live.memPsiAvg10} > ${thresholds.max_mem_psi_avg10}`);
266
+ }
267
+ if (live.memPsiAvg60 === undefined) breach('mem-psi-avg60', undefined, thresholds.max_mem_psi_avg60, '/proc/pressure/memory not detectable on this host');
268
+ else if (live.memPsiAvg60 > thresholds.max_mem_psi_avg60) {
269
+ breach('mem-psi-avg60', live.memPsiAvg60, thresholds.max_mem_psi_avg60, `memory PSI avg60 ${live.memPsiAvg60} > ${thresholds.max_mem_psi_avg60}`);
270
+ }
271
+ if (thresholds.max_workers !== undefined) {
272
+ if (live.workers === undefined) breach('workers', undefined, thresholds.max_workers, 'worker count not detectable on this host');
273
+ else if (live.workers >= thresholds.max_workers) {
274
+ breach('workers', live.workers, thresholds.max_workers, `${live.workers} running workers >= ${thresholds.max_workers}`);
275
+ }
276
+ }
277
+ // 08 disk-pressure admission: unknown-but-required free disk fails closed,
278
+ // like every other required signal; under-threshold free disk blocks.
279
+ // Pre-sampled NaN/Infinity/negative readings are rejected here too, so a
280
+ // forged or broken sample can never satisfy the gate.
281
+ if (thresholds.min_free_disk_gb !== undefined && thresholds.min_free_disk_gb > 0) {
282
+ const disk = live.freeDiskGb;
283
+ if (disk === undefined || !Number.isFinite(disk) || disk < 0) {
284
+ breach('free-disk', undefined, thresholds.min_free_disk_gb, 'free disk not detectable on this host');
285
+ } else if (disk < thresholds.min_free_disk_gb) {
286
+ breach('free-disk', disk, thresholds.min_free_disk_gb, `free ${disk.toFixed(1)}GB < ${thresholds.min_free_disk_gb}GB`);
287
+ }
288
+ }
289
+ return { ok: failures.length === 0, failures, thresholds };
290
+ }
291
+
292
+
293
+ export { parseMemAvailableGb, parseMemoryPsi, parseLoadAverages, listWorkerUnits, countWorkerUnits, countWorkerProcesses, defaultCountWorkers, readLiveHostResources, evaluateDispatchGate };
@@ -0,0 +1,22 @@
1
+ // Keep automatic redeployment from changing the explicitly installed selection.
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
3
+ import { resolve } from 'node:path';
4
+ import { REGISTRY_ID_TO_USE_NAME } from './framework-aliases.js';
5
+ const selection = new AsyncLocalStorage();
6
+ export function withInstalledSelection(project, installed, deploy) {
7
+ return selection.run({ project: resolve(project), installed: structuredClone(installed) }, deploy);
8
+ }
9
+ export function preserveInstalledSelection(project, config) {
10
+ const current = selection.getStore();
11
+ if (!current || current.project !== resolve(project))
12
+ return config;
13
+ const guarded = { ...config };
14
+ if (current.installed === undefined)
15
+ delete guarded.installed;
16
+ else
17
+ guarded.installed = Object.fromEntries(Object.entries(current.installed).map(([id, entry]) => [
18
+ id, structuredClone(config.installed?.[REGISTRY_ID_TO_USE_NAME[id] ?? id] ?? config.installed?.[id] ?? entry),
19
+ ]));
20
+ return guarded;
21
+ }
22
+ //# sourceMappingURL=installed-selection.js.map
@@ -125,8 +125,35 @@ export function resolveWorkerContextProvidersFromConfig(config) {
125
125
  }
126
126
  return { providers, skipped };
127
127
  }
128
- /** AIWG-managed rule-section markers written into a deployed AGENTS.md. */
129
- const WORKER_CONTEXT_RULE_MARKER = /<!--\s*AIWG:[A-Za-z0-9_-]+:(start|end)\s*-->/;
128
+ /** Complete managed sections are required; a bootstrap marker alone is insufficient. */
129
+ function ruleSection(content, owner) {
130
+ return content.match(new RegExp(`<!--\\s*AIWG:${owner}:start\\s*-->([\\s\\S]*?)<!--\\s*AIWG:${owner}:end\\s*-->`))?.[1].trim() ?? '';
131
+ }
132
+ function readNonempty(file) {
133
+ try {
134
+ return readFileSync(file, 'utf8').trim();
135
+ }
136
+ catch {
137
+ return '';
138
+ }
139
+ }
140
+ function hasRuleBootstrap(content, workdir, provider, rulesDir) {
141
+ // Older complete inline deployments remain usable during migration.
142
+ if (ruleSection(content, 'rule-startup'))
143
+ return true;
144
+ const hook = ruleSection(content, `rule-hook-${provider}`);
145
+ if (!ruleSection(content, 'rule-core') || !rulesDir)
146
+ return false;
147
+ const entry = path.join(rulesDir, 'RULES-INDEX.md');
148
+ if (!hook.includes(`\`${entry.replaceAll('\\', '/')}\``))
149
+ return false;
150
+ const indexFile = path.resolve(workdir, entry);
151
+ const index = readNonempty(indexFile);
152
+ if (!index)
153
+ return false;
154
+ return [...index.matchAll(/\]\(\.\/([^)]*\.md)\)/g)]
155
+ .every(match => Boolean(readNonempty(path.resolve(path.dirname(indexFile), match[1]))));
156
+ }
130
157
  /**
131
158
  * Check that a worker workdir already carries one provider's bootstrap:
132
159
  * the kernel artifact dirs (`use all` writes kernel skills, rules,
@@ -157,8 +184,10 @@ export function workerContextBootstrapStatus({ workdir, provider }) {
157
184
  catch {
158
185
  entries = null;
159
186
  }
160
- if (!entries || entries.length === 0)
187
+ if (!entries || entries.length === 0 || (dir === paths?.rules &&
188
+ !entries.some(name => /\.(md|mdc)$/.test(name) && readNonempty(path.join(absolute, name))))) {
161
189
  missing.push(`provider dir '${dir}'`);
190
+ }
162
191
  }
163
192
  if ((definition.context?.bootstrapTargets ?? []).includes('AGENTS.md')) {
164
193
  let content = null;
@@ -168,7 +197,7 @@ export function workerContextBootstrapStatus({ workdir, provider }) {
168
197
  catch {
169
198
  content = null;
170
199
  }
171
- if (!content || !WORKER_CONTEXT_RULE_MARKER.test(content)) {
200
+ if (!content || !hasRuleBootstrap(content, workdir, definition.id, paths?.rules ?? null)) {
172
201
  missing.push('AGENTS.md rule sections');
173
202
  }
174
203
  }
@@ -0,0 +1 @@
1
+ export const WORKER_INVOCATION_MARKER: 'AIWG_WORKER_INVOCATION_ID';
@@ -0,0 +1,2 @@
1
+ // Shared environment protocol identifying an AIWG worker and its descendants.
2
+ export const WORKER_INVOCATION_MARKER = 'AIWG_WORKER_INVOCATION_ID';
@@ -0,0 +1,74 @@
1
+ // Sign and verify D29 first-access records with the existing effect-ledger trust.
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import Ajv2020 from 'ajv/dist/2020.js';
6
+ import addFormats from 'ajv-formats';
7
+ import { activeKey, assertKeyring, checkSignature } from '../../effects/keyring.js';
8
+ import { canonicalJson } from '../../security/artifact-trust.js';
9
+ import { heldoutDigest } from './contract.js';
10
+ export const HELDOUT_ACCESS_PAYLOAD_TYPE = 'application/vnd.aiwg.decision-d29-access+json';
11
+ let validator;
12
+ export function validateHeldoutAccess(value) {
13
+ if (!validator) {
14
+ const here = dirname(fileURLToPath(import.meta.url));
15
+ const name = 'D29Study.v10.schema.json';
16
+ const root = [resolve(here, '../../../schemas/decision'), resolve(here, '../../../../schemas/decision')]
17
+ .find(path => existsSync(resolve(path, name)));
18
+ if (!root)
19
+ throw new Error('first-access schema unavailable');
20
+ const schema = JSON.parse(readFileSync(resolve(root, name), 'utf8'));
21
+ const ajv = new Ajv2020({ strict: true });
22
+ addFormats(ajv);
23
+ validator = ajv.compile(schema);
24
+ }
25
+ if (!validator(value))
26
+ throw new Error('first-access record schema invalid');
27
+ }
28
+ const payload = (body) => Buffer.from(canonicalJson(body), 'utf8');
29
+ /** The keyring must come from protected host state, never from the access record. */
30
+ export function verifyHeldoutAccess(access, keyring) {
31
+ if (!access?.signature)
32
+ throw new Error('first-access signature missing');
33
+ if (typeof access.firstTestAccessAt !== 'string' || !Number.isFinite(Date.parse(access.firstTestAccessAt))) {
34
+ throw new Error('first-access timestamp is not a valid date-time');
35
+ }
36
+ validateHeldoutAccess(access);
37
+ try {
38
+ assertKeyring(keyring);
39
+ }
40
+ catch {
41
+ throw new Error('first-access keyring invalid or unavailable');
42
+ }
43
+ const { signature, ...body } = access;
44
+ const result = checkSignature(keyring, signature.keyid, signature.sig, HELDOUT_ACCESS_PAYLOAD_TYPE, payload(body), access.firstTestAccessAt);
45
+ if (result !== 'ok')
46
+ throw new Error(`first-access signature ${result}`);
47
+ }
48
+ /** Called at first access, before any test dispatch; never re-sign records during scoring. */
49
+ export function signHeldoutAccess(body, trust) {
50
+ assertKeyring(trust.keyring);
51
+ if (activeKey(trust.keyring).keyid !== trust.signingKey.keyid)
52
+ throw new Error('first-access signing key is not active');
53
+ const record = { ...body, signature: { keyid: trust.signingKey.keyid,
54
+ sig: trust.signingKey.signPae(HELDOUT_ACCESS_PAYLOAD_TYPE, payload(body)) } };
55
+ verifyHeldoutAccess(record, trust.keyring);
56
+ return record;
57
+ }
58
+ /** Uses the same configured delivery ledger as worker qualification; does not provision keys. */
59
+ export async function createHeldoutAccess(bundle, firstTestAccessAt, projectDir, injected, anchoredAt = bundle.preregistration.frozenAt) {
60
+ let trust = injected;
61
+ if (!trust) {
62
+ const { effectSession, openLedger } = await import('../../effects/host.js');
63
+ const { readLedgerKeyring } = await import('../../effects/ledger.js');
64
+ const ledger = openLedger(await effectSession(projectDir));
65
+ const keyring = await readLedgerKeyring(ledger);
66
+ if (!keyring)
67
+ throw new Error('first-access effect-ledger keyring unavailable');
68
+ trust = { keyring, signingKey: await ledger.signingKey() };
69
+ }
70
+ return signHeldoutAccess({ schemaVersion: 'decision-d29-access/v2', runId: bundle.approval.runId,
71
+ analysisDigest: bundle.preregistration.studyAnalysisDigest, frozenBundleDigest: heldoutDigest(bundle),
72
+ anchoredAt, firstTestAccessAt, reference: `heldout-run:${bundle.approval.runId}` }, trust);
73
+ }
74
+ //# sourceMappingURL=access.js.map
@@ -132,6 +132,7 @@ export async function validateHeldoutPhaseAccess(bundle, runsRoot, priorRuns, ac
132
132
  if (calibrationApproval(frozen.bundle) && !record.lineage.some(item => item.runId === frozen.bundle.approval.runId))
133
133
  throw new HeldoutError('calibration-phase-lineage');
134
134
  }
135
+ return record.sealedAt;
135
136
  }
136
137
  catch {
137
138
  throw new HeldoutError('calibration-phase-access');
@@ -14,6 +14,7 @@ import { redactText } from '../../governance/redaction.js';
14
14
  import { heldoutDigest, heldoutRequest, heldoutReservationMicros, heldoutReservationTokens, HeldoutError, HELDOUT_ENV_GATE, heldoutRowsInScope, heldoutResumeAttempts, heldoutPendingRequests, planHeldoutCollection, validateHeldoutBundle } from './contract.js';
15
15
  import { appendHeldoutSpend, appendHeldoutEvent, heldoutDirectory, heldoutEvidenceDigest, heldoutRunsRoot, readHeldoutFile, readHeldoutJournal, reconcileHeldoutBaseline, scanHeldoutSpend, writeHeldoutFile, validateHeldoutJournal, heldoutCollectionAllowance } from './journal.js';
16
16
  import { readHeldoutFrozen, sealHeldoutCalibrationPhase, validateHeldoutPhaseAccess } from './calibration.js';
17
+ import { createHeldoutAccess } from './access.js';
17
18
  import { D17_MULTIFACT_CALIBRATION_NOT_AFTER, usesD17MultifactGenerator } from './study-generators.js';
18
19
  const byteDigest = (bytes) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
19
20
  const delay = (ms) => new Promise(done => setTimeout(done, ms));
@@ -88,13 +89,19 @@ export async function collectHeldoutStudy(options) {
88
89
  }
89
90
  }
90
91
  const testPhaseAccessAt = a.calibration.mode === 'staged' && a.calibration.phase === 'test' ? new Date(started).toISOString() : null;
91
- await validateHeldoutPhaseAccess(bundle, heldoutRunsRoot(options.artifactRoot), prior.runs, testPhaseAccessAt);
92
+ const accessAnchoredAt = await validateHeldoutPhaseAccess(bundle, heldoutRunsRoot(options.artifactRoot), prior.runs, testPhaseAccessAt);
92
93
  if (testPhaseAccessAt !== null)
93
94
  await planHeldoutCollection(bundle, options.trustedApprovalDigest);
94
95
  const rows = heldoutRowsInScope(bundle);
95
96
  const run = join(heldoutRunsRoot(options.artifactRoot), a.runId);
96
97
  await mkdir(run, { mode: 0o700 });
97
98
  await writeHeldoutFile(join(run, 'frozen.json'), { schemaVersion: 'decision-heldout-frozen/v1', source: offline ? 'injected-transport' : 'provider', approval: { study: a.study, runId: a.runId }, bundle, baselineDigests, testPhaseAccessAt, collectionStartedAt: new Date(started).toISOString(), digest: heldoutDigest(bundle), priorRuns: prior.runs.filter(r => r.study === a.study && r.corpusDigest === a.corpusDigest) });
99
+ if (a.study === 'D29' && testPhaseAccessAt !== null) {
100
+ if (offline && !offline.accessSigning)
101
+ throw new HeldoutError('offline-access-signing-required');
102
+ const access = await createHeldoutAccess(bundle, testPhaseAccessAt, options.sourceRoot, offline?.accessSigning, accessAnchoredAt);
103
+ await writeHeldoutFile(join(run, 'access.json'), access);
104
+ }
98
105
  const events = [];
99
106
  const allowance = heldoutCollectionAllowance(a, prior);
100
107
  let calls = 0, reserved = 0, accounted = 0, tokens = 0, lastDispatch = started - plan.minDispatchIntervalMs;
@@ -408,7 +415,7 @@ export async function scoreHeldoutStudy(input) {
408
415
  const approvedCalibration = structuredClone(approval.calibration);
409
416
  const calibrated = approvedCalibration.mode === 'uncalibrated-diagnostic'
410
417
  || approvedCalibration.mode === 'staged' && approvedCalibration.phase === 'calibration' ? false : null;
411
- const diagnostics = await input.module.score({ corpus: { ...corpus, rows }, preregistration, attempts, gold: input.gold,
418
+ const diagnostics = await input.module.score({ frozen, corpus: { ...corpus, rows }, preregistration, attempts, gold: input.gold,
412
419
  integrity: structuredClone(input.integrity), approvedCalibration: structuredClone(approvedCalibration), calibrated });
413
420
  if (calibrated === false && (!diagnostics || typeof diagnostics !== 'object'
414
421
  || diagnostics.calibrated !== false
@@ -63,13 +63,12 @@ export function fileDigestVerifier(options) {
63
63
  if (errno(error) !== 'ENOENT' && errno(error) !== 'ENOTDIR')
64
64
  return unknown('container-unreadable');
65
65
  // Missing: `absent` only when the nearest existing ancestor is itself contained.
66
- let parent = dirname(lexical);
66
+ let parent = lexical;
67
67
  for (;;) {
68
+ // An existing but unresolvable component (such as a dangling
69
+ // symlink) is unknown. Never step above it and call the file absent.
68
70
  try {
69
- const realParent = await realpath(parent);
70
- if (realParent !== root && !inside(root, realParent))
71
- return unknown('container-unreadable');
72
- break;
71
+ await lstat(parent);
73
72
  }
74
73
  catch (inner) {
75
74
  if (errno(inner) !== 'ENOENT' && errno(inner) !== 'ENOTDIR')
@@ -77,6 +76,18 @@ export function fileDigestVerifier(options) {
77
76
  if (parent === dirname(parent))
78
77
  return unknown('container-unreadable');
79
78
  parent = dirname(parent);
79
+ continue;
80
+ }
81
+ try {
82
+ const realParent = await realpath(parent);
83
+ if (realParent !== root && !inside(root, realParent))
84
+ return unknown('container-unreadable');
85
+ if (!(await lstat(realParent)).isDirectory())
86
+ return unknown('container-unreadable');
87
+ break;
88
+ }
89
+ catch {
90
+ return unknown('container-unreadable');
80
91
  }
81
92
  }
82
93
  const evidence = { path, expectedDigest: digest, found: false };
@@ -97,6 +108,12 @@ export function fileDigestVerifier(options) {
97
108
  return unknown('container-unreadable');
98
109
  }
99
110
  const evidence = { path, expectedDigest: digest, actualDigest: actual, found: true };
111
+ // Query-only callers may ask whether a digest is absent. Replay callers
112
+ // must also prove that existing bytes are the recorded pre-write state.
113
+ if (actual !== digest && request.expected.previousDigest !== undefined
114
+ && actual !== request.expected.previousDigest) {
115
+ return { ...unknown('evidence-conflict'), evidence };
116
+ }
100
117
  return actual === digest
101
118
  ? { result: 'present', reason: 'digest-match', complete: true, evidence }
102
119
  : { result: 'absent', reason: 'complete-query-no-match', complete: true, evidence };