@aiwg/cli 2026.10.15 → 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 (180) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +23 -9
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/cli/handlers/daemon.js +17 -1
  26. package/dist/src/cli/handlers/doctor-args.js +10 -5
  27. package/dist/src/cli/handlers/doctor-help.js +4 -1
  28. package/dist/src/cli/handlers/index.js +2 -2
  29. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  30. package/dist/src/cli/handlers/models.js +3 -2
  31. package/dist/src/cli/handlers/regenerate.js +8 -16
  32. package/dist/src/cli/handlers/sessions.js +7 -7
  33. package/dist/src/cli/handlers/subcommands.js +8 -0
  34. package/dist/src/cli/handlers/update.js +157 -0
  35. package/dist/src/cli/handlers/use.js +14 -4
  36. package/dist/src/cli/handlers/utilities.js +3 -560
  37. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  38. package/dist/src/cli/services/deployment-verification.js +0 -1
  39. package/dist/src/config/aiwg-config.js +2 -1
  40. package/dist/src/config/authorization-cli.js +7 -3
  41. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  42. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  43. package/dist/src/config/framework-aliases.js +12 -0
  44. package/dist/src/config/host-resource-report.d.mts +19 -0
  45. package/dist/src/config/host-resource-report.mjs +80 -0
  46. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  47. package/dist/src/config/host-resource-runtime.mjs +293 -0
  48. package/dist/src/config/installed-selection.js +22 -0
  49. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  50. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  51. package/dist/src/decision/heldout/access.js +74 -0
  52. package/dist/src/decision/heldout/calibration.js +1 -0
  53. package/dist/src/decision/heldout/collector.js +8 -1
  54. package/dist/src/effects/verifiers/file.js +22 -5
  55. package/dist/src/extensions/claude-attribution.js +82 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  57. package/dist/src/extensions/commands/daemon.js +109 -0
  58. package/dist/src/extensions/commands/definitions.js +5 -89
  59. package/dist/src/gates/heldout.js +17 -7
  60. package/dist/src/lint/check-patterns.js +163 -0
  61. package/dist/src/lint/checks.js +268 -0
  62. package/dist/src/lint/reference-resolution.js +54 -0
  63. package/dist/src/lint/runner.js +3 -465
  64. package/dist/src/mcp/helpers.mjs +11 -1
  65. package/dist/src/memory/project-registry.js +44 -4
  66. package/dist/src/models/worker-plan.js +36 -5
  67. package/dist/src/models/wrapper-deployment.js +25 -12
  68. package/dist/src/models/wrapper-enforcement.js +47 -7
  69. package/dist/src/network-analysis/research.js +2 -1
  70. package/dist/src/policy/hitl-check.js +14 -4
  71. package/dist/src/policy/hitl-consume.js +54 -0
  72. package/dist/src/policy/hitl-receipt.js +2 -0
  73. package/dist/src/policy/hitl.js +11 -3
  74. package/dist/src/providers/provider-context-contracts.js +162 -0
  75. package/dist/src/providers/provider-definition-schema.js +136 -0
  76. package/dist/src/providers/provider-definitions.js +8 -1298
  77. package/dist/src/providers/provider-seeds-1.js +360 -0
  78. package/dist/src/providers/provider-seeds-2.js +387 -0
  79. package/dist/src/providers/provider-seeds-3.js +262 -0
  80. package/dist/src/research/clients/arxiv.js +4 -30
  81. package/dist/src/research/clients/base.js +48 -22
  82. package/dist/src/research/identity.js +34 -2
  83. package/dist/src/research/query-cli.js +3 -87
  84. package/dist/src/research/query-options.js +87 -0
  85. package/dist/src/research/reference-match.js +70 -24
  86. package/dist/src/research/services/acquisition.js +9 -7
  87. package/dist/src/research/services/citation.js +5 -2
  88. package/dist/src/research/types.js +2 -0
  89. package/dist/src/serve/mission-conductor.js +48 -4
  90. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  91. package/dist/src/sessions/adapters/grok-build.js +14 -7
  92. package/dist/src/sessions/workspace-discovery.js +5 -5
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +16 -46
  94. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  95. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  96. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  97. package/dist/src/smiths/context-pipeline/generator.js +9 -10
  98. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  99. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  100. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  101. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  102. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  103. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  104. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  105. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  106. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  107. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  108. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  109. package/package.json +10 -1
  110. package/schemas/decision/D29Study.v10.schema.json +65 -0
  111. package/tools/agents/deploy-agents.mjs +10 -0
  112. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  113. package/tools/agents/providers/context-write.mjs +4 -0
  114. package/tools/agents/providers/pi.mjs +3 -1
  115. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  116. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  117. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  118. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  119. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  120. package/tools/daemon/README.md +511 -0
  121. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  122. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  123. package/tools/daemon/agent-supervisor.mjs +299 -0
  124. package/tools/daemon/automation-engine.mjs +310 -0
  125. package/tools/daemon/autonomous-engine.mjs +346 -0
  126. package/tools/daemon/behavior-loader.mjs +316 -0
  127. package/tools/daemon/behavior.mjs +174 -0
  128. package/tools/daemon/concierge/intent-router.mjs +401 -0
  129. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  130. package/tools/daemon/concierge/response-translator.mjs +462 -0
  131. package/tools/daemon/config.mjs +377 -0
  132. package/tools/daemon/cron-scheduler.mjs +178 -0
  133. package/tools/daemon/daemon-main.mjs +1169 -0
  134. package/tools/daemon/event-router.mjs +84 -0
  135. package/tools/daemon/file-watcher.mjs +383 -0
  136. package/tools/daemon/index.mjs +1181 -0
  137. package/tools/daemon/init-profile.mjs +124 -0
  138. package/tools/daemon/ipc-client.mjs +197 -0
  139. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  140. package/tools/daemon/ipc-server.mjs +275 -0
  141. package/tools/daemon/maintenance-owner.mjs +79 -0
  142. package/tools/daemon/memory-manager.mjs +386 -0
  143. package/tools/daemon/message-router.mjs +194 -0
  144. package/tools/daemon/provider-watcher.mjs +585 -0
  145. package/tools/daemon/pty-adapter.mjs +420 -0
  146. package/tools/daemon/repl-chat.mjs +359 -0
  147. package/tools/daemon/resource-bounds.mjs +88 -0
  148. package/tools/daemon/sandbox-transport.mjs +295 -0
  149. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  150. package/tools/daemon/task-store.mjs +450 -0
  151. package/tools/daemon/tmux-manager.mjs +324 -0
  152. package/tools/daemon/update-policy.mjs +517 -0
  153. package/tools/daemon/web-server.mjs +399 -0
  154. package/tools/daemon/web-ui/index.html +585 -0
  155. package/tools/daemon/web-ui/styles.css +156 -0
  156. package/tools/docker/Dockerfile.daemon +35 -0
  157. package/tools/docker/container-manager.mjs +291 -0
  158. package/tools/messaging/adapter-registry.mjs +230 -0
  159. package/tools/messaging/adapters/base.mjs +326 -0
  160. package/tools/messaging/adapters/discord.mjs +462 -0
  161. package/tools/messaging/adapters/slack.mjs +402 -0
  162. package/tools/messaging/adapters/telegram.mjs +552 -0
  163. package/tools/messaging/chat-handler.mjs +297 -0
  164. package/tools/messaging/command-router.mjs +269 -0
  165. package/tools/messaging/event-bus.mjs +199 -0
  166. package/tools/messaging/index.mjs +456 -0
  167. package/tools/messaging/message-formatter.mjs +320 -0
  168. package/tools/messaging/room-manager.mjs +277 -0
  169. package/tools/messaging/types.mjs +94 -0
  170. package/tools/providers/pi-bridge-policy.mjs +4 -0
  171. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  172. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  173. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  174. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  175. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  176. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  177. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  178. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  179. package/tools/ralph-external/session-launcher.mjs +7 -7
  180. 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
@@ -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;
@@ -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 };
@@ -0,0 +1,82 @@
1
+ // Merge and undo Claude attribution defaults, and inspect effective settings offline.
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ const DEFAULTS = { commit: '', pr: '', sessionUrl: false };
6
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ export function mergeClaudeAttribution(settings, warnings) {
8
+ if (settings.attribution !== undefined && !object(settings.attribution)) {
9
+ warnings.push('Preserved operator attribution setting; expected an object.');
10
+ return;
11
+ }
12
+ if (settings.aiwg !== undefined && !object(settings.aiwg)) {
13
+ warnings.push('Preserved the existing non-object "aiwg" setting; AIWG attribution defaults were not merged.');
14
+ return;
15
+ }
16
+ const attribution = (settings.attribution ??= {});
17
+ const aiwg = (settings.aiwg ?? {});
18
+ const owned = new Set(Array.isArray(aiwg.attributionKeys) ? aiwg.attributionKeys : []);
19
+ for (const [key, value] of Object.entries(DEFAULTS)) {
20
+ if (attribution[key] === undefined) {
21
+ attribution[key] = value;
22
+ owned.add(key);
23
+ }
24
+ else if (attribution[key] !== value) {
25
+ warnings.push(`Preserved operator attribution.${key}; attribution remains enabled. Clear it explicitly to disable attribution.`);
26
+ }
27
+ }
28
+ if (owned.size) {
29
+ aiwg.attributionKeys = [...owned];
30
+ settings.aiwg = aiwg;
31
+ }
32
+ }
33
+ export function undoClaudeAttribution(settings) {
34
+ if (!object(settings.aiwg) || !Array.isArray(settings.aiwg.attributionKeys))
35
+ return false;
36
+ const attribution = settings.attribution;
37
+ if (object(attribution)) {
38
+ for (const key of settings.aiwg.attributionKeys) {
39
+ if (Object.hasOwn(DEFAULTS, key) && attribution[key] === DEFAULTS[key]) {
40
+ delete attribution[key];
41
+ }
42
+ }
43
+ if (Object.keys(attribution).length === 0)
44
+ delete settings.attribution;
45
+ }
46
+ delete settings.aiwg.attributionKeys;
47
+ if (Object.keys(settings.aiwg).length === 0)
48
+ delete settings.aiwg;
49
+ return true;
50
+ }
51
+ /** Higher-precedence files override individual keys; missing keys use Claude defaults. */
52
+ export async function checkClaudeAttribution(projectPath, home = os.homedir(), managedFile = path.join(process.platform === 'darwin' ? '/Library/Application Support/ClaudeCode'
53
+ : process.platform === 'win32' ? path.join(process.env.ProgramFiles || 'C:\\Program Files', 'ClaudeCode')
54
+ : '/etc/claude-code', 'managed-settings.json')) {
55
+ const effective = { commit: '(Claude default)', pr: '(Claude default)', sessionUrl: true };
56
+ const sources = [path.join(home, '.claude/settings.json'), path.join(projectPath, '.claude/settings.json'),
57
+ path.join(projectPath, '.claude/settings.local.json'), managedFile];
58
+ try {
59
+ for (const file of sources) {
60
+ let settings;
61
+ try {
62
+ settings = JSON.parse(await fs.readFile(file, 'utf8'));
63
+ }
64
+ catch (err) {
65
+ if (err.code === 'ENOENT')
66
+ continue;
67
+ throw err;
68
+ }
69
+ if (settings.attribution === false)
70
+ Object.assign(effective, DEFAULTS);
71
+ else if (object(settings.attribution))
72
+ Object.assign(effective, settings.attribution);
73
+ }
74
+ const enabled = Object.keys(DEFAULTS).filter(key => effective[key] !== DEFAULTS[key]);
75
+ return enabled.length ? { status: 'warn', message: `Effective Claude attribution enabled: ${enabled.join(', ')}. Run: aiwg use all --provider claude. Existing operator values are preserved; clear those keys explicitly in the overriding settings file. Session-only overrides are not inspected.` }
76
+ : { status: 'ok', message: 'Claude attribution disabled by user/project/managed settings (session-only overrides are not inspected).' };
77
+ }
78
+ catch (err) {
79
+ return { status: 'warn', message: `Could not inspect Claude attribution: ${err instanceof Error ? err.message : String(err)}. Run: aiwg use all --provider claude after repairing settings JSON.` };
80
+ }
81
+ }
82
+ //# sourceMappingURL=claude-attribution.js.map