@fitlab-ai/agent-infra 0.9.5 → 0.9.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 (106) hide show
  1. package/dist/bin/internal-cli.js +3 -3
  2. package/dist/lib/agent-clients/adapters/codex-lifecycle/app-server.js +126 -16
  3. package/dist/lib/agent-clients/adapters/codex-lifecycle/evidence.js +14 -2
  4. package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +48 -4
  5. package/dist/lib/agent-clients/adapters/codex.js +1 -1
  6. package/dist/lib/git/workflow.js +0 -1
  7. package/dist/lib/internal/codex-lifecycle.js +100 -2
  8. package/dist/lib/internal/release-workflow.js +108 -11
  9. package/dist/lib/internal/sandbox-control.js +43 -6
  10. package/dist/lib/internal/task-create.js +12 -4
  11. package/dist/lib/internal/task-orchestration.js +5 -4
  12. package/dist/lib/platform/issue-comments.js +2 -1
  13. package/dist/lib/release/workflow.js +29 -21
  14. package/dist/lib/sandbox/commands/create.js +15 -16
  15. package/dist/lib/sandbox/commands/prune.js +40 -16
  16. package/dist/lib/sandbox/commands/rm.js +318 -89
  17. package/dist/lib/sandbox/control/client.js +138 -22
  18. package/dist/lib/sandbox/control/executor.js +136 -0
  19. package/dist/lib/sandbox/control/lifecycle.js +348 -0
  20. package/dist/lib/sandbox/control/protocol.js +62 -26
  21. package/dist/lib/sandbox/control/server.js +222 -102
  22. package/dist/lib/sandbox/control/state.js +181 -0
  23. package/dist/lib/sandbox/index.js +2 -2
  24. package/dist/lib/sandbox/managed-fs.js +14 -2
  25. package/dist/lib/sandbox/mounts.js +35 -24
  26. package/dist/lib/sandbox/recovery.js +262 -45
  27. package/dist/lib/sandbox/workspace-view.js +73 -10
  28. package/dist/lib/sandbox/worktree-safety.js +196 -0
  29. package/dist/lib/server/process-control.js +6 -0
  30. package/dist/lib/task/artifact-lifecycle.js +5 -4
  31. package/dist/lib/task/codex-orchestration.js +161 -0
  32. package/dist/lib/task/commands/status.js +3 -0
  33. package/dist/lib/task/commands/validate.js +289 -0
  34. package/dist/lib/task/commit-finalization.js +36 -9
  35. package/dist/lib/task/delegation-receipts.js +25 -0
  36. package/dist/lib/task/events.js +10 -4
  37. package/dist/lib/task/finalization-artifacts.js +2 -1
  38. package/dist/lib/task/implementation-inputs.js +1 -7
  39. package/dist/lib/task/index.js +9 -0
  40. package/dist/lib/task/orchestration.js +133 -4
  41. package/dist/lib/task/verification-engine.js +38 -6
  42. package/dist/lib/task/verification.js +1 -0
  43. package/lib/agent-clients/adapters/codex-lifecycle/app-server.ts +142 -15
  44. package/lib/agent-clients/adapters/codex-lifecycle/evidence.ts +19 -3
  45. package/lib/agent-clients/adapters/codex-lifecycle/store.ts +51 -3
  46. package/lib/agent-clients/adapters/codex.ts +1 -1
  47. package/lib/git/workflow.ts +0 -1
  48. package/lib/internal/codex-lifecycle.ts +107 -3
  49. package/lib/internal/release-workflow.ts +107 -11
  50. package/lib/internal/sandbox-control.ts +38 -6
  51. package/lib/internal/task-create.ts +16 -4
  52. package/lib/internal/task-orchestration.ts +4 -4
  53. package/lib/platform/issue-comments.ts +2 -1
  54. package/lib/release/workflow.ts +69 -20
  55. package/lib/sandbox/commands/create.ts +17 -21
  56. package/lib/sandbox/commands/prune.ts +53 -15
  57. package/lib/sandbox/commands/rm.ts +368 -103
  58. package/lib/sandbox/control/client.ts +152 -28
  59. package/lib/sandbox/control/executor.ts +163 -0
  60. package/lib/sandbox/control/lifecycle.ts +342 -0
  61. package/lib/sandbox/control/protocol.ts +96 -69
  62. package/lib/sandbox/control/server.ts +239 -110
  63. package/lib/sandbox/control/state.ts +196 -0
  64. package/lib/sandbox/index.ts +2 -2
  65. package/lib/sandbox/managed-fs.ts +17 -2
  66. package/lib/sandbox/mounts.ts +31 -13
  67. package/lib/sandbox/recovery.ts +301 -60
  68. package/lib/sandbox/workspace-view.ts +81 -11
  69. package/lib/sandbox/worktree-safety.ts +234 -0
  70. package/lib/server/process-control.ts +11 -0
  71. package/lib/task/artifact-lifecycle.ts +5 -4
  72. package/lib/task/codex-orchestration.ts +233 -0
  73. package/lib/task/commands/status.ts +2 -0
  74. package/lib/task/commands/validate.ts +282 -0
  75. package/lib/task/commit-finalization.ts +52 -9
  76. package/lib/task/delegation-receipts.ts +52 -3
  77. package/lib/task/events.ts +9 -4
  78. package/lib/task/finalization-artifacts.ts +2 -1
  79. package/lib/task/implementation-inputs.ts +1 -5
  80. package/lib/task/index.ts +8 -0
  81. package/lib/task/orchestration.ts +199 -4
  82. package/lib/task/verification-engine.ts +42 -8
  83. package/lib/task/verification.ts +2 -1
  84. package/package.json +1 -1
  85. package/templates/.agents/hooks/lifecycle-delegation.js +48 -12
  86. package/templates/.agents/rules/lifecycle-orchestration.en.md +1 -1
  87. package/templates/.agents/rules/lifecycle-orchestration.zh-CN.md +1 -1
  88. package/templates/.agents/rules/no-mid-flow-questions.en.md +1 -0
  89. package/templates/.agents/rules/no-mid-flow-questions.zh-CN.md +1 -0
  90. package/templates/.agents/skills/post-release/SKILL.en.md +32 -6
  91. package/templates/.agents/skills/post-release/SKILL.zh-CN.md +32 -6
  92. package/templates/.agents/skills/run-manual-validation/SKILL.en.md +42 -0
  93. package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +42 -0
  94. package/templates/.agents/skills/run-manual-validation/config/verify.en.json +14 -0
  95. package/templates/.agents/skills/run-manual-validation/config/verify.zh-CN.json +14 -0
  96. package/templates/.agents/skills/run-manual-validation/reference/report-template.en.md +44 -0
  97. package/templates/.agents/skills/run-manual-validation/reference/report-template.zh-CN.md +44 -0
  98. package/templates/.agents/skills/run-task/SKILL.en.md +2 -2
  99. package/templates/.agents/skills/run-task/SKILL.zh-CN.md +2 -2
  100. package/templates/.agents/skills/run-task/reference/host-validation.en.md +3 -3
  101. package/templates/.agents/skills/run-task/reference/host-validation.zh-CN.md +3 -3
  102. package/templates/.claude/commands/run-manual-validation.en.md +9 -0
  103. package/templates/.claude/commands/run-manual-validation.zh-CN.md +9 -0
  104. package/templates/.codex/hooks.json +8 -8
  105. package/templates/.opencode/commands/run-manual-validation.en.md +11 -0
  106. package/templates/.opencode/commands/run-manual-validation.zh-CN.md +11 -0
@@ -129,7 +129,6 @@ function pushRebasedBranch(input: PushRebasedInput, runner: GitRunner = defaultR
129
129
  .map((name) => value(runner, input.cwd, ['rev-parse', '--git-path', name]))
130
130
  .filter((candidate): candidate is string => Boolean(candidate));
131
131
  if (snapshot.worktree.length > 0 || snapshot.staged.length > 0 ||
132
- run(runner, input.cwd, ['rev-parse', '-q', '--verify', 'REBASE_HEAD']).status === 0 ||
133
132
  rebasePaths.some((candidate) => fs.existsSync(path.isAbsolute(candidate) ? candidate : path.join(input.cwd, candidate)))) {
134
133
  return { status: 'failed' as const, changed: false, snapshot, operations: [], error: { code: 'GIT_LOCAL_STATE_UNSAFE', message: 'Working tree must be clean with no rebase in progress' } };
135
134
  }
@@ -10,11 +10,19 @@ import {
10
10
  } from '../agent-clients/adapters/codex-lifecycle/app-server.ts';
11
11
  import { createCodexLifecycleStore } from '../agent-clients/adapters/codex-lifecycle/store.ts';
12
12
  import type { CodexLifecycleEvent } from '../agent-clients/adapters/codex-lifecycle/evidence.ts';
13
+ import {
14
+ activateCodexOrchestrationDelegation,
15
+ activateCodexSpawnDelegation,
16
+ reconcileCodexOrchestrationDelegation,
17
+ sealCodexOrchestrationDelegation,
18
+ sealCodexParentDelegation
19
+ } from '../task/codex-orchestration.ts';
13
20
 
14
21
  const USAGE = 'Usage: agent-infra-internal codex-lifecycle <hook-event|resolve-start|resolve-stop|preflight|consume> [options]\n';
15
22
  const MANAGED_AGENT = /^agent-infra-lifecycle-(executor|reviewer)$/;
16
23
 
17
24
  type Parsed = Readonly<{ operation: string; values: Readonly<Record<string, string>> }>;
25
+ type UnresolvedHookChild = Omit<Extract<CodexLifecycleEvent, { type: 'hook-child' }>, 'parentThreadId'>;
18
26
 
19
27
  function output(value: unknown): void {
20
28
  process.stdout.write(`${JSON.stringify(value)}\n`);
@@ -25,6 +33,15 @@ function failure(code: string, message: string): void {
25
33
  process.exitCode = 1;
26
34
  }
27
35
 
36
+ function outputBridgeResult(result: Awaited<ReturnType<typeof activateCodexOrchestrationDelegation>>): void {
37
+ if (result.error?.code === 'ORCHESTRATION_DELEGATION_MISSING') {
38
+ output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
39
+ return;
40
+ }
41
+ output(result);
42
+ if (result.status !== 'running') process.exitCode = 1;
43
+ }
44
+
28
45
  function parse(args: string[]): Parsed | null {
29
46
  if (args[0] === '--help' || args[0] === '-h') {
30
47
  process.stdout.write(USAGE);
@@ -36,7 +53,7 @@ function parse(args: string[]): Parsed | null {
36
53
  return null;
37
54
  }
38
55
  const allowed = {
39
- 'hook-event': ['--event'],
56
+ 'hook-event': ['--event', '--bridge'],
40
57
  'resolve-start': ['--child-id'],
41
58
  'resolve-stop': ['--child-id'],
42
59
  preflight: ['--format', '--session-id', '--turn-id', '--tool-use-id'],
@@ -85,7 +102,7 @@ async function readStdin(): Promise<unknown> {
85
102
  return JSON.parse(input || '{}') as unknown;
86
103
  }
87
104
 
88
- function recordFromPayload(phase: string, payload: unknown): CodexLifecycleEvent | null {
105
+ function recordFromPayload(phase: string, payload: unknown): CodexLifecycleEvent | UnresolvedHookChild | null {
89
106
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
90
107
  throw new Error('Codex lifecycle hook payload must be an object');
91
108
  }
@@ -120,6 +137,13 @@ function recordFromPayload(phase: string, payload: unknown): CodexLifecycleEvent
120
137
  throw new Error(`unknown Codex lifecycle hook phase '${phase}'`);
121
138
  }
122
139
 
140
+ function payloadText(payload: unknown, key: string): string {
141
+ return payload && typeof payload === 'object' && !Array.isArray(payload)
142
+ && typeof (payload as Record<string, unknown>)[key] === 'string'
143
+ ? (payload as Record<string, string>)[key]!
144
+ : '';
145
+ }
146
+
123
147
  async function codexLifecycle(args: string[] = []): Promise<void> {
124
148
  const parsed = parse(args);
125
149
  if (!parsed || process.exitCode) return;
@@ -153,12 +177,92 @@ async function codexLifecycle(args: string[] = []): Promise<void> {
153
177
  if (!phase || !['pre-tool', 'subagent-start', 'post-tool', 'subagent-stop'].includes(phase)) {
154
178
  throw new Error('hook-event requires a known --event');
155
179
  }
156
- const event = recordFromPayload(phase, await readStdin());
180
+ if (parsed.values['--bridge'] !== undefined && parsed.values['--bridge'] !== 'true') {
181
+ throw new Error("hook-event --bridge must be 'true'");
182
+ }
183
+ const payload = await readStdin();
184
+ if (phase === 'post-tool' && parsed.values['--bridge'] === 'true') {
185
+ const toolName = payloadText(payload, 'toolName');
186
+ if (toolName === 'collaborationspawn_agent') {
187
+ const nativeAgent = payloadText(payload, 'nativeAgent');
188
+ if (!MANAGED_AGENT.test(nativeAgent)) {
189
+ output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
190
+ return;
191
+ }
192
+ const requestedModel = payloadText(payload, 'requestedModel');
193
+ const requestedReasoningEffort = payloadText(payload, 'requestedReasoningEffort');
194
+ const bridged = await activateCodexSpawnDelegation({
195
+ sessionId: payloadText(payload, 'sessionId'),
196
+ turnId: payloadText(payload, 'turnId'),
197
+ toolUseId: payloadText(payload, 'toolUseId'),
198
+ transcriptPath: payloadText(payload, 'transcriptPath'),
199
+ nativeAgent,
200
+ taskName: payloadText(payload, 'taskName'),
201
+ ...(requestedModel ? { requestedModel } : {}),
202
+ ...(requestedReasoningEffort ? { requestedReasoningEffort } : {})
203
+ }, { store });
204
+ outputBridgeResult(bridged);
205
+ return;
206
+ }
207
+ if (toolName === 'collaborationwait_agent') {
208
+ outputBridgeResult(await sealCodexParentDelegation(payloadText(payload, 'sessionId'), { store }));
209
+ return;
210
+ }
211
+ output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
212
+ return;
213
+ }
214
+ const event = recordFromPayload(phase, payload);
157
215
  if (!event) {
216
+ if (phase === 'post-tool' && parsed.values['--bridge'] === 'true') {
217
+ const value = payload as Record<string, unknown>;
218
+ const childThreadId = String(value.childThreadId ?? '');
219
+ const reconciled = reconcileCodexOrchestrationDelegation(childThreadId);
220
+ outputBridgeResult(reconciled);
221
+ return;
222
+ }
158
223
  output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
159
224
  return;
160
225
  }
226
+ if (parsed.values['--bridge'] === 'true' && event.type === 'hook-stop') {
227
+ try {
228
+ if (store.read(event.childThreadId).consumer) {
229
+ const bridged = await sealCodexOrchestrationDelegation(event.childThreadId, { store });
230
+ outputBridgeResult(bridged);
231
+ return;
232
+ }
233
+ } catch {
234
+ // The normal apply path below owns missing or invalid evidence errors.
235
+ }
236
+ }
237
+ if (parsed.values['--bridge'] === 'true' && event.type === 'hook-child') {
238
+ const resolved = await resolveCodexThread(event.childThreadId);
239
+ store.apply({
240
+ ...event,
241
+ parentThreadId: resolved.resolution.thread.parentThreadId
242
+ });
243
+ const bridged = await activateCodexOrchestrationDelegation(event.childThreadId, {
244
+ store,
245
+ resolveThread: async () => resolved
246
+ });
247
+ outputBridgeResult(bridged);
248
+ return;
249
+ }
250
+ if (event.type === 'hook-child') {
251
+ const resolved = await resolveCodexThread(event.childThreadId);
252
+ const result = store.apply({
253
+ ...event,
254
+ parentThreadId: resolved.resolution.thread.parentThreadId
255
+ });
256
+ output({ status: result.state.status, changed: true, evidence: result.state, diagnostics: resolved.diagnostics, error: result.state.error });
257
+ if (result.state.status === 'invalid') process.exitCode = 1;
258
+ return;
259
+ }
161
260
  const result = store.apply(event);
261
+ if (parsed.values['--bridge'] === 'true' && event.type === 'hook-stop') {
262
+ const bridged = await sealCodexOrchestrationDelegation(event.childThreadId, { store });
263
+ outputBridgeResult(bridged);
264
+ return;
265
+ }
162
266
  output({ status: result.state.status, changed: true, evidence: result.state, diagnostics: [], error: result.state.error });
163
267
  if (result.state.status === 'invalid') process.exitCode = 1;
164
268
  return;
@@ -8,7 +8,7 @@ import { commitExplicitPaths, inspectGitWorkflow, pushGitRefs } from '../git/wor
8
8
  import { inspectPlatformRelease, reconcileReleaseMilestones } from '../platform/releases.ts';
9
9
  import { inspectHomebrewChannel, inspectNpmChannel } from '../release/channels.ts';
10
10
  import { releaseSnapshot } from '../release/workflow.ts';
11
- import type { ReleaseFacts } from '../release/workflow.ts';
11
+ import type { PostReleaseFacts, ReleaseFacts } from '../release/workflow.ts';
12
12
 
13
13
  function command(cwd: string, executable: string, args: string[]) {
14
14
  return spawnSync(executable, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
@@ -168,12 +168,52 @@ function inspectLocalReleaseFacts(cwd: string, version: string, run: CommandRunn
168
168
  const localTagConflict = Boolean(tagCommit && !localTag && !localTagAncestor);
169
169
  const postSubject = `chore: prepare next dev iteration after v${version}`;
170
170
  const postLog = localTag || localTagAncestor
171
- ? git(cwd, ['log', '--format=%s', `${tag}..HEAD`], run) ?? ''
171
+ ? git(cwd, ['log', '--format=%H%x00%s', `${tag}..HEAD`], run) ?? ''
172
172
  : '';
173
- const postCommit = postLog.split('\n').some((subject) => subject === postSubject);
173
+ const postCommit = postLog.split('\n').map((line) => line.split('\0'))
174
+ .find(([, subject]) => subject === postSubject)?.[0] ?? null;
174
175
  return { localTag, localTagAncestor, localTagConflict, postCommit };
175
176
  }
176
177
 
178
+ function inspectPostReleaseFacts(
179
+ cwd: string,
180
+ commit: string | null,
181
+ run: CommandRunner = command
182
+ ): PostReleaseFacts {
183
+ const inspected = inspectGitWorkflow(cwd);
184
+ const snapshot = inspected.snapshot;
185
+ const branch = snapshot?.branch ?? '';
186
+ const remoteLine = branch ? git(cwd, ['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], run) : null;
187
+ const remoteHead = remoteLine?.split(/\s+/)[0] ?? null;
188
+ const packageJson = commit ? git(cwd, ['show', `${commit}:package.json`], run, false) : null;
189
+ let newVersion: string | null = null;
190
+ if (packageJson) {
191
+ try {
192
+ const version = (JSON.parse(packageJson) as { version?: unknown }).version;
193
+ newVersion = typeof version === 'string' ? version : null;
194
+ } catch {
195
+ newVersion = null;
196
+ }
197
+ }
198
+ const paths = commit ? git(cwd, ['diff-tree', '--root', '--no-commit-id', '--name-only', '-r', '-z', commit], run, false) : null;
199
+ const changedPaths = paths ? paths.split('\0').filter(Boolean)
200
+ .sort((left, right) => Buffer.from(left).compare(Buffer.from(right))) : [];
201
+ const digest = commit ? git(cwd, ['show', `${commit}:${DEMO_DIGEST_PATH}`], run) : null;
202
+ return {
203
+ commit,
204
+ isHead: Boolean(commit && snapshot?.head === commit),
205
+ published: Boolean(commit && remoteHead === commit),
206
+ branch,
207
+ upstream: snapshot?.upstream ?? null,
208
+ remoteHead,
209
+ newVersion,
210
+ changedPaths,
211
+ demoInputSha256: digest && /^[0-9a-f]{64}$/.test(digest) ? digest : null,
212
+ worktree: snapshot?.worktree ?? [],
213
+ staged: snapshot?.staged ?? []
214
+ };
215
+ }
216
+
177
217
  function releaseSmokeStatus(workflows: Array<Record<string, unknown>>, version: string, tagCommit: string | null): ReleaseFacts['smoke'] {
178
218
  const manualTitle = `Post-Release Smoke v${version}`;
179
219
  const targets = workflows.filter((run) => {
@@ -220,12 +260,15 @@ async function inspectFacts(cwd: string, version: string): Promise<ReleaseFacts>
220
260
  const workflows = platform.workflows as Array<Record<string, unknown>>;
221
261
  const smoke = releaseSmokeStatus(workflows, version, localTagTarget);
222
262
  return {
223
- ...local,
263
+ localTag: local.localTag,
264
+ localTagAncestor: local.localTagAncestor,
265
+ localTagConflict: local.localTagConflict,
224
266
  remoteBranch: Boolean(remoteBranch && remoteBranch.split(/\s+/)[0] === head), remoteTag: Boolean(remoteTag),
225
267
  githubRelease: platform.platform.type !== 'github'
226
268
  ? true
227
269
  : platform.status === 'blocked' ? null : Boolean(platform.release?.published),
228
- npm: npm.published, homebrew: homebrew.published, smoke
270
+ npm: npm.published, homebrew: homebrew.published, smoke,
271
+ post: inspectPostReleaseFacts(cwd, local.postCommit)
229
272
  };
230
273
  }
231
274
 
@@ -258,13 +301,21 @@ function updateReleaseMetadata(cwd: string, version: string): void {
258
301
  }
259
302
  }
260
303
 
304
+ function optionValues(args: string[], name: string): string[] {
305
+ const values: string[] = [];
306
+ for (let index = 0; index < args.length; index += 1) {
307
+ if (args[index] === name) values.push(args[index + 1] ?? '');
308
+ }
309
+ return values;
310
+ }
311
+
261
312
  async function releaseWorkflow(args: string[] = []): Promise<void> {
262
313
  const [action, rawVersion, ...rest] = args;
263
314
  const version = String(rawVersion || '').replace(/^v/, '');
264
315
  const cwdIndex = rest.indexOf('--cwd');
265
316
  const cwd = path.resolve(cwdIndex >= 0 && rest[cwdIndex + 1] ? rest[cwdIndex + 1]! : process.cwd());
266
- if (!['inspect', 'prepare', 'publish', 'post'].includes(action || '') || !semver.valid(version)) {
267
- process.stdout.write(`${JSON.stringify({ status: 'failed', changed: false, error: { code: 'RELEASE_INPUT_INVALID', message: 'Usage: release-workflow inspect|prepare|publish|post <version>' } })}\n`);
317
+ if (!['inspect', 'prepare', 'publish', 'post-prepare', 'post-publish'].includes(action || '') || !semver.valid(version)) {
318
+ process.stdout.write(`${JSON.stringify({ status: 'failed', changed: false, error: { code: 'RELEASE_INPUT_INVALID', message: 'Usage: release-workflow inspect|prepare|publish|post-prepare|post-publish <version>' } })}\n`);
268
319
  process.exitCode = 1; return;
269
320
  }
270
321
  const before = releaseSnapshot(version, await inspectFacts(cwd, version));
@@ -310,10 +361,51 @@ async function releaseWorkflow(args: string[] = []): Promise<void> {
310
361
  const result = pushGitRefs({ cwd, remote: 'origin', refs });
311
362
  process.stdout.write(`${JSON.stringify({ ...result, snapshot: releaseSnapshot(version, await inspectFacts(cwd, version)) })}\n`); process.exitCode = result.status === 'failed' ? 1 : result.status === 'degraded' ? 2 : 0; return;
312
363
  }
364
+ if (action === 'post-publish') {
365
+ const expectedValues = optionValues(rest, '--expected-sha256');
366
+ if (expectedValues.length !== 1 || !/^sha256:[0-9a-f]{64}$/.test(expectedValues[0]!)) {
367
+ process.stdout.write(`${JSON.stringify({ status: 'failed', changed: false, snapshot: before, error: { code: 'RELEASE_INPUT_INVALID', message: 'post-publish requires one --expected-sha256 sha256:<64 hex>' } })}\n`);
368
+ process.exitCode = 1; return;
369
+ }
370
+ if (before.phase === 'complete') {
371
+ process.stdout.write(`${JSON.stringify({ status: 'no-op', changed: false, snapshot: before, error: null })}\n`);
372
+ return;
373
+ }
374
+ const confirmation = 'postConfirmation' in before ? before.postConfirmation : null;
375
+ if (before.phase !== 'post-prepared' || !confirmation) {
376
+ process.stdout.write(`${JSON.stringify({ status: 'failed', changed: false, snapshot: before, error: { code: confirmation ? 'RELEASE_PHASE_INVALID' : 'RELEASE_POST_CONFIRMATION_UNAVAILABLE', message: 'Post-release facts cannot authorize publish' } })}\n`);
377
+ process.exitCode = 1; return;
378
+ }
379
+ if (confirmation.sha256 !== expectedValues[0]) {
380
+ process.stdout.write(`${JSON.stringify({ status: 'failed', changed: false, snapshot: before, error: { code: 'RELEASE_POST_SNAPSHOT_MISMATCH', message: 'Post-release confirmation snapshot changed' } })}\n`);
381
+ process.exitCode = 1; return;
382
+ }
383
+ const channelsComplete = before.facts.githubRelease === true && before.facts.npm === true && before.facts.homebrew === true;
384
+ if (!channelsComplete || before.facts.smoke !== 'success') {
385
+ process.stdout.write(`${JSON.stringify({ status: before.facts.smoke === 'failed' ? 'failed' : 'blocked', changed: false, snapshot: before, error: { code: 'RELEASE_CHANNELS_PENDING', message: 'Release channels or smoke workflow are not complete' } })}\n`);
386
+ process.exitCode = before.facts.smoke === 'failed' ? 1 : 2; return;
387
+ }
388
+ const pushed = pushGitRefs({ cwd, remote: 'origin', refs: [before.facts.post.branch] });
389
+ const snapshot = releaseSnapshot(version, await inspectFacts(cwd, version));
390
+ if (snapshot.phase === 'complete') {
391
+ process.stdout.write(`${JSON.stringify({ ...pushed, status: 'applied', changed: true, snapshot, error: null })}\n`);
392
+ return;
393
+ }
394
+ const blocked = pushed.status !== 'failed';
395
+ process.stdout.write(`${JSON.stringify({ ...pushed, status: blocked ? 'blocked' : 'failed', snapshot, error: pushed.error ?? { code: 'RELEASE_PROGRESS_PENDING', message: 'Post-release push is not visible at the expected remote head' } })}\n`);
396
+ process.exitCode = blocked ? 2 : 1; return;
397
+ }
398
+
313
399
  if (before.phase === 'complete') {
314
400
  process.stdout.write(`${JSON.stringify({ status: 'no-op', changed: false, snapshot: before, error: null })}\n`);
315
401
  return;
316
402
  }
403
+ if (before.phase === 'post-prepared') {
404
+ const confirmation = 'postConfirmation' in before ? before.postConfirmation : null;
405
+ const status = confirmation ? 'no-op' : 'blocked';
406
+ process.stdout.write(`${JSON.stringify({ status, changed: false, snapshot: before, error: confirmation ? null : { code: 'RELEASE_POST_CONFIRMATION_UNAVAILABLE', message: 'Post commit is not the clean current HEAD' } })}\n`);
407
+ process.exitCode = confirmation ? 0 : 2; return;
408
+ }
317
409
  const channelsComplete = before.facts.githubRelease === true && before.facts.npm === true && before.facts.homebrew === true;
318
410
  if (!['published', 'post-pending'].includes(before.phase) || !channelsComplete || before.facts.smoke !== 'success') {
319
411
  process.stdout.write(`${JSON.stringify({ status: before.facts.smoke === 'failed' ? 'failed' : 'blocked', changed: false, snapshot: before, error: { code: 'RELEASE_CHANNELS_PENDING', message: 'Release channels or smoke workflow are not complete' } })}\n`); process.exitCode = before.facts.smoke === 'failed' ? 1 : 2; return;
@@ -338,10 +430,14 @@ async function releaseWorkflow(args: string[] = []): Promise<void> {
338
430
  }
339
431
  const committed = commitExplicitPaths({ cwd, paths: changedPaths(cwd), message: `chore: prepare next dev iteration after v${version}` });
340
432
  if (committed.status === 'failed') { process.stdout.write(`${JSON.stringify(committed)}\n`); process.exitCode = 1; return; }
341
- const branch = git(cwd, ['branch', '--show-current']) || '';
342
- const pushed = pushGitRefs({ cwd, remote: 'origin', refs: [branch] });
343
- process.stdout.write(`${JSON.stringify({ ...pushed, demo, snapshot: releaseSnapshot(version, await inspectFacts(cwd, version)) })}\n`); process.exitCode = pushed.status === 'failed' ? 1 : pushed.status === 'degraded' ? 2 : 0;
433
+ const snapshot = releaseSnapshot(version, await inspectFacts(cwd, version));
434
+ const confirmation = 'postConfirmation' in snapshot ? snapshot.postConfirmation : null;
435
+ if (snapshot.phase !== 'post-prepared' || !confirmation) {
436
+ process.stdout.write(`${JSON.stringify({ status: 'failed', changed: true, demo, snapshot, error: { code: 'RELEASE_POST_CONFIRMATION_UNAVAILABLE', message: 'Prepared post commit did not produce a confirmation snapshot' } })}\n`);
437
+ process.exitCode = 1; return;
438
+ }
439
+ process.stdout.write(`${JSON.stringify({ status: 'applied', changed: true, demo, snapshot, error: null })}\n`);
344
440
  }
345
441
 
346
- export { changedPaths, computeDemoInputDigest, inspectFacts, inspectLocalReleaseFacts, inspectPostWorktree, releaseSmokeStatus, releaseWorkflow, runOptionalDemo };
442
+ export { changedPaths, computeDemoInputDigest, inspectFacts, inspectLocalReleaseFacts, inspectPostReleaseFacts, inspectPostWorktree, releaseSmokeStatus, releaseWorkflow, runOptionalDemo };
347
443
  export type { CommandRunner, DemoResult };
@@ -1,24 +1,56 @@
1
- import { requestSandboxControl } from '../sandbox/control/client.ts';
1
+ import { requestSandboxControl, SandboxControlClientError } from '../sandbox/control/client.ts';
2
2
  import { serveSandboxControl } from '../sandbox/control/server.ts';
3
+ import { runSandboxControlExecutor } from '../sandbox/control/executor.ts';
3
4
 
4
- function sandboxControl(args: string[]): void {
5
+ async function sandboxControl(args: string[]): Promise<void> {
5
6
  const [operation, ...rest] = args;
6
7
  if (operation === 'serve') {
7
8
  const manifestIndex = rest.indexOf('--manifest');
8
9
  const manifest = manifestIndex >= 0 ? rest[manifestIndex + 1] : undefined;
9
10
  if (!manifest) throw new Error('sandbox-control serve requires --manifest');
10
- serveSandboxControl(manifest);
11
+ const controller = new AbortController();
12
+ const abort = () => controller.abort();
13
+ process.once('SIGINT', abort);
14
+ process.once('SIGTERM', abort);
15
+ try {
16
+ await serveSandboxControl(manifest, controller.signal);
17
+ } finally {
18
+ process.off('SIGINT', abort);
19
+ process.off('SIGTERM', abort);
20
+ }
21
+ return;
22
+ }
23
+ if (operation === 'execute') {
24
+ const requestIndex = rest.indexOf('--request');
25
+ const nonceIndex = rest.indexOf('--nonce');
26
+ const request = requestIndex >= 0 ? rest[requestIndex + 1] : undefined;
27
+ const nonce = nonceIndex >= 0 ? rest[nonceIndex + 1] : undefined;
28
+ if (!request || !nonce) throw new Error('sandbox-control execute requires --request and --nonce');
29
+ await runSandboxControlExecutor(request, nonce);
11
30
  return;
12
31
  }
13
32
  if (operation === 'client') {
14
33
  const [family = '', ...commandArgs] = rest;
15
- const response = requestSandboxControl({ family, args: commandArgs });
34
+ let response;
35
+ try {
36
+ response = requestSandboxControl({ family, args: commandArgs });
37
+ } catch (error) {
38
+ if (!(error instanceof SandboxControlClientError)) throw error;
39
+ process.stderr.write(`${error.detail.message}\n`);
40
+ process.exitCode = error.detail.retryable ? 75 : 1;
41
+ return;
42
+ }
16
43
  process.stdout.write(response.stdout);
17
44
  process.stderr.write(response.stderr);
18
- process.exitCode = response.exitCode;
45
+ if (response.phase === 'rejected') {
46
+ process.stderr.write(response.error?.message ?? response.stderr);
47
+ process.exitCode = response.error?.retryable ? 75 : 1;
48
+ } else {
49
+ process.exitCode = response.exitCode ?? 1;
50
+ }
19
51
  return;
20
52
  }
21
- throw new Error('Usage: agent-infra-internal sandbox-control serve --manifest <path> | client <family> [args...]');
53
+ throw new Error('Usage: agent-infra-internal sandbox-control serve --manifest <path> | execute --request <path> --nonce <nonce> | client <family> [args...]');
22
54
  }
23
55
 
24
56
  export { sandboxControl };
@@ -1,15 +1,15 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
- import { requestSandboxTaskCreate } from '../sandbox/control/client.ts';
4
+ import { requestSandboxTaskCreate, SandboxControlClientError } from '../sandbox/control/client.ts';
5
5
  import { SANDBOX_CONTROL_MAX_BYTES } from '../sandbox/control/protocol.ts';
6
6
  import { validateTaskCreateCandidate } from '../task/create.ts';
7
7
  import { createTask, type TaskCreateResult } from '../task/create-service.ts';
8
8
 
9
- function failed(code: string, message: string): TaskCreateResult {
9
+ function failed(code: string, message: string, retryable = false): TaskCreateResult {
10
10
  return {
11
- status: 'failed', changed: false, task: { id: null, shortId: null }, issue: null,
12
- operations: [], warnings: [], error: { code, message, retryable: false }
11
+ status: retryable ? 'blocked' : 'failed', changed: false, task: { id: null, shortId: null }, issue: null,
12
+ operations: [], warnings: [], error: { code, message, retryable }
13
13
  };
14
14
  }
15
15
 
@@ -33,6 +33,14 @@ function taskCreate(args: string[]): void {
33
33
  const candidate = validateTaskCreateCandidate(JSON.parse(fs.readFileSync(inputPath, 'utf8')));
34
34
  if (process.env.AGENT_INFRA_CONTROL_TOKEN) {
35
35
  const response = requestSandboxTaskCreate({ candidate });
36
+ if (response.phase === 'rejected') {
37
+ output(failed(
38
+ response.error?.code ?? 'SANDBOX_CONTROL_REJECTED',
39
+ response.error?.message ?? response.stderr,
40
+ response.error?.retryable ?? false
41
+ ));
42
+ return;
43
+ }
36
44
  process.stdout.write(response.stdout);
37
45
  process.stderr.write(response.stderr);
38
46
  process.exitCode = response.exitCode;
@@ -40,6 +48,10 @@ function taskCreate(args: string[]): void {
40
48
  }
41
49
  output(createTask(candidate, { repoRoot: process.cwd() }));
42
50
  } catch (error) {
51
+ if (error instanceof SandboxControlClientError) {
52
+ output(failed(error.detail.code, error.detail.message, error.detail.retryable));
53
+ return;
54
+ }
43
55
  const message = error instanceof Error ? error.message : String(error);
44
56
  const code = /^([A-Z][A-Z0-9_]+)/.exec(message)?.[1] ?? 'TASK_CREATE_INPUT_INVALID';
45
57
  output(failed(code, message));
@@ -9,7 +9,6 @@ import {
9
9
  checkpointCommitIntent,
10
10
  completeCommitIntent,
11
11
  pauseOrchestration,
12
- prepareOrchestrationDelegation,
13
12
  recoverCommitIntent,
14
13
  routeOrchestration,
15
14
  sealMatchingOrchestrationDelegation,
@@ -19,6 +18,7 @@ import {
19
18
  statusOrchestration,
20
19
  terminateCommitAttempt
21
20
  } from '../task/orchestration.ts';
21
+ import { prepareCodexOrchestrationDelegation } from '../task/codex-orchestration.ts';
22
22
  import { isAgentClientId } from '../agent-clients/types.ts';
23
23
  import type { AgentClientId } from '../agent-clients/types.ts';
24
24
 
@@ -33,7 +33,7 @@ function usageFailure(message: string): void {
33
33
  process.exitCode = 2;
34
34
  }
35
35
 
36
- function taskOrchestration(args: string[] = []): void {
36
+ async function taskOrchestration(args: string[] = []): Promise<void> {
37
37
  if (args[0] === '--help' || args[0] === '-h') {
38
38
  process.stdout.write(USAGE);
39
39
  return;
@@ -212,11 +212,11 @@ function taskOrchestration(args: string[] = []): void {
212
212
  } else if (intent === 'prepare') {
213
213
  const missing = requireValues(['--client']);
214
214
  if (missing) { usageFailure(`intent 'prepare' requires '${missing}'`); return; }
215
- result = prepareOrchestrationDelegation(taskRef!, {
215
+ result = await prepareCodexOrchestrationDelegation(taskRef!, {
216
216
  client: values['--client'] as AgentClientId,
217
217
  requestedModel: values['--requested-model'],
218
218
  requestedReasoningEffort: values['--requested-reasoning-effort']
219
- }, coreOptions);
219
+ }, { orchestrationOptions: coreOptions });
220
220
  } else if (intent === 'hook-start') {
221
221
  const missing = requireValues([
222
222
  ...(taskRef === 'auto' ? ['--client'] : []),
@@ -39,6 +39,7 @@ const ARTIFACT_TITLES: Record<string, string> = {
39
39
  code: '实现报告',
40
40
  'review-code': '代码审查',
41
41
  'manual-validation': '人工验证报告',
42
+ 'validation-run': '验证运行证据',
42
43
  'pr-review': 'PR 审查报告'
43
44
  };
44
45
 
@@ -75,7 +76,7 @@ function renderTaskComment(content: string, taskId: string, agent: string): stri
75
76
 
76
77
  function artifactIdentity(artifact: string): { stem: string; title: string } {
77
78
  const stem = path.basename(artifact, '.md');
78
- const match = stem.match(/^(analysis|review-analysis|plan|review-plan|code|review-code|manual-validation|pr-review)(?:-r(\d+))?$/);
79
+ const match = stem.match(/^(analysis|review-analysis|plan|review-plan|code|review-code|manual-validation|validation-run|pr-review)(?:-r(\d+))?$/);
79
80
  if (!match) throw new Error(`unsupported artifact '${artifact}'`);
80
81
  const base = ARTIFACT_TITLES[match[1]!]!;
81
82
  const round = match[2] ? Number(match[2]) : 1;
@@ -1,32 +1,81 @@
1
- type ReleasePhase = 'unprepared' | 'prepared' | 'partially-published' | 'published' | 'post-pending' | 'complete';
2
- type ReleaseFacts = { localTag: boolean; localTagAncestor?: boolean; localTagConflict?: boolean; remoteBranch: boolean; remoteTag: boolean; githubRelease: boolean | null; npm: boolean | null; homebrew: boolean | null; smoke: 'success' | 'pending' | 'failed' | null; postCommit: boolean };
1
+ import crypto from 'node:crypto';
2
+
3
+ type ReleasePhase = 'unprepared' | 'prepared' | 'partially-published' | 'published' | 'post-pending' | 'post-prepared' | 'complete';
4
+ type PostReleaseFacts = {
5
+ commit: string | null;
6
+ isHead: boolean;
7
+ published: boolean;
8
+ branch: string;
9
+ upstream: string | null;
10
+ remoteHead: string | null;
11
+ newVersion: string | null;
12
+ changedPaths: string[];
13
+ demoInputSha256: string | null;
14
+ worktree: string[];
15
+ staged: string[];
16
+ };
17
+ type ReleaseFacts = {
18
+ localTag: boolean;
19
+ localTagAncestor?: boolean;
20
+ localTagConflict?: boolean;
21
+ remoteBranch: boolean;
22
+ remoteTag: boolean;
23
+ githubRelease: boolean | null;
24
+ npm: boolean | null;
25
+ homebrew: boolean | null;
26
+ smoke: 'success' | 'pending' | 'failed' | null;
27
+ post: PostReleaseFacts;
28
+ };
29
+ type PostConfirmation = {
30
+ version: string;
31
+ commit: string;
32
+ branch: string;
33
+ upstream: string | null;
34
+ remoteHead: string | null;
35
+ newVersion: string | null;
36
+ changedPaths: string[];
37
+ demoInputSha256: string | null;
38
+ worktree: string[];
39
+ staged: string[];
40
+ sha256: string;
41
+ };
42
+
43
+ function byteSort(values: readonly string[]): string[] {
44
+ return [...values].sort((left, right) => Buffer.from(left).compare(Buffer.from(right)));
45
+ }
3
46
 
4
47
  function deriveReleasePhase(facts: ReleaseFacts): ReleasePhase {
5
48
  if (!facts.localTag && !facts.localTagAncestor) return 'unprepared';
49
+ if (facts.post.commit) return facts.post.published ? 'complete' : 'post-prepared';
6
50
  if (!facts.remoteBranch && !facts.remoteTag) return 'prepared';
7
51
  if (!facts.remoteBranch || !facts.remoteTag) return 'partially-published';
8
52
  if (facts.githubRelease !== true || facts.npm !== true || facts.homebrew !== true) return 'published';
9
- if (facts.smoke !== 'success' || !facts.postCommit) return 'post-pending';
10
- return 'complete';
53
+ return 'post-pending';
11
54
  }
12
55
 
13
- function releaseSnapshot(version: string, facts: ReleaseFacts) {
14
- return { version, tag: `v${version.replace(/^v/, '')}`, phase: deriveReleasePhase(facts), facts };
56
+ function createPostConfirmation(version: string, post: PostReleaseFacts): PostConfirmation | null {
57
+ if (!post.commit || !post.isHead || post.worktree.length || post.staged.length) return null;
58
+ const canonical = {
59
+ version,
60
+ commit: post.commit,
61
+ branch: post.branch,
62
+ upstream: post.upstream,
63
+ remoteHead: post.remoteHead,
64
+ newVersion: post.newVersion,
65
+ changedPaths: byteSort(post.changedPaths),
66
+ demoInputSha256: post.demoInputSha256,
67
+ worktree: byteSort(post.worktree),
68
+ staged: byteSort(post.staged)
69
+ };
70
+ const sha256 = `sha256:${crypto.createHash('sha256').update(JSON.stringify(canonical), 'utf8').digest('hex')}`;
71
+ return { ...canonical, sha256 };
15
72
  }
16
73
 
17
- async function runReleaseAction(input: { version: string; action: 'inspect' | 'prepare' | 'publish' | 'post'; inspect: () => Promise<ReleaseFacts>; prepare?: () => Promise<void>; publish?: () => Promise<void>; post?: () => Promise<void> }) {
18
- const before = releaseSnapshot(input.version, await input.inspect());
19
- if (input.action === 'inspect') return { status: 'no-op' as const, changed: false, before, snapshot: before, error: null };
20
- if (before.facts.localTagConflict) return { status: 'failed' as const, changed: false, before, snapshot: before, error: { code: 'GIT_TAG_CONFLICT', message: `Tag ${before.tag} is not reachable from HEAD` } };
21
- const allowed = input.action === 'prepare' ? before.phase === 'unprepared'
22
- : input.action === 'publish' ? before.facts.localTag && ['prepared', 'partially-published'].includes(before.phase)
23
- : ['published', 'post-pending'].includes(before.phase);
24
- if (!allowed) return { status: before.phase === 'complete' ? 'no-op' as const : 'failed' as const, changed: false, before, snapshot: before, error: before.phase === 'complete' ? null : { code: 'RELEASE_PHASE_INVALID', message: `Cannot ${input.action} from ${before.phase}` } };
25
- await input[input.action]?.();
26
- const snapshot = releaseSnapshot(input.version, await input.inspect());
27
- const progressed = snapshot.phase !== before.phase;
28
- return { status: progressed ? 'applied' as const : 'blocked' as const, changed: progressed, before, snapshot, error: progressed ? null : { code: 'RELEASE_PROGRESS_PENDING', message: `${input.action} has not reached the next observable phase` } };
74
+ function releaseSnapshot(version: string, facts: ReleaseFacts) {
75
+ const snapshot = { version, tag: `v${version.replace(/^v/, '')}`, phase: deriveReleasePhase(facts), facts };
76
+ const postConfirmation = createPostConfirmation(version, facts.post);
77
+ return postConfirmation ? { ...snapshot, postConfirmation } : snapshot;
29
78
  }
30
79
 
31
- export { deriveReleasePhase, releaseSnapshot, runReleaseAction };
32
- export type { ReleaseFacts, ReleasePhase };
80
+ export { createPostConfirmation, deriveReleasePhase, releaseSnapshot };
81
+ export type { PostConfirmation, PostReleaseFacts, ReleaseFacts, ReleasePhase };