@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,417 @@
1
+ /**
2
+ * Tier 0 writer worktree preparation and ownership (FR-OG-039, FR-OG-068,
3
+ * #2889 / B-OG-13). Extends Rule 9 step 4 ("Prepare the worktree") with the
4
+ * exact-base-digest binding and overlapping-claim refusal that step only
5
+ * described narratively.
6
+ *
7
+ * The conductor — never the worker — owns worktree creation and the claim
8
+ * registry below. A worktree is created at an exact recorded base digest
9
+ * (`git rev-parse <revision>`, not a moving ref) so later acceptance can
10
+ * bind to a specific tree; two writer claims on the same file or port
11
+ * refuse to both proceed rather than silently interleave writes.
12
+ *
13
+ * This module adds no daemon, store, or scheduler: `WorktreeClaimRegistry`
14
+ * is a plain in-memory ownership table the conductor process holds for the
15
+ * duration of its own run, matching the Tier 0 "no admission store" scope.
16
+ * Managed, cross-conductor disk reservations and leases remain Tier 1
17
+ * (deferred to S2+; see `agentic/code/addons/aiwg-utils/rules/subagent-scoping.md`
18
+ * Rule 9 and `08-security-and-threat-model.md`'s Tier 1 brief/retention
19
+ * section).
20
+ *
21
+ * #3685: a fresh worktree holds only tracked files, so deployed provider
22
+ * context (gitignored `.codex/`, `.claude/`, `.muse/`, `.agents/` and the
23
+ * AIWG rule sections in `AGENTS.md`) is missing until the conductor puts
24
+ * it there. Preparation therefore deploys that context by default
25
+ * (`deployContext`, one `aiwg use all` pass for every configured provider
26
+ * — never one deploy per provider, which clobbers other providers'
27
+ * `AGENTS.md` sections), hides the deploy's tracked-bridge edits from the
28
+ * worker diff with `git update-index --skip-worktree`, and verifies the
29
+ * rule sections before reporting ready.
30
+ *
31
+ * #3685 round 2: the provider set is the union of the config `providers`
32
+ * and every orchestration CLI, loaded through `readAiwgConfig` (see
33
+ * `worker-context.mjs`, which also owns the single-pass deploy, the
34
+ * section verifier, and the skip-worktree helpers extracted from here).
35
+ * This module stays synchronous: callers preload the set with
36
+ * `resolveWorkerContextProviders()` and pass it as `contextProviders`.
37
+ */
38
+
39
+ import { spawnSync } from 'node:child_process';
40
+ import { existsSync, lstatSync, mkdirSync, realpathSync, statSync } from 'node:fs';
41
+ import path from 'node:path';
42
+ import { excludeWorkerLocalOnlyPaths } from './worker-local-only-paths.mjs';
43
+ import {
44
+ defaultDeployWorkerContext,
45
+ listDeployDirtiedBridges,
46
+ resolveWorkerContextProviders,
47
+ verifyWorkerContextSections,
48
+ } from './worker-context.mjs';
49
+
50
+ export {
51
+ defaultDeployWorkerContext,
52
+ listDeployDirtiedBridges,
53
+ resolveWorkerContextProviders,
54
+ verifyWorkerContextSections,
55
+ };
56
+
57
+ /** Thrown when a requested claim set collides with an already-held claim. */
58
+ export class WorktreeClaimConflictError extends Error {
59
+ constructor(conflicts) {
60
+ super(`worktree claim conflict: ${conflicts.map(c => `${c.claim} held by ${c.heldBy}`).join(', ')}`);
61
+ this.name = 'WorktreeClaimConflictError';
62
+ this.conflicts = conflicts;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * M4: key a file claim by its realpath (and, for a file that already
68
+ * exists, its `dev:inode` as a secondary disambiguator) rather than by
69
+ * `path.resolve` alone. Two spellings of the same inode — a literal path
70
+ * and a `/proc/self/cwd`-relative or symlinked-ancestor spelling — must
71
+ * collide to the same claim key so two owners can never both be granted a
72
+ * claim that is actually the same file; `path.resolve` alone cannot
73
+ * guarantee that, since it only normalizes `.`/`..`/separators, never
74
+ * symlinks. A not-yet-existing file (the common case — a worker hasn't
75
+ * written it yet) keys on the realpath of its resolved *directory* plus
76
+ * its own basename, since the file itself has no inode yet to read.
77
+ */
78
+ function claimKeyForFile(file) {
79
+ // Returns the display key used in conflict reports plus every identity key
80
+ // the registry indexes. An existing file is indexed by dev:inode (so
81
+ // hardlink aliases collide) AND by its canonical path (so a claim made
82
+ // before the file existed still collides once it appears). A file that does
83
+ // not exist yet is indexed by its canonical directory plus basename.
84
+ const resolved = path.resolve(file);
85
+ const dir = path.dirname(resolved);
86
+ const base = path.basename(resolved);
87
+ let dirReal;
88
+ try {
89
+ dirReal = realpathSync(dir);
90
+ } catch {
91
+ // Parent directory does not exist yet either: key the resolved spelling.
92
+ dirReal = dir;
93
+ }
94
+ const candidate = path.join(dirReal, base);
95
+ try {
96
+ const real = realpathSync(candidate);
97
+ const stat = statSync(real);
98
+ return { display: `file:${real}#${stat.dev}:${stat.ino}`, keys: [`inode:${stat.dev}:${stat.ino}`, `path:${real}`] };
99
+ } catch {
100
+ return { display: `file:${candidate}`, keys: [`path:${candidate}`] };
101
+ }
102
+ }
103
+
104
+ function normalizeClaims({ files = [], ports = [] } = {}) {
105
+ // File claims must already be absolute: resolving a relative claim
106
+ // against the conductor process's own CWD (rather than the repo/worktree
107
+ // the claim is actually about) would silently key two different intended
108
+ // files identically or two identical intended files differently,
109
+ // depending on wherever the process happened to be started from.
110
+ for (const file of files) {
111
+ if (typeof file !== 'string' || !path.isAbsolute(file)) {
112
+ throw new Error(`worktree claim requires absolute file paths, got ${JSON.stringify(file)}`);
113
+ }
114
+ }
115
+ const fileEntries = files.map(claimKeyForFile);
116
+ const portEntries = ports.map(port => {
117
+ const key = `port:${Number(port)}`;
118
+ if (!Number.isInteger(Number(port)) || Number(port) <= 0) {
119
+ throw new Error(`worktree claim requires positive integer ports, got ${key}`);
120
+ }
121
+ return { display: key, keys: [key] };
122
+ });
123
+ return [...fileEntries, ...portEntries];
124
+ }
125
+
126
+ /**
127
+ * Tracks which conductor-local owner currently holds which file/port
128
+ * claims. One shared registry instance per conductor process/run — not a
129
+ * cross-process store. `claim` is all-or-nothing: either every requested
130
+ * claim is free and all are granted atomically, or none are granted and the
131
+ * caller gets back the exact conflicts so it can serialize (wait and
132
+ * retry) or fail the attempt. This is the mechanism Rule 9 step 6 assumes
133
+ * when it says overlapping writer claims "serialize or fail."
134
+ */
135
+ export class WorktreeClaimRegistry {
136
+ constructor() {
137
+ /** @type {Map<string, string>} claimKey -> ownerId */
138
+ this._held = new Map();
139
+ /** @type {Map<string, string[]>} ownerId -> claimKeys */
140
+ this._byOwner = new Map();
141
+ }
142
+
143
+ /**
144
+ * @param {string} ownerId
145
+ * @param {{files?: string[], ports?: number[]}} claims
146
+ * @returns {{granted: boolean, conflicts: Array<{claim: string, heldBy: string}>}}
147
+ */
148
+ claim(ownerId, claims) {
149
+ if (typeof ownerId !== 'string' || ownerId.length === 0) {
150
+ throw new Error('worktree claim requires a non-empty ownerId');
151
+ }
152
+ const entries = normalizeClaims(claims);
153
+ const conflicts = [];
154
+ for (const entry of entries) {
155
+ const heldBy = entry.keys.map(key => this._held.get(key)).find(owner => owner !== undefined && owner !== ownerId);
156
+ if (heldBy !== undefined) conflicts.push({ claim: entry.display, heldBy });
157
+ }
158
+ if (conflicts.length > 0) {
159
+ return { granted: false, conflicts };
160
+ }
161
+ const keys = entries.flatMap(entry => entry.keys);
162
+ for (const key of keys) this._held.set(key, ownerId);
163
+ const existing = this._byOwner.get(ownerId) ?? [];
164
+ this._byOwner.set(ownerId, [...new Set([...existing, ...keys])]);
165
+ return { granted: true, conflicts: [] };
166
+ }
167
+
168
+ /** Release every claim held by `ownerId`. Idempotent. */
169
+ release(ownerId) {
170
+ const keys = this._byOwner.get(ownerId) ?? [];
171
+ for (const key of keys) {
172
+ if (this._held.get(key) === ownerId) this._held.delete(key);
173
+ }
174
+ this._byOwner.delete(ownerId);
175
+ }
176
+
177
+ /** Snapshot of current claims for diagnostics/tests. */
178
+ list() {
179
+ return [...this._held.entries()].map(([claim, heldBy]) => ({ claim, heldBy }));
180
+ }
181
+ }
182
+
183
+ /**
184
+ * M5 (round 2): create a directory tree with NO exposure window, instead of
185
+ * `mkdirSync({ recursive: true })` (default mode, i.e. `0o777 & ~umask`)
186
+ * followed by a separate `chmodSync` — between those two calls the
187
+ * directory briefly exists at whatever the ambient umask left it at
188
+ * (`0775`/`0777` on a `0002`/`0000` umask host), which is a real exposure
189
+ * window for anything racing to open/traverse it before the chmod lands.
190
+ *
191
+ * Instead, each path component this call actually creates passes
192
+ * `mode: 0o700` directly to the SAME `mkdirSync` syscall that creates it:
193
+ * `mkdir(2)` is atomic, so the directory never exists at any wider mode
194
+ * even momentarily — there is no second step for a race to land in. This
195
+ * deliberately does NOT touch `process.umask()` to "neutralize" the
196
+ * ambient umask (that setter throws `TypeError: Setting process.umask() is
197
+ * not supported in workers` inside a worker-thread test runner such as
198
+ * Vitest's default pool, and is unnecessary besides: `mode & ~umask` can
199
+ * only ever CLEAR bits from the requested `0o700`, never add any, so an
200
+ * ordinary umask — which conventionally narrows group/other bits that
201
+ * `0o700` does not request in the first place — leaves the result
202
+ * unchanged). Every created component is still verified with `lstatSync`
203
+ * immediately afterward and this throws (never silently `chmod`s) if the
204
+ * resulting mode is not EXACTLY `0o700` — catching, rather than silently
205
+ * tolerating, an unusual host umask that narrows even owner bits. Existing
206
+ * ancestor components (e.g. the repo root, or `/tmp`) are left
207
+ * untouched — this only tightens components it creates itself.
208
+ */
209
+ export function mkdirOwnerOnlySync(dirPath) {
210
+ const resolved = path.resolve(dirPath);
211
+ const segments = resolved.split(path.sep).filter(Boolean);
212
+ let current = path.isAbsolute(resolved) ? path.sep : '';
213
+ for (const segment of segments) {
214
+ current = current === path.sep ? path.join(current, segment) : (current ? path.join(current, segment) : segment);
215
+ if (existsSync(current)) {
216
+ const existingStat = lstatSync(current);
217
+ if (!existingStat.isDirectory()) {
218
+ throw new Error(`refusing to use ${current} as a directory: it already exists and is not a directory`);
219
+ }
220
+ continue; // pre-existing ancestor: leave its permissions as found.
221
+ }
222
+ mkdirSync(current, { mode: 0o700 });
223
+ const created = lstatSync(current);
224
+ const createdMode = created.mode & 0o777;
225
+ if (createdMode !== 0o700) {
226
+ throw new Error(`refusing ${current}: expected mode 0700 immediately after creation, got ${createdMode.toString(8)} (never widened via chmod-after-the-fact)`);
227
+ }
228
+ }
229
+ return resolved;
230
+ }
231
+
232
+ /**
233
+ * Back-compat alias kept for any external caller still naming the old
234
+ * "mkdir then chmod" step; now routes through the exposure-window-free
235
+ * `mkdirOwnerOnlySync`. Prefer `mkdirOwnerOnlySync` directly in new code.
236
+ */
237
+ export function forceOwnerOnlyDir(dirPath) {
238
+ if (existsSync(dirPath)) {
239
+ const stat = lstatSync(dirPath);
240
+ if (!stat.isDirectory()) throw new Error(`refusing to use ${dirPath} as a directory: it already exists and is not a directory`);
241
+ return dirPath;
242
+ }
243
+ return mkdirOwnerOnlySync(dirPath);
244
+ }
245
+
246
+ function runGit(args, { cwd, spawn = spawnSync, timeoutMs = 30000 } = {}) {
247
+ const result = spawn('git', args, { cwd, encoding: 'utf8', timeout: timeoutMs });
248
+ if (result.error) throw new Error(`git ${args.join(' ')} failed to run: ${result.error.message}`);
249
+ if (result.status !== 0) {
250
+ throw new Error(`git ${args.join(' ')} exited ${result.status}: ${String(result.stderr ?? '').trim()}`);
251
+ }
252
+ return String(result.stdout ?? '').trim();
253
+ }
254
+
255
+ /**
256
+ * Resolve `revision` to an exact, immutable base digest (full commit SHA).
257
+ * Never pass a moving ref (branch name, `HEAD`) onward as the recorded
258
+ * base — resolve it here first so the brief's `workspace.baseRevision`
259
+ * (schemas/mission-v1.schema.json `$defs/workerDirectBrief`) is a digest,
260
+ * not a pointer that can move after the worktree is created.
261
+ */
262
+ export function resolveBaseDigest({ repoRoot, revision = 'HEAD', spawn = spawnSync, timeoutMs = 30000 } = {}) {
263
+ const digest = runGit(['rev-parse', '--verify', `${revision}^{commit}`], { cwd: repoRoot, spawn, timeoutMs });
264
+ if (!/^[a-f0-9]{40}$/i.test(digest)) {
265
+ throw new Error(`git rev-parse did not return a commit SHA for ${revision}: ${digest}`);
266
+ }
267
+ return digest;
268
+ }
269
+
270
+ /**
271
+ * Create a unique writer worktree at an exact base digest, after claiming
272
+ * ownership of the requested files/ports. Fails closed: a claim conflict
273
+ * or a failing `git worktree add` leaves no worktree behind and (on the
274
+ * git-failure path) releases the claim it just took, so a failed
275
+ * preparation never leaks ownership of files/ports nobody can use.
276
+ *
277
+ * @param {object} options
278
+ * @param {string} options.repoRoot - Absolute path to the repository the worktree is cut from.
279
+ * @param {string} options.ownerId - Conductor-local id for this writer attempt (unique per attempt).
280
+ * @param {string} options.name - Human-readable worktree label (used in the directory name only).
281
+ * @param {string} [options.revision='HEAD'] - Revision to resolve into an exact base digest.
282
+ * @param {{files?: string[], ports?: number[]}} [options.claims] - Ownership claims to hold for this writer (files must be absolute paths).
283
+ * @param {WorktreeClaimRegistry} options.registry - Shared claim registry for this conductor run.
284
+ * @param {string} [options.worktreesRoot] - Parent directory for writer worktrees (defaults under `.aiwg/working/worktrees`).
285
+ * @param {boolean} [options.deployContext=true] - Deploy AIWG context for the configured providers into the new worktree (Tier 0 default on, #3685).
286
+ * @param {string[]|null} [options.contextProviders=null] - Explicit provider ids, or null to resolve the union of
287
+ * config providers and orchestration CLIs via `readAiwgConfig` (round 2; never ad-hoc JSON).
288
+ * @param {string} [options.aiwgBin='aiwg'] - Binary for the default single-pass deploy.
289
+ * @param {(opts: object) => object} [options.deployContextFn] - Injectable single-pass deploy (defaults to `defaultDeployWorkerContext`).
290
+ * @param {(opts: object) => object} [options.verifyContextFn] - Injectable rule-section verifier (defaults to `verifyWorkerContextSections`).
291
+ * @param {(cmd: string, args: string[], opts: object) => object} [options.spawn=spawnSync]
292
+ * @param {(repoRoot: string) => Promise<object|null>} [options.contextReadConfig] - Injectable config loader (defaults to `readAiwgConfig`).
293
+ * @param {(config: object) => object} [options.contextResolveFromConfig] - Injectable union resolver (defaults to the src-side pure function).
294
+ * @returns {Promise<{created: boolean, blocked?: boolean, conflicts?: Array, path?: string, baseDigest?: string, context?: object, excludedLocalOnlyPaths?: string[]}>}
295
+ */
296
+ export async function prepareWorkerWorktree({
297
+ repoRoot,
298
+ ownerId,
299
+ name = 'writer',
300
+ revision = 'HEAD',
301
+ claims = {},
302
+ registry,
303
+ worktreesRoot,
304
+ deployContext = true,
305
+ contextProviders = null,
306
+ aiwgBin = 'aiwg',
307
+ deployContextFn = null,
308
+ verifyContextFn = null,
309
+ contextReadConfig = null,
310
+ contextResolveFromConfig = null,
311
+ spawn = spawnSync,
312
+ timeoutMs = 30000,
313
+ } = {}) {
314
+ if (!registry || typeof registry.claim !== 'function') {
315
+ throw new Error('prepareWorkerWorktree requires a WorktreeClaimRegistry');
316
+ }
317
+ // Resolve the base digest before claiming anything: an unresolvable
318
+ // revision should never hold a claim even transiently.
319
+ const baseDigest = resolveBaseDigest({ repoRoot, revision, spawn, timeoutMs });
320
+ const grant = registry.claim(ownerId, claims);
321
+ if (!grant.granted) {
322
+ return { created: false, blocked: true, conflicts: grant.conflicts };
323
+ }
324
+ // Every failure from here on must release the claim it just took, so a
325
+ // failed preparation never leaks ownership of files/ports nobody can use.
326
+ try {
327
+ const root = worktreesRoot ?? path.join(repoRoot, '.aiwg', 'working', 'worktrees');
328
+ // M5: create (every newly-created component of) the worktrees-root at
329
+ // mode 0700 from the moment it is created — never default-mode-then-
330
+ // chmod — so there is no window where it is briefly wider than intended.
331
+ mkdirOwnerOnlySync(root);
332
+ const stem = `${name}-${ownerId}`.replace(/[^A-Za-z0-9_.-]/g, '-');
333
+ const worktreePath = path.join(root, stem);
334
+ if (existsSync(worktreePath)) {
335
+ throw new Error(`worktree path already exists: ${worktreePath} (ownership not held twice for one path)`);
336
+ }
337
+ // M5: pre-create the worktree's own directory at mode 0700 (same
338
+ // exposure-window-free helper) BEFORE `git worktree add` ever touches
339
+ // it. `git worktree add` happily adopts a pre-existing EMPTY directory
340
+ // without altering its mode (verified empirically), so the directory is
341
+ // 0700 from its very first instant on disk instead of being created by
342
+ // git at a default mode and chmod-ed afterward.
343
+ mkdirOwnerOnlySync(worktreePath);
344
+ runGit(['worktree', 'add', '--detach', worktreePath, baseDigest], { cwd: repoRoot, spawn, timeoutMs });
345
+ const finalMode = statSync(worktreePath).mode & 0o777;
346
+ if (finalMode !== 0o700) {
347
+ throw new Error(`refusing worktree ${worktreePath}: expected mode 0700 after git worktree add, got ${finalMode.toString(8)}`);
348
+ }
349
+ try {
350
+ const excludedLocalOnlyPaths = await excludeWorkerLocalOnlyPaths({ repoRoot, worktreePath, spawn, timeoutMs });
351
+ // #3685: a fresh worktree contains only tracked files, so deployed
352
+ // provider context (.codex/, .claude/, .muse/, .agents/, AGENTS.md rule
353
+ // sections) is missing until the conductor deploys it. Default on for
354
+ // Tier 0; pass deployContext:false only to test worktree mechanics.
355
+ let context = { deployed: false, providers: [], skippedBridges: [] };
356
+ if (deployContext) {
357
+ // The union needs `readAiwgConfig` (async): an explicit list wins
358
+ // verbatim, otherwise the config providers plus orchestration CLIs.
359
+ // Deploying a guessed set would leave the worker with the wrong (or
360
+ // no) context, so resolution failure throws before anything is made.
361
+ const { providers } = await resolveWorkerContextProviders({
362
+ repoRoot, providers: contextProviders,
363
+ ...(contextReadConfig ? { readConfig: contextReadConfig } : {}),
364
+ ...(contextResolveFromConfig ? { resolveFromConfig: contextResolveFromConfig } : {}),
365
+ });
366
+ const deploy = deployContextFn ?? defaultDeployWorkerContext;
367
+ await deploy({ worktreePath, repoRoot, providers, aiwgBin, spawn, timeoutMs });
368
+ // Keep the deploy's tracked-bridge edits out of the worker diff:
369
+ // flag each deploy-dirtied tracked file skip-worktree (content
370
+ // stays on disk for the worker; only git status/diff hides it).
371
+ const dirtied = listDeployDirtiedBridges({ worktreePath, spawn, timeoutMs });
372
+ if (dirtied.length > 0) {
373
+ runGit(['update-index', '--skip-worktree', '--', ...dirtied], { cwd: worktreePath, spawn, timeoutMs });
374
+ }
375
+ const verify = verifyContextFn ?? verifyWorkerContextSections;
376
+ verify({ worktreePath, providers });
377
+ context = { deployed: true, providers, skippedBridges: dirtied };
378
+ }
379
+ return { created: true, path: worktreePath, baseDigest, ownerId, context, excludedLocalOnlyPaths };
380
+ } catch (error) {
381
+ // Policy, exclusion and context failures leave no worker tree or claim.
382
+ try {
383
+ runGit(['worktree', 'remove', '--force', worktreePath], { cwd: repoRoot, spawn, timeoutMs });
384
+ } catch { /* best-effort cleanup; report the preparation failure */ }
385
+ throw error;
386
+ }
387
+ } catch (error) {
388
+ registry.release(ownerId);
389
+ throw error;
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Release a writer's ownership claims. Dirty/failed work is retained by
395
+ * default (08's retention rule: never force-delete unexplained dirty
396
+ * work) — only release the registry bookkeeping. Pass `remove: true` only
397
+ * after the caller has made and recorded an explicit disposition decision
398
+ * (accepted-and-integrated, or explicitly discarded); that decision is a
399
+ * workflow/operator concern this module does not make on its own.
400
+ */
401
+ export function releaseWorkerWorktree({
402
+ registry,
403
+ ownerId,
404
+ repoRoot,
405
+ worktreePath,
406
+ remove = false,
407
+ spawn = spawnSync,
408
+ timeoutMs = 30000,
409
+ } = {}) {
410
+ if (!registry || typeof registry.release !== 'function') {
411
+ throw new Error('releaseWorkerWorktree requires a WorktreeClaimRegistry');
412
+ }
413
+ registry.release(ownerId);
414
+ if (!remove) return { removed: false, retained: true, path: worktreePath };
415
+ runGit(['worktree', 'remove', '--force', worktreePath], { cwd: repoRoot, spawn, timeoutMs });
416
+ return { removed: true, retained: false, path: worktreePath };
417
+ }
@@ -52,6 +52,7 @@ import { buildSessionEnvironment } from './lib/session-environment.mjs';
52
52
  import { withWorkerPath, withWorkerDirectory, boundedPrivateRead } from './lib/worker-inputs.mjs';
53
53
  import { collectWorkerFinal } from './lib/worker-final.mjs';
54
54
  import { workerRunDirectoryRefusal } from './lib/worker-run-directory-refusal.mjs';
55
+ import { createAttemptRunDirectory } from './lib/worker-run-directory.mjs';
55
56
  import { workerPromptBrief } from './lib/worker-prompt.mjs';
56
57
  import { prepareWorkerRetry, workerRetryRecordFields } from './lib/worker-retry-evidence.mjs';
57
58
  import { settleWorkerTermination, terminationRemedy } from './lib/worker-termination.mjs';
@@ -349,14 +350,6 @@ function workerLaunchRefusal(outcome) {
349
350
  // Neither worker output nor a caller-supplied result can populate this context.
350
351
  const directStartupCorrectionContext = new WeakMap();
351
352
 
352
- // Each attempt directory is created exclusively; its parent is the conductor's job.
353
- async function createAttemptRunDirectory(runDir) {
354
- try { await mkdir(runDir, { mode: 0o700 }); } catch (error) {
355
- if (error?.code === 'ENOENT') throw new Error(`Worker run directory parent does not exist: ${dirname(runDir)}; create it (mode 0700) before launch`);
356
- throw error;
357
- }
358
- }
359
-
360
353
  async function launchOneWorker(owner, options) {
361
354
  const { inspectWorkerPath: inspect, revalidateWorkerInvocationPlan: validatePlan } = await importImpl(import.meta.url, 'serve/worker-invocation.js');
362
355
  // Forward the saved-plan path: invocation identity is verified against it (#2905).
@@ -500,7 +493,7 @@ async function launchOneWorker(owner, options) {
500
493
  // themselves; pre-spawn refusals above never reach this point. Global
501
494
  // dispatch AND per-CLI enablement are checked inside `admitDirectWorker`
502
495
  // before any breaker construction (#2915 final review, finding 1).
503
- const invocationId = invocation.invocationId ?? randomUUID();
496
+ const invocationId = invocation.invocationId ?? options.invocationId ?? randomUUID();
504
497
  // #2915 review 4 (finding 8): computed ONCE, before admission, so the
505
498
  // SAME digest both gates the allowance reservation here and is published
506
499
  // into invocation.json below — never recomputed from a possibly-stale
@@ -618,7 +611,7 @@ async function launchOneWorker(owner, options) {
618
611
  // the reservation exactly like every other pre-spawn exit, never leak it
619
612
  // by throwing before the big try/catch below is reached.
620
613
  try {
621
- if (!runExists) await createAttemptRunDirectory(runDir); // exclusive attempt: no recursive creation or reuse
614
+ if (!runExists) await createAttemptRunDirectory(runDir, options.projectRoot); // exclusive attempt
622
615
  const runStat = await lstat(runDir);
623
616
  if (runStat.uid !== process.getuid()) throw new Error('Worker run directory must be conductor-owned');
624
617
  await withWorkerPath(runDir, async target => { const handle = await open(target, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
@@ -1539,12 +1532,12 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1539
1532
  loadInputs, validate, inspect, clock, qualificationDigest } = ctx;
1540
1533
  let inputs = ctx.inputs;
1541
1534
  let localGate = gate;
1542
- if (!runExists) await createAttemptRunDirectory(runDir); // exclusive attempt: no recursive creation or reuse
1535
+ if (!runExists) await createAttemptRunDirectory(runDir, options.projectRoot); // exclusive attempt
1543
1536
  const runStat = await lstat(runDir);
1544
1537
  if (runStat.uid !== process.getuid()) throw new Error('Worker run directory must be conductor-owned');
1545
1538
  await withWorkerPath(runDir, async target => { const handle = await open(target, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
1546
1539
  try { await handle.chmod(0o700); } finally { await handle.close(); } });
1547
- const invocationId = invocation.invocationId ?? (options.managedAdmission ? options.managedInvocationId : randomUUID());
1540
+ const invocationId = invocation.invocationId ?? options.invocationId ?? (options.managedAdmission ? options.managedInvocationId : randomUUID());
1548
1541
  if (options.managedAdmission && invocationId !== options.managedInvocationId) throw new Error('Worker artifact invocation id differs from managed admission');
1549
1542
  const reservation = await withWorkerPath(join(runDir, '.launch-owner'), target => open(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600));
1550
1543
  try { await reservation.writeFile(invocationId); await reservation.sync(); } finally { await reservation.close(); }
@@ -4910,7 +4903,7 @@ export function planDirectWorkerLaunch({
4910
4903
  proposeUnit,
4911
4904
  kind,
4912
4905
  attached = false,
4913
- ownedGroup = false, onSpawnAttempt,
4906
+ ownedGroup = false, onSpawnAttempt, runDir,
4914
4907
  // #2892: forwarded only when explicitly given, so every existing caller
4915
4908
  // (which omits it) keeps #2895's own `attached` default (`stdin: 'closed'`
4916
4909
  // -> stdio[0] 'ignore') unchanged. An MCP stdio worker passes `'open'` to
@@ -4963,7 +4956,7 @@ export function planDirectWorkerLaunch({
4963
4956
  // comment. Omitted by every existing caller today.
4964
4957
  dispatchGuard,
4965
4958
  } = {}) {
4966
- if (invocation?.stdin === 'brief-json' && stdinPath === undefined) {
4959
+ if (invocation?.stdin === 'brief-json' && stdinPath === undefined && !runDir) {
4967
4960
  throw new Error('brief-json stdin requires an explicit conductor-framed params file (stdinPath)');
4968
4961
  }
4969
4962
  // #2915 final (step 6, compatibility): the dispatch switch is consulted
@@ -4993,7 +4986,7 @@ export function planDirectWorkerLaunch({
4993
4986
  }
4994
4987
  let dispatchAttempt;
4995
4988
  const launch = (onDispatchCommit) => launchIsolatedWorker({ name, memoryMaxGb, command, args, cwd, logFile, stdinPath, stdoutPath, stderrPath,
4996
- gate, config, allowDegraded, attached, ownedGroup,
4989
+ gate, config, allowDegraded, attached, ownedGroup, runDir, workerGroup: invocation?.selected?.group,
4997
4990
  onSpawnAttempt: onDispatchCommit ? value => { dispatchAttempt = value; onSpawnAttempt?.(value); } : onSpawnAttempt,
4998
4991
  ...(envNames !== undefined ? { envNames } : {}), ...(env !== undefined ? { env } : {}),
4999
4992
  ...(isolation !== undefined ? { isolation } : {}), ...(spawn !== undefined ? { spawn } : {}),
@@ -1398,6 +1398,33 @@
1398
1398
  "minLength": 1,
1399
1399
  "format": "uri"
1400
1400
  },
1401
+ "localModels": {
1402
+ "type": "object",
1403
+ "additionalProperties": false,
1404
+ "required": ["endpoint", "models"],
1405
+ "description": "Operator-declared self-hosted execution path; GET endpoint/models observes presence, not backend identity or privacy guarantees.",
1406
+ "properties": {
1407
+ "endpoint": { "type": "string", "format": "uri", "pattern": "^https?://" },
1408
+ "authEnv": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" },
1409
+ "allowedHosts": { "type": "array", "uniqueItems": true, "items": { "type": "string", "minLength": 1 } },
1410
+ "timeoutMs": { "type": "integer", "minimum": 1, "maximum": 30000 },
1411
+ "models": {
1412
+ "type": "array", "minItems": 1,
1413
+ "items": {
1414
+ "type": "object", "additionalProperties": false,
1415
+ "required": ["id", "checkpoint"],
1416
+ "properties": {
1417
+ "id": { "type": "string", "minLength": 1 },
1418
+ "checkpoint": { "type": "string", "minLength": 1 },
1419
+ "family": { "type": "string", "minLength": 1 },
1420
+ "contextTokens": { "type": "integer", "minimum": 1 },
1421
+ "maxOutputTokens": { "type": "integer", "minimum": 1 },
1422
+ "efforts": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "type": "string", "minLength": 1 } }
1423
+ }
1424
+ }
1425
+ }
1426
+ }
1427
+ },
1401
1428
  "accountScope": {
1402
1429
  "type": "string",
1403
1430
  "minLength": 1