@aiwg/cli 2026.11.5 → 2026.11.6

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 (150) hide show
  1. package/agentic/code/providers/model-capabilities.v1.json +9 -9
  2. package/bin/aiwg.mjs +6 -4
  3. package/dist/src/activity-log/cli.js +1 -1
  4. package/dist/src/agents/agent-deployer.js +1 -1
  5. package/dist/src/artifacts/audit/types.js +1 -1
  6. package/dist/src/artifacts/discover-facets.js +1 -1
  7. package/dist/src/artifacts/enrichment/prompt.js +1 -1
  8. package/dist/src/artifacts/enrichment/types.js +1 -1
  9. package/dist/src/artifacts/views/definition.js +1 -1
  10. package/dist/src/artifacts/views/types.js +1 -1
  11. package/dist/src/catalog/cli.js +1 -1
  12. package/dist/src/catalog/cli.mjs +1 -1
  13. package/dist/src/catalog/loader.js +1 -1
  14. package/dist/src/catalog/loader.mjs +1 -1
  15. package/dist/src/catalog/types.js +1 -1
  16. package/dist/src/cli/cli-extension-loader.js +19 -5
  17. package/dist/src/cli/cli-extension-paths.js +65 -0
  18. package/dist/src/cli/handlers/best-practices-audit.js +1 -1
  19. package/dist/src/cli/handlers/help.js +3 -4
  20. package/dist/src/cli/handlers/index.js +1 -1
  21. package/dist/src/cli/handlers/marketplace-plugin-search.js +37 -0
  22. package/dist/src/cli/handlers/marketplace.js +3 -1
  23. package/dist/src/cli/handlers/models.js +1 -1
  24. package/dist/src/cli/handlers/ralph-launcher.js +8 -2
  25. package/dist/src/cli/handlers/ralph.js +1 -1
  26. package/dist/src/cli/handlers/runtime-info.js +1 -1
  27. package/dist/src/cli/handlers/scaffolding.js +2 -2
  28. package/dist/src/cli/handlers/script-runner.js +1 -1
  29. package/dist/src/cli/handlers/sdlc-accelerate.js +1 -1
  30. package/dist/src/cli/handlers/subcommands-bundles.js +1 -1
  31. package/dist/src/cli/handlers/subcommands-list-format.js +19 -1
  32. package/dist/src/cli/handlers/types.js +1 -1
  33. package/dist/src/cli/handlers/use.js +2 -2
  34. package/dist/src/cli/handlers/utilities.js +1 -1
  35. package/dist/src/cli/handlers/version.js +1 -1
  36. package/dist/src/cli/handlers/workspace.js +1 -1
  37. package/dist/src/cli/help-generator.js +9 -11
  38. package/dist/src/cli/hooks/builtin/activity-log-hook.js +1 -1
  39. package/dist/src/cli/router.js +1 -1
  40. package/dist/src/cli/workflow-orchestrator.js +1 -1
  41. package/dist/src/config/worker-context.js +37 -7
  42. package/dist/src/config/worker-parallelism.js +11 -0
  43. package/dist/src/contributors/detect.js +1 -1
  44. package/dist/src/contributors/discover.js +1 -1
  45. package/dist/src/contributors/heuristic.js +1 -1
  46. package/dist/src/contributors/index.js +1 -1
  47. package/dist/src/contributors/types.js +1 -1
  48. package/dist/src/contributors/validation.js +1 -1
  49. package/dist/src/effects/worker-delivery.js +83 -0
  50. package/dist/src/extensions/capability-index.js +1 -1
  51. package/dist/src/extensions/commands/definitions.js +2 -2
  52. package/dist/src/extensions/deployment-registration.js +1 -1
  53. package/dist/src/extensions/index.js +1 -1
  54. package/dist/src/extensions/loader.js +1 -1
  55. package/dist/src/extensions/manifest.js +4 -2
  56. package/dist/src/extensions/project-local-activity.js +1 -1
  57. package/dist/src/extensions/project-local-discovery.js +2 -2
  58. package/dist/src/extensions/project-local-doctor.js +7 -3
  59. package/dist/src/extensions/project-local-promote.js +3 -3
  60. package/dist/src/extensions/project-local-remove.js +3 -3
  61. package/dist/src/extensions/project-local-scaffold.js +1 -1
  62. package/dist/src/extensions/registry.js +1 -1
  63. package/dist/src/extensions/shadow-resolver.js +1 -1
  64. package/dist/src/extensions/types.js +1 -1
  65. package/dist/src/extensions/upstream-registry.js +1 -1
  66. package/dist/src/extensions/validation.js +1 -1
  67. package/dist/src/intake/git-history-analyzer.js +1 -1
  68. package/dist/src/kb/cli.js +1 -1
  69. package/dist/src/marketplace/plugin-directory.js +36 -0
  70. package/dist/src/marketplace/plugin-search.js +180 -0
  71. package/dist/src/mcp/cli.mjs +2 -2
  72. package/dist/src/mcp/helpers.mjs +1 -1
  73. package/dist/src/mcp/http-tools.mjs +8 -6
  74. package/dist/src/mcp/http-transport.mjs +3 -1
  75. package/dist/src/mcp/server.mjs +1 -1
  76. package/dist/src/mcp/tools/command-run.mjs +1 -1
  77. package/dist/src/mcp/tools/discovery.mjs +1 -1
  78. package/dist/src/mcp/tools/subsystems.mjs +1 -1
  79. package/dist/src/mcp/tools/worker-invoke.mjs +68 -22
  80. package/dist/src/mcp/tools/worker-local-only-preflight.mjs +79 -0
  81. package/dist/src/mcp/tools/worker-recorded-launch.mjs +26 -0
  82. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +33 -6
  83. package/dist/src/mcp/tools/worker-verify-deliver-schema.mjs +33 -0
  84. package/dist/src/mcp/tools/worker-verify-deliver.mjs +27 -0
  85. package/dist/src/models/catalog-policy.js +2 -2
  86. package/dist/src/models/conductor-data-policy.mjs +83 -14
  87. package/dist/src/models/config-loader.js +2 -2
  88. package/dist/src/models/index.js +2 -2
  89. package/dist/src/models/local-endpoint-models.js +155 -0
  90. package/dist/src/models/model-capabilities.v1.json +9 -9
  91. package/dist/src/models/model-discovery.js +9 -5
  92. package/dist/src/models/opencode-worker-model.mjs +16 -0
  93. package/dist/src/models/resolver.js +2 -2
  94. package/dist/src/models/worker-installation.mjs +5 -3
  95. package/dist/src/models/worker-plan.js +1 -1
  96. package/dist/src/plugin/plugin-installer.js +2 -2
  97. package/dist/src/plugin/registry-validator.js +2 -2
  98. package/dist/src/plugin/skill-command-translator.js +1 -1
  99. package/dist/src/rlm/cache/hash.js +1 -1
  100. package/dist/src/rlm/cache/store.js +1 -1
  101. package/dist/src/rlm/cache/types.js +1 -1
  102. package/dist/src/serve/worker-invocation-preparation.js +13 -0
  103. package/dist/src/serve/worker-invocation.js +21 -6
  104. package/dist/src/skills/run.js +0 -11
  105. package/dist/src/smiths/agentsmith/generator.js +1 -1
  106. package/dist/src/smiths/context-pipeline/index.js +1 -1
  107. package/dist/src/smiths/context-pipeline/provider-policy.js +1 -1
  108. package/dist/src/smiths/context-pipeline/types.js +1 -1
  109. package/dist/src/smiths/mcpsmith/analyzers/cli-analyzer.js +2 -2
  110. package/dist/src/smiths/mcpsmith/generator.js +2 -2
  111. package/dist/src/smiths/mcpsmith/index.js +2 -2
  112. package/dist/src/smiths/mcpsmith/types.js +2 -2
  113. package/dist/src/smiths/skillsmith/collision-detector.js +1 -1
  114. package/dist/src/smiths/skillsmith/namespace-adapter.js +1 -1
  115. package/dist/src/smiths/toolsmith/runtime-discovery.mjs +2 -2
  116. package/dist/src/smiths/toolsmith/types.js +2 -2
  117. package/dist/src/storage/backends/fortemi.js +1 -1
  118. package/dist/src/storage/backends/fs.js +1 -1
  119. package/dist/src/storage/backends/logseq.js +1 -1
  120. package/dist/src/storage/backends/obsidian.js +1 -1
  121. package/dist/src/storage/cli.js +2 -2
  122. package/dist/src/storage/config.js +1 -1
  123. package/dist/src/storage/index.js +1 -1
  124. package/dist/src/storage/subsystem-cli.js +1 -1
  125. package/dist/src/storage/types.js +1 -1
  126. package/dist/src/testing/generators/test-case-generator.js +1 -1
  127. package/dist/src/writing/validation-engine.js +1 -1
  128. package/package.json +11 -1
  129. package/schemas/models/model-catalog.v1.schema.json +6 -3
  130. package/tools/agents/providers/conductor-data-guard.mjs +1 -1
  131. package/tools/ralph-external/lib/mcp-worker-launch.mjs +67 -0
  132. package/tools/ralph-external/lib/opencode-adapter.mjs +9 -7
  133. package/tools/ralph-external/lib/trusted-verification.mjs +1021 -0
  134. package/tools/ralph-external/lib/typed-stop-delivery.mjs +46 -0
  135. package/tools/ralph-external/lib/verification-isolation.mjs +509 -0
  136. package/tools/ralph-external/lib/worker-context.mjs +3 -3
  137. package/tools/ralph-external/lib/worker-delivery-guards.mjs +95 -0
  138. package/tools/ralph-external/lib/worker-delivery-record.mjs +15 -0
  139. package/tools/ralph-external/lib/worker-final.mjs +4 -1
  140. package/tools/ralph-external/lib/worker-isolation-status.mjs +3 -0
  141. package/tools/ralph-external/lib/worker-launch-cli.mjs +8 -0
  142. package/tools/ralph-external/lib/worker-local-only-paths.mjs +45 -0
  143. package/tools/ralph-external/lib/worker-prompt.mjs +4 -1
  144. package/tools/ralph-external/lib/worker-retry-evidence.mjs +2 -1
  145. package/tools/ralph-external/lib/worker-run-directory.mjs +45 -0
  146. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +10 -2
  147. package/tools/ralph-external/lib/worker-verification-cli.mjs +164 -0
  148. package/tools/ralph-external/lib/worktree-preparation.mjs +417 -0
  149. package/tools/ralph-external/session-launcher.mjs +8 -15
  150. package/vscode-extension/schemas/aiwg.config.v1.json +27 -0
@@ -0,0 +1,46 @@
1
+ // Publish a validated zero-launch stop through the existing signed delivery route.
2
+ import { createHash } from 'node:crypto';
3
+ import { lstatSync, mkdtempSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { importImpl } from '../../_resolve-impl.mjs';
7
+ import { prepareDeliveryRecord } from './worker-delivery-record.mjs';
8
+
9
+ function destinationFor(deliverablePath, writableRoots) {
10
+ const destination = join(realpathSync(dirname(deliverablePath)), basename(deliverablePath));
11
+ for (const tree of writableRoots) {
12
+ const rel = relative(realpathSync(tree), destination);
13
+ if (rel === '' || rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel)) {
14
+ throw new Error('--deliverable must be outside worker-writable roots');
15
+ }
16
+ }
17
+ let existing;
18
+ try { existing = lstatSync(destination); } catch (error) { if (error.code !== 'ENOENT') throw error; }
19
+ if (existing && (!existing.isFile() || existing.nlink !== 1)) throw new Error('--deliverable must be a regular non-linked file or an absent path');
20
+ return destination;
21
+ }
22
+
23
+ export async function deliverTypedStop(input, { prepareRecord = prepareDeliveryRecord } = {}) {
24
+ const { projectDir = process.cwd(), ...request } = input;
25
+ const { typedStopDeliverySchema, invalidTypedStop } = await importImpl(import.meta.url, 'mcp/tools/worker-verify-deliver-schema.mjs');
26
+ const parsed = typedStopDeliverySchema.safeParse(request);
27
+ if (!parsed.success) throw invalidTypedStop(parsed.error.message);
28
+ const { deliverablePath, typedStop } = parsed.data;
29
+ const { loadWorkerInputs } = await importImpl(import.meta.url, 'cli/handlers/models.js');
30
+ const inputs = await loadWorkerInputs({ cwd: projectDir, args: [], rawArgs: [],
31
+ frameworkRoot: fileURLToPath(new URL('../../../', import.meta.url)) });
32
+ const writableRoots = Object.values(inputs.drivers).flatMap(driver => driver.qualification.installation?.workerWritableRoots ?? []);
33
+ const destination = destinationFor(deliverablePath, writableRoots);
34
+ const bytes = Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(typedStop).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))) + '\n');
35
+ const artifactDigest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
36
+ const complete = await prepareRecord(projectDir, { kind: 'typed-stop', verifierId: 'typed-stop@1', artifactDigest, deliverablePath: destination });
37
+ // Recheck after signing, before the same-directory atomic rename.
38
+ destinationFor(destination, writableRoots);
39
+ const staging = mkdtempSync(join(dirname(destination), '.aiwg-deliver-'));
40
+ try {
41
+ const staged = join(staging, 'typed-stop');
42
+ writeFileSync(staged, bytes, { flag: 'wx', mode: 0o600 });
43
+ renameSync(staged, destination);
44
+ } finally { rmSync(staging, { recursive: true, force: true }); }
45
+ return { status: 'accepted', kind: 'typed-stop', verifierId: 'typed-stop@1', artifactDigest, deliveryRecord: await complete() };
46
+ }
@@ -0,0 +1,509 @@
1
+ /**
2
+ * Confinement for Tier 0 trusted verification checks (#2889 B1,
3
+ * FR-OG-039/042/068). Extends the #2954/#2888 worker-isolation path
4
+ * (`worker-isolation.mjs`) with the extra `systemd-run --user` properties a
5
+ * *verification* check needs: checks execute worker-controlled code (the
6
+ * worker's own tests, `vitest`/`tsconfig` configs, Makefiles, cwd-relative
7
+ * runners) so they must never run with the conductor's full filesystem and
8
+ * network access or an exposed `HOME`.
9
+ *
10
+ * This host (and, empirically, any Ubuntu host with
11
+ * `kernel.apparmor_restrict_unprivileged_userns=1`, confirmed via
12
+ * `dmesg`/`audit` showing `apparmor="DENIED" ... capability=21 sys_admin
13
+ * profile=unprivileged_userns` on every `systemd-run --user` invocation)
14
+ * cannot create the nested user namespace `systemd-run --user` wants for
15
+ * namespace-creating confinement (`ProtectHome=`, `PrivateTmp=`,
16
+ * `PrivateNetwork=`, `InaccessiblePaths=`, `TemporaryFileSystem=`): all five
17
+ * silently no-op (`ProtectHome`/`PrivateTmp`/`InaccessiblePaths`) or log a
18
+ * single degrade line and continue unconfined (`PrivateNetwork`) rather than
19
+ * failing the unit. Only confinement implemented as a *remount* of an
20
+ * already-mounted filesystem — `ReadOnlyPaths=`/`ReadWritePaths=`,
21
+ * `NoNewPrivileges=`, and `PrivateUsers=`'s self-only uid map — is enforced
22
+ * here without that extra privilege. `probeVerificationIsolationCapabilities`
23
+ * never trusts that distinction from memory: it live-probes every property
24
+ * on first use so a different host or a kernel/policy change is reflected
25
+ * automatically instead of silently assumed.
26
+ *
27
+ * Round-2 fail-closed hardening (#2889 B1 CRITICAL): the probe is
28
+ * fail-closed end to end. A probe spawn error, non-zero exit, timeout, or
29
+ * ANY missing/ambiguous output field means the WHOLE probe is treated as
30
+ * failed — every capability is reported `degraded`, nothing is cached, and
31
+ * `runConfinedCheck` refuses to launch unless the caller explicitly opts
32
+ * into degraded isolation. Every capability this module claims `enforced`
33
+ * is positively demonstrated from OUTSIDE the probe unit, after it has
34
+ * exited, never from the unit's own self-reported exit code alone: a write
35
+ * sentinel outside the allowed paths must be observably ABSENT on the real
36
+ * host filesystem after the unit ends (not merely "the shell said the write
37
+ * failed"), and network isolation additionally requires the probe to have
38
+ * positively confirmed it ran to completion (the `DONE` marker below) before
39
+ * its reported network namespace id is trusted at all. The capability cache
40
+ * has a short TTL (re-measured well within a single conductor run, but
41
+ * never cached across a changing kernel/policy for the life of a long
42
+ * process) and is invalidated immediately on any probe failure, never
43
+ * reused stale. It is additionally keyed to the exact set of systemd
44
+ * properties this probe exercises (`PROBE_PROFILE_KEY`), so a future change
45
+ * to that set can never silently reuse an now-unrelated cached result.
46
+ *
47
+ * Given that split, this module's `runConfinedCheck` enforces EVERY
48
+ * required capability (write confinement, home-read protection, and network
49
+ * isolation — not write confinement alone) and reports every capability it
50
+ * could not additionally enforce — most importantly, that readable paths
51
+ * outside the worktree and home/tmp trees remain visible — as an
52
+ * explicit, structured `degraded` list on every result. A launch requests
53
+ * EXACTLY the systemd properties this host's live probe just proved
54
+ * (`buildVerificationExtraProperties`): `ProtectHome=`, `PrivateTmp=`, and
55
+ * `PrivateNetwork=` are each included only when their own probed capability
56
+ * came back `enforced`, never requested unconditionally and never silently
57
+ * omitted when they ARE available. Nothing is ever silently claimed
58
+ * "isolated" when it is not: callers decide whether a degraded run is
59
+ * acceptable (`allowDegradedIsolation: true`, a strict boolean — a string
60
+ * `"false"` or any other truthy-but-not-`true` value is treated as `false`
61
+ * and still refuses); the default is to refuse to run the check at all when
62
+ * the per-host probe shows a required capability is unavailable.
63
+ *
64
+ * One more host-specific gap the live probe measures separately
65
+ * (`tmpWriteConfinement`, never folded into `writeConfinement` and never
66
+ * part of the REQUIRED set `runConfinedCheck` refuses on): on this host,
67
+ * `systemd-run --user` leaves `/tmp` and `/var/tmp` writable EVERYWHERE,
68
+ * not just inside the worktree/output-directory allow-list, regardless of
69
+ * an explicit `ReadOnlyPaths=/tmp`/`ReadOnlyPaths=/var/tmp`.
70
+ * `systemd.exec(5)` ties that specific lock-down to `PrivateTmp=` actually
71
+ * engaging (which, per the same AppArmor restriction, it does not here);
72
+ * every other path on the same filesystem (confirmed with `/opt`, `/srv`,
73
+ * `/home`, `/var` directly) IS correctly confined. A worktree created
74
+ * under a real repository checkout (the normal case — see
75
+ * `worktree-preparation.mjs`) is unaffected; only a worktree or output
76
+ * directory placed under `/tmp`/`/var/tmp` inherits this specific gap, and
77
+ * it is reported, never assumed away.
78
+ */
79
+
80
+ import { spawnSync } from 'node:child_process';
81
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs';
82
+ import { homedir, tmpdir } from 'node:os';
83
+ import path from 'node:path';
84
+ import {
85
+ buildWorkerIsolationArgs,
86
+ detectWorkerIsolation,
87
+ resolveManagerEnvNames,
88
+ } from './worker-isolation.mjs';
89
+ import { buildSystemdClientEnv, resolveSystemdRun } from './systemd-client.mjs';
90
+
91
+ let cachedCapabilities;
92
+
93
+ /** Reset the process-lifetime capability cache. Test-only. */
94
+ export function resetVerificationIsolationCapabilityCache() {
95
+ cachedCapabilities = undefined;
96
+ }
97
+
98
+ // Short TTL: long enough that a normal conductor run (many checks across one
99
+ // or a few verification passes) does not re-probe every call, short enough
100
+ // that a long-running process never trusts a kernel/AppArmor-policy change
101
+ // (or a one-off probe flake) for more than a few minutes.
102
+ const CAPABILITY_CACHE_TTL_MS = 5 * 60 * 1000;
103
+
104
+ // The exact systemd properties this probe exercises, used only to key the
105
+ // cache (see module doc comment): if a future change to this list is made
106
+ // without also bumping this key, the stale cache is used instead of being
107
+ // silently (and wrongly) treated as still valid for a DIFFERENT probe.
108
+ const PROBE_PROFILE_KEY = [
109
+ 'NoNewPrivileges=yes', 'ProtectHome=tmpfs', 'PrivateTmp=yes',
110
+ 'PrivateUsers=yes', 'PrivateNetwork=yes', 'ReadOnlyPaths=/', 'ReadWritePaths=<scratch>',
111
+ ].join('|');
112
+
113
+ // Every capability a launch REQUIRES before it will proceed without an
114
+ // explicit `allowDegradedIsolation` opt-in (B1: "the refusal covers EVERY
115
+ // required capability ... not just write"). `tmpIsolation`/
116
+ // `tmpWriteConfinement`/`noNewPrivileges`/`arbitraryPathReadIsolation` are
117
+ // real, separately reported findings but are NOT required for launch —
118
+ // they are documented, known-degraded gaps on this host class (see module
119
+ // doc comment) that a caller may still accept as part of the overall
120
+ // degraded picture without blocking every launch outright.
121
+ export const REQUIRED_VERIFICATION_CAPABILITIES = ['writeConfinement', 'homeReadIsolation', 'networkIsolation'];
122
+
123
+ /** Which of `REQUIRED_VERIFICATION_CAPABILITIES` are NOT `'enforced'` on `capabilities`. */
124
+ export function missingRequiredCapabilities(capabilities) {
125
+ if (!capabilities || capabilities.mode !== 'systemd-unit') return [...REQUIRED_VERIFICATION_CAPABILITIES];
126
+ return REQUIRED_VERIFICATION_CAPABILITIES.filter(name => capabilities[name] !== 'enforced');
127
+ }
128
+
129
+ function runProbeUnit({ spawn, argv }) {
130
+ return spawn(resolveSystemdRun(), argv.slice(1), { encoding: 'utf8', timeout: 20000, env: buildSystemdClientEnv({ envNames: [] }) });
131
+ }
132
+
133
+ function fullyDegradedResult(reason) {
134
+ return {
135
+ mode: 'systemd-unit',
136
+ reason,
137
+ writeConfinement: 'degraded',
138
+ tmpWriteConfinement: 'degraded',
139
+ noNewPrivileges: 'degraded',
140
+ homeReadIsolation: 'degraded',
141
+ tmpIsolation: 'degraded',
142
+ networkIsolation: 'degraded',
143
+ arbitraryPathReadIsolation: 'degraded',
144
+ degraded: [{ capability: 'probe', reason }],
145
+ };
146
+ }
147
+
148
+ const PROBE_REQUIRED_FIELDS = [
149
+ 'NONEWPRIVS', 'NETNS', 'HOMECOUNT', 'TMPMARK',
150
+ 'SCRATCHWRITE', 'TMPWRITE', 'VARTMPWRITE', 'HOMEWRITE', 'DONE',
151
+ ];
152
+
153
+ /**
154
+ * Live-probe which confinement properties this host's `systemd-run --user`
155
+ * actually enforces, rather than assuming from a fixed list. Runs ONE
156
+ * combined throwaway unit (bounded, single call — `tool-quota`) that
157
+ * exercises each property against disposable fixtures it creates and tears
158
+ * down itself; nothing it touches is a real secret or a real worktree.
159
+ *
160
+ * Fail-closed (B1): a probe spawn error, non-zero exit, or any missing
161
+ * expected output field means the probe is treated as having failed
162
+ * entirely — every capability comes back `degraded` with a `probe`-level
163
+ * reason, and the result is NOT cached (so the very next call re-probes
164
+ * rather than wedging on a transient failure). A successful probe is
165
+ * cached for `CAPABILITY_CACHE_TTL_MS` and keyed to `PROBE_PROFILE_KEY`;
166
+ * pass `force: true` to bypass the cache outright (tests only).
167
+ */
168
+ export function probeVerificationIsolationCapabilities({ spawn = spawnSync, force = false } = {}) {
169
+ if (cachedCapabilities && !force) {
170
+ const fresh = Date.now() - cachedCapabilities._probedAt < CAPABILITY_CACHE_TTL_MS;
171
+ const sameProfile = cachedCapabilities._profileKey === PROBE_PROFILE_KEY;
172
+ if (fresh && sameProfile) return cachedCapabilities;
173
+ cachedCapabilities = undefined;
174
+ }
175
+
176
+ const detected = detectWorkerIsolation({ spawn });
177
+ if (detected.mode !== 'systemd-unit') {
178
+ const result = {
179
+ mode: 'degraded',
180
+ reason: detected.reason,
181
+ writeConfinement: 'degraded',
182
+ tmpWriteConfinement: 'degraded',
183
+ noNewPrivileges: 'degraded',
184
+ homeReadIsolation: 'degraded',
185
+ tmpIsolation: 'degraded',
186
+ networkIsolation: 'degraded',
187
+ arbitraryPathReadIsolation: 'degraded',
188
+ degraded: [{ capability: 'systemd-unit', reason: detected.reason }],
189
+ };
190
+ // This is a durable, legitimate finding (no systemd user manager at
191
+ // all), not a probe failure -- caching it avoids re-shelling out to
192
+ // `systemd-run --version`/`systemctl --user show` on every call.
193
+ cachedCapabilities = { ...result, _probedAt: Date.now(), _profileKey: PROBE_PROFILE_KEY };
194
+ return cachedCapabilities;
195
+ }
196
+
197
+ // B1: a failed/ambiguous host-netns lookup must never be read as "the
198
+ // probe's reported namespace differs, so isolation is enforced" -- fail
199
+ // the WHOLE probe closed rather than comparing against an empty/unknown
200
+ // baseline.
201
+ let hostNetNs;
202
+ try {
203
+ hostNetNs = spawn('readlink', ['/proc/self/ns/net'], { encoding: 'utf8', timeout: 5000 });
204
+ } catch (error) {
205
+ return fullyDegradedResult(`could not determine this host's own network namespace: ${error.message}`);
206
+ }
207
+ if (hostNetNs.error || hostNetNs.status !== 0) {
208
+ return fullyDegradedResult(`could not determine this host's own network namespace: ${hostNetNs.error?.message ?? `readlink exited ${hostNetNs.status}`}`);
209
+ }
210
+ const hostNetNsId = String(hostNetNs.stdout ?? '').trim();
211
+ if (!hostNetNsId) {
212
+ return fullyDegradedResult('host network namespace lookup returned no output');
213
+ }
214
+
215
+ // A disposable scratch directory stands in for a real worktree/output
216
+ // directory, exercising the exact same `ReadOnlyPaths=/`+`ReadWritePaths=`
217
+ // pair `buildVerificationExtraProperties` builds for a real check — so
218
+ // this probe measures the real mechanism, not a simplified stand-in.
219
+ //
220
+ // Uniqueness note: `process.pid` is identical across Vitest worker
221
+ // THREADS (they share one OS process), so two test files running
222
+ // concurrent live probes with `${process.pid}`-only escape-sentinel
223
+ // names raced each other's writes/cleanup of the SAME host path — one
224
+ // probe's cleanup could delete another concurrent probe's still-pending
225
+ // sentinel, producing a flaky "enforced" reading for `writeConfinement`/
226
+ // `tmpWriteConfinement` that depends on nothing but scheduling luck.
227
+ // `mkdtempSync` already gives the scratch directory a unique name; the
228
+ // escape-sentinel filenames and the systemd unit name get an explicit
229
+ // random suffix for the same reason a `systemd-run --unit=` name must
230
+ // also never collide across concurrent probes.
231
+ const probeNonce = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
232
+ const scratchDir = mkdtempSync(path.join(tmpdir(), 'aiwg-verify-probe-scratch-'));
233
+ const escapeOutsideScratchButInTmp = path.join(tmpdir(), `aiwg-verify-probe-tmp-escape-${probeNonce}`);
234
+ const escapeInVarTmp = path.join('/var/tmp', `aiwg-verify-probe-vartmp-escape-${probeNonce}`);
235
+ const escapeInHome = path.join(homedir(), `.aiwg-verify-probe-home-escape-${probeNonce}`);
236
+ rmSync(escapeOutsideScratchButInTmp, { force: true });
237
+ rmSync(escapeInVarTmp, { force: true });
238
+ rmSync(escapeInHome, { force: true });
239
+
240
+ const cleanupScratchFixtures = () => {
241
+ try { rmSync(scratchDir, { recursive: true, force: true }); } catch { /* best effort */ }
242
+ try { rmSync(escapeOutsideScratchButInTmp, { force: true }); } catch { /* best effort */ }
243
+ try { rmSync(escapeInVarTmp, { force: true }); } catch { /* best effort */ }
244
+ try { rmSync(escapeInHome, { force: true }); } catch { /* best effort */ }
245
+ };
246
+
247
+ const unit = `aiwg-verify-isolation-probe-${probeNonce}`;
248
+ // B1: the probe no longer deletes its own /tmp marker from INSIDE the
249
+ // unit (`rm -f "$MARK"` used to run before the conductor ever looked at
250
+ // it, which meant the marker was always gone by the time the degraded
251
+ // check below ran — a host where PrivateTmp is degraded and the write
252
+ // landed on the REAL /tmp would still read back "enforced" because the
253
+ // unit had already erased the only evidence of its own failure). Cleanup
254
+ // of any marker that DID leak onto the real host /tmp now happens only
255
+ // from OUTSIDE, after the unit has exited, by this function itself.
256
+ const argv = ['systemd-run', '--user', '--pipe', '--wait', '--quiet', `--unit=${unit}`,
257
+ '-p', 'NoNewPrivileges=yes', '-p', 'ProtectHome=tmpfs', '-p', 'PrivateTmp=yes',
258
+ '-p', 'PrivateUsers=yes', '-p', 'PrivateNetwork=yes',
259
+ // BindPaths= keeps the granted directory visible through ProtectHome=tmpfs/PrivateTmp=yes;
260
+ // without it an enforcing host fails the unit with 226/NAMESPACE (noodle, #4128).
261
+ '-p', 'ReadOnlyPaths=/', '-p', `BindPaths=${scratchDir}`, '-p', `ReadWritePaths=${scratchDir}`,
262
+ '--', '/bin/sh', '-c',
263
+ 'echo NONEWPRIVS:$(grep -c "NoNewPrivs:\\s1" /proc/self/status);' +
264
+ 'echo NETNS:$(readlink /proc/self/ns/net);' +
265
+ 'echo HOMECOUNT:$(ls -A "$HOME" 2>/dev/null | wc -l);' +
266
+ 'MARK=/tmp/aiwg-verify-probe-$$; echo x > "$MARK" 2>/dev/null; echo TMPMARK:$MARK;' +
267
+ `(echo x > '${scratchDir}/ok') 2>/dev/null; echo SCRATCHWRITE:$?;` +
268
+ `(echo x > '${escapeOutsideScratchButInTmp}') 2>/dev/null; echo TMPWRITE:$?;` +
269
+ `(echo x > '${escapeInVarTmp}') 2>/dev/null; echo VARTMPWRITE:$?;` +
270
+ `(echo x > '${escapeInHome}') 2>/dev/null; echo HOMEWRITE:$?;` +
271
+ 'echo DONE:1'];
272
+
273
+ let result;
274
+ try {
275
+ result = runProbeUnit({ spawn, argv });
276
+ } catch (error) {
277
+ cleanupScratchFixtures();
278
+ return fullyDegradedResult(`probe unit could not be spawned: ${error.message}`);
279
+ }
280
+ // B1: a spawn-level error, timeout (ETIMEDOUT leaves `status: null`), or
281
+ // non-zero exit means we got nothing trustworthy -- never parse partial
282
+ // stdout from a probe that did not cleanly finish.
283
+ if (result.error || result.status !== 0) {
284
+ cleanupScratchFixtures();
285
+ const reason = result.error
286
+ ? `probe unit failed to run: ${result.error.code ?? result.error.message}`
287
+ : `probe unit exited ${result.status}`;
288
+ return fullyDegradedResult(reason);
289
+ }
290
+
291
+ const stdout = String(result.stdout ?? '');
292
+ const fields = {};
293
+ for (const line of stdout.split('\n')) {
294
+ const index = line.indexOf(':');
295
+ if (index === -1) continue;
296
+ fields[line.slice(0, index)] = line.slice(index + 1);
297
+ }
298
+
299
+ // B1: a timed-out or otherwise truncated probe can still exit 0 with
300
+ // partial output (e.g. the pipe closed mid-write); require every expected
301
+ // field to be present before trusting ANY of them, rather than letting
302
+ // missing fields silently default into "enforced" one at a time.
303
+ const missingFields = PROBE_REQUIRED_FIELDS.filter(name => fields[name] === undefined);
304
+ if (missingFields.length > 0) {
305
+ cleanupScratchFixtures();
306
+ return fullyDegradedResult(`probe output incomplete (missing: ${missingFields.join(', ')}); refusing to trust a partial probe`);
307
+ }
308
+
309
+ const degraded = [];
310
+ const noNewPrivileges = fields.NONEWPRIVS === '1' ? 'enforced' : 'degraded';
311
+ if (noNewPrivileges === 'degraded') degraded.push({ capability: 'noNewPrivileges', reason: 'NoNewPrivs was not set to 1 inside the probe unit' });
312
+
313
+ // B1: network isolation is positively shown by (a) the probe having
314
+ // positively confirmed it ran to completion (the DONE marker, checked
315
+ // above as part of "every field present") and (b) the probe's own
316
+ // reported namespace id actually differing from the HOST's own id, which
317
+ // was independently resolved (and error-checked) above.
318
+ const networkIsolation = fields.NETNS !== hostNetNsId ? 'enforced' : 'degraded';
319
+ if (networkIsolation === 'degraded') degraded.push({ capability: 'networkIsolation', reason: `PrivateNetwork=yes did not change the net namespace (host: ${hostNetNsId}, probe: ${fields.NETNS}); this host's AppArmor policy denies the CAP_SYS_ADMIN unprivileged-userns needs to create one` });
320
+
321
+ // A real $HOME is never empty on a developer/CI host; ProtectHome=tmpfs
322
+ // enforced would make it 0 (a fresh empty tmpfs). Any positive count means
323
+ // the real HOME directory is still visible.
324
+ const homeCount = Number(fields.HOMECOUNT);
325
+ const homeReadIsolation = Number.isFinite(homeCount) && homeCount === 0 ? 'enforced' : 'degraded';
326
+ if (homeReadIsolation === 'degraded') degraded.push({ capability: 'homeReadIsolation', reason: `ProtectHome=tmpfs did not hide $HOME (still ${fields.HOMECOUNT ?? 'unknown'} entries visible); same AppArmor unprivileged-userns restriction` });
327
+
328
+ // B1: PrivateTmp enforced is now positively demonstrated from OUTSIDE,
329
+ // after the unit has exited: the marker the probe wrote under its own
330
+ // /tmp must be ABSENT from the real host /tmp. The unit no longer deletes
331
+ // it itself (see argv comment above), so this is the first and only
332
+ // place it is removed.
333
+ const tmpMarkerPath = fields.TMPMARK;
334
+ const tmpMarkerLeaked = existsSync(tmpMarkerPath);
335
+ const tmpIsolation = tmpMarkerLeaked ? 'degraded' : 'enforced';
336
+ if (tmpMarkerLeaked) {
337
+ degraded.push({ capability: 'tmpIsolation', reason: 'PrivateTmp=yes did not isolate /tmp: the probe\'s own tmp marker was visible on the real host /tmp after the unit exited' });
338
+ try { rmSync(tmpMarkerPath, { force: true }); } catch { /* best effort cleanup of the leaked marker */ }
339
+ }
340
+
341
+ // ProtectHome/PrivateTmp hide their trees; ReadOnlyPaths=/ leaves other reads visible.
342
+ const arbitraryPathReadIsolation = 'degraded';
343
+ degraded.push({ capability: 'arbitraryPathReadIsolation', reason: 'the verification profile does not confine reads to the worktree and output directory: ProtectHome/PrivateTmp hide only home and temporary paths, and ReadOnlyPaths=/ prevents writes but leaves other readable host paths accessible' });
344
+
345
+ // B1: writeConfinement is positively demonstrated from OUTSIDE, after
346
+ // the unit exits, on BOTH sides: the allow-listed scratch write must be
347
+ // observably present (the mechanism actually works, not merely "the
348
+ // shell said exit 0"), and the disallowed $HOME write must be observably
349
+ // ABSENT (not merely "the shell said it failed"). A missing/ambiguous
350
+ // self-reported exit code (`fields.SCRATCHWRITE`/`HOMEWRITE`) is already
351
+ // ruled out above (every field is required to be present), so these are
352
+ // now a secondary corroborating signal, never the sole evidence.
353
+ const scratchWriteLanded = existsSync(path.join(scratchDir, 'ok'));
354
+ const homeWriteLeaked = existsSync(escapeInHome);
355
+ const writeConfinement = (scratchWriteLanded && !homeWriteLeaked) ? 'enforced' : 'degraded';
356
+ if (!scratchWriteLanded) degraded.push({ capability: 'writeConfinement', reason: 'the ReadWritePaths= allow-list itself did not work: the write inside the granted scratch directory was not observed to land (checked from outside the unit)' });
357
+ if (homeWriteLeaked) degraded.push({ capability: 'writeConfinement', reason: 'ReadOnlyPaths=/ did not block a write to an ordinary path outside the allow-list ($HOME): the sentinel was observed to exist after the unit exited' });
358
+
359
+ const tmpWriteLeaked = existsSync(escapeOutsideScratchButInTmp);
360
+ const varTmpWriteLeaked = existsSync(escapeInVarTmp);
361
+ const tmpWriteConfinement = (!tmpWriteLeaked && !varTmpWriteLeaked) ? 'enforced' : 'degraded';
362
+ if (tmpWriteLeaked) degraded.push({ capability: 'tmpWriteConfinement', reason: '/tmp is writable outside the designated worktree/output-directory allow-list regardless of ReadOnlyPaths=/ (systemd exempts /tmp from path-based confinement unless PrivateTmp= is actually functioning, which it is not on this host)' });
363
+ if (varTmpWriteLeaked) degraded.push({ capability: 'tmpWriteConfinement', reason: '/var/tmp is writable outside the designated worktree/output-directory allow-list, for the same reason as /tmp' });
364
+
365
+ cleanupScratchFixtures();
366
+
367
+ cachedCapabilities = {
368
+ mode: 'systemd-unit',
369
+ reason: detected.reason,
370
+ writeConfinement,
371
+ tmpWriteConfinement,
372
+ noNewPrivileges,
373
+ homeReadIsolation,
374
+ tmpIsolation,
375
+ networkIsolation,
376
+ arbitraryPathReadIsolation,
377
+ degraded,
378
+ _probedAt: Date.now(),
379
+ _profileKey: PROBE_PROFILE_KEY,
380
+ };
381
+ return cachedCapabilities;
382
+ }
383
+
384
+ /**
385
+ * Build the extra confinement properties `runConfinedCheck` always requests.
386
+ * B1: a launch requests EXACTLY the property set the live probe just
387
+ * proved — never a fixed list assumed from memory. `NoNewPrivileges=`/
388
+ * `PrivateUsers=` are requested unconditionally because they are pure
389
+ * remounts/uid-map restrictions that can only narrow privilege (never grant
390
+ * it) and are the two properties this host's AppArmor policy does NOT deny
391
+ * (see module doc comment); `ReadOnlyPaths=`/`ReadWritePaths=`,
392
+ * `ProtectHome=tmpfs`, `PrivateTmp=yes`, and `PrivateNetwork=yes` are each
393
+ * included only when `capabilities` shows the matching capability
394
+ * `'enforced'` on THIS host, so a degraded property is never requested as
395
+ * if it worked.
396
+ */
397
+ export function buildVerificationExtraProperties({ worktreeRootReal, outputDirReal, readWritePaths = [], capabilities } = {}) {
398
+ if (typeof worktreeRootReal !== 'string' || worktreeRootReal.length === 0) {
399
+ throw new Error('buildVerificationExtraProperties requires worktreeRootReal');
400
+ }
401
+ if (!capabilities || typeof capabilities !== 'object') {
402
+ throw new Error('buildVerificationExtraProperties requires the live-probed capabilities, so a launch only requests what this host actually proved');
403
+ }
404
+ const properties = ['NoNewPrivileges=yes', 'PrivateUsers=yes'];
405
+ if (capabilities.writeConfinement === 'enforced') {
406
+ // Bind each granted path into the unit's namespace so it survives ProtectHome=tmpfs and
407
+ // PrivateTmp=yes (worktrees usually live under /home); ReadWritePaths= alone fails there (#4128).
408
+ properties.push('ReadOnlyPaths=/');
409
+ for (const granted of [worktreeRootReal, outputDirReal, ...readWritePaths].filter(Boolean)) {
410
+ properties.push(`BindPaths=${granted}`, `ReadWritePaths=${granted}`);
411
+ }
412
+ }
413
+ if (capabilities.homeReadIsolation === 'enforced') properties.push('ProtectHome=tmpfs');
414
+ if (capabilities.tmpIsolation === 'enforced') properties.push('PrivateTmp=yes');
415
+ if (capabilities.networkIsolation === 'enforced') properties.push('PrivateNetwork=yes');
416
+ return properties;
417
+ }
418
+
419
+ /**
420
+ * Run one check confined through `systemd-run --user` with the properties
421
+ * this host actually enforces, `--pipe --wait` so stdout/stderr/exit code
422
+ * return synchronously exactly like a plain `spawnSync` result.
423
+ *
424
+ * Returns `{ status, stdout, stderr, error, isolation }`. `isolation`
425
+ * carries the mode and the full degraded-capability list from
426
+ * `probeVerificationIsolationCapabilities` on every call — including
427
+ * accepted/passed ones — so a caller can never mistake "the check passed"
428
+ * for "the check was fully isolated."
429
+ *
430
+ * B1: the refusal-by-default gate now covers EVERY capability in
431
+ * `REQUIRED_VERIFICATION_CAPABILITIES` (write confinement, home-read
432
+ * protection, network isolation) — not write confinement alone. When this
433
+ * host cannot even reach a systemd user manager, OR any required
434
+ * capability is not `'enforced'`, the check is refused (`{ status: null,
435
+ * error: {code: 'ISOLATION_UNAVAILABLE'}, isolation }`) unless
436
+ * `allowDegradedIsolation` is the strict boolean `true` — a string
437
+ * `"false"`, `1`, or any other truthy-but-not-literally-`true` value is
438
+ * treated as `false` and still refuses, closing the JS-truthiness gap where
439
+ * `!allowDegradedIsolation` would have let a stray `"false"` string through
440
+ * as if it were an explicit opt-in. Refusing by default here — rather than
441
+ * launching through `systemd-run` anyway and trusting its properties
442
+ * silently no-op into a pass-through — is deliberate: a caller must
443
+ * explicitly accept running genuinely unconfined, never discover it only
444
+ * after reading `isolation.degraded`.
445
+ */
446
+ export function runConfinedCheck({
447
+ command,
448
+ args = [],
449
+ cwd,
450
+ worktreeRootReal,
451
+ outputDirReal,
452
+ envNames = ['PATH', 'HOME'],
453
+ env = process.env,
454
+ timeoutMs = 60000,
455
+ spawn = spawnSync,
456
+ allowDegradedIsolation = false,
457
+ } = {}) {
458
+ const capabilities = probeVerificationIsolationCapabilities({ spawn });
459
+ const isolation = { mode: capabilities.mode, degraded: capabilities.degraded };
460
+ const missingRequired = missingRequiredCapabilities(capabilities);
461
+ const confinementUnavailable = capabilities.mode !== 'systemd-unit' || missingRequired.length > 0;
462
+ const degradedOptIn = allowDegradedIsolation === true;
463
+
464
+ if (confinementUnavailable) {
465
+ if (!degradedOptIn) {
466
+ const reason = capabilities.mode !== 'systemd-unit'
467
+ ? capabilities.reason
468
+ : `required confinement capabilities are not enforced on this host for systemd --user units: ${missingRequired.join(', ')}`;
469
+ return { status: null, stdout: '', stderr: '', error: { code: 'ISOLATION_UNAVAILABLE', message: reason }, isolation };
470
+ }
471
+ // HIGH m2 regression (round 2): a degraded launch has no systemd unit
472
+ // to isolate the environment, so it MUST build its own allowlisted
473
+ // environment and pass it as the child's *entire* environment (the
474
+ // `env` option REPLACES, never merges with, the current process
475
+ // environment — the functional equivalent of `env -i NAME=value ...`,
476
+ // matching `worker-isolation.mjs`'s `launchIsolatedWorker` degraded
477
+ // path). The previous version forwarded `env` (defaulting to
478
+ // `process.env`, the conductor's FULL environment, secrets included)
479
+ // straight into worker-controlled check code — confirmed by an
480
+ // unlisted synthetic secret surviving into the degraded child's
481
+ // environment. Only names present in `envNames` ever cross this
482
+ // boundary now, exactly like the confined (`systemd-unit`) path's own
483
+ // `--setenv=` allowlist.
484
+ const allowedEnv = {};
485
+ for (const name of envNames) {
486
+ const value = env?.[name];
487
+ if (value !== undefined) allowedEnv[name] = value;
488
+ }
489
+ const result = spawn(command, args, { cwd, env: allowedEnv, encoding: 'utf8', timeout: timeoutMs });
490
+ return { ...result, isolation };
491
+ }
492
+
493
+ let managerEnvNames, systemdRun;
494
+ try {
495
+ managerEnvNames = resolveManagerEnvNames({ spawn });
496
+ systemdRun = resolveSystemdRun();
497
+ } catch (error) {
498
+ return { status: null, stdout: '', stderr: '', error: { code: 'ISOLATION_UNAVAILABLE', message: `unable to resolve the user manager's environment or trusted systemd-run client: ${error.message}` }, isolation };
499
+ }
500
+
501
+ const unit = `aiwg-verify-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
502
+ const extraProperties = buildVerificationExtraProperties({ worktreeRootReal, outputDirReal, capabilities });
503
+ const argv = buildWorkerIsolationArgs({
504
+ unit, memoryMax: '2G', command, args, cwd, env, envNames, managerEnvNames,
505
+ kind: 'unit', extraProperties, pipe: true, wait: true,
506
+ });
507
+ const result = spawn(systemdRun, argv.slice(1), { encoding: 'utf8', timeout: timeoutMs, env: buildSystemdClientEnv({ env, envNames }) });
508
+ return { ...result, isolation };
509
+ }
@@ -68,7 +68,7 @@ export async function resolveWorkerContextProviders({ repoRoot, providers = null
68
68
  * Ensure a worker workdir carries its CLI's AIWG bootstrap before launch.
69
69
  * Resolves the worker CLI to its provider (from the project config, so
70
70
  * orchestration CLIs map through the registry), checks presence, and
71
- * deploys through the same one-pass helper when missing. The deploy
71
+ * deploys only that provider with project scope when missing. The deploy
72
72
  * target is always exactly `workdir` — never anywhere else.
73
73
  *
74
74
  * Injectable for synthetic tests: `ensureFn` stubs the whole ensure,
@@ -116,13 +116,13 @@ export async function ensureWorkerContextForLaunch({
116
116
  );
117
117
  }
118
118
  const provider = mapped.provider;
119
- const deployProviders = resolved ? [...new Set([...resolved.providers, provider])] : [provider];
119
+ const deployProviders = [provider];
120
120
  const ensure = ensureFn ?? (async (opts) => {
121
121
  const { ensureWorkerContextBootstrap } = await importImpl(import.meta.url, 'config/worker-context.js');
122
122
  return ensureWorkerContextBootstrap(opts);
123
123
  });
124
124
  const outcome = await ensure({
125
- workdir, provider, providers: deployProviders, aiwgBin,
125
+ workdir, provider, providers: deployProviders, projectLocal: true, aiwgBin,
126
126
  ...(statusFn ? { statusFn } : {}),
127
127
  ...(deployFn ? { deployFn } : {}),
128
128
  ...(skipWorktreeFn ? { skipWorktreeFn } : {}),