@fitlab-ai/agent-infra 0.11.2 → 0.11.4

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 (162) hide show
  1. package/README.md +17 -8
  2. package/README.zh-CN.md +17 -8
  3. package/dist/bin/internal-cli.js +7 -2
  4. package/dist/lib/agent-clients/adapter.js +3 -0
  5. package/dist/lib/agent-clients/adapters/codex-lifecycle/recovery.js +234 -0
  6. package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +8 -35
  7. package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +1 -34
  8. package/dist/lib/agent-clients/adapters/codex.js +10 -0
  9. package/dist/lib/internal/cli-route-inventory.js +1 -1
  10. package/dist/lib/internal/manual-validation.js +22 -27
  11. package/dist/lib/internal/sandbox-control.js +1 -43
  12. package/dist/lib/internal/task-artifact.js +1 -1
  13. package/dist/lib/internal/task-finalization.js +41 -1
  14. package/dist/lib/internal/task-ledger.js +13 -5
  15. package/dist/lib/internal/task-lifecycle.js +1 -1
  16. package/dist/lib/internal/task-operation-registry.js +7 -2
  17. package/dist/lib/platform/completion-backfill.js +63 -17
  18. package/dist/lib/platform/issue-comments.js +2 -31
  19. package/dist/lib/platform/pr-summary.js +7 -2
  20. package/dist/lib/sandbox/control/client.js +3 -44
  21. package/dist/lib/sandbox/control/executor.js +14 -79
  22. package/dist/lib/sandbox/control/protocol.js +5 -64
  23. package/dist/lib/sandbox/control/server.js +49 -343
  24. package/dist/lib/sandbox/control/state.js +1 -7
  25. package/dist/lib/sandbox/control/task-view.js +1 -2
  26. package/dist/lib/sandbox/task-cleanup.js +13 -20
  27. package/dist/lib/task/artifact-command.js +11 -4
  28. package/dist/lib/task/artifact-lifecycle.js +217 -85
  29. package/dist/lib/task/artifact-operations.js +1 -26
  30. package/dist/lib/task/artifact-receipts.js +4 -1
  31. package/dist/lib/task/artifact-schema.js +1 -0
  32. package/dist/lib/task/artifact-selection.js +25 -0
  33. package/dist/lib/task/capabilities.js +158 -39
  34. package/dist/lib/task/commands/status.js +9 -2
  35. package/dist/lib/task/control-authority.js +37 -38
  36. package/dist/lib/task/control-recovery.js +3 -42
  37. package/dist/lib/task/decision-intents.js +12 -0
  38. package/dist/lib/task/delegation-receipts.js +2 -2
  39. package/dist/lib/task/delivery.js +1 -43
  40. package/dist/lib/task/events.js +80 -64
  41. package/dist/lib/task/finalization-artifacts.js +1 -3
  42. package/dist/lib/task/finalization-state.js +1 -1
  43. package/dist/lib/task/finalization.js +319 -234
  44. package/dist/lib/task/ledger-intents.js +157 -15
  45. package/dist/lib/task/lifecycle-path.js +75 -0
  46. package/dist/lib/task/lifecycle.js +11 -1
  47. package/dist/lib/task/local-artifact-finalization.js +1 -20
  48. package/dist/lib/task/manual-validation-receipt.js +8 -3
  49. package/dist/lib/task/orchestration.js +29 -13
  50. package/dist/lib/task/review-finalization.js +3 -16
  51. package/dist/lib/task/rework-intent.js +70 -4
  52. package/dist/lib/task/verification-engine.js +20 -30
  53. package/dist/lib/task/verification.js +1 -0
  54. package/dist/lib/task/workflow-warning-intents.js +21 -6
  55. package/dist/lib/task/workspace-snapshot.js +7 -2
  56. package/dist/lifecycle-build-manifest.json +3 -3
  57. package/lib/agent-clients/adapter.ts +46 -0
  58. package/lib/agent-clients/adapters/codex-lifecycle/recovery.ts +297 -0
  59. package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +13 -33
  60. package/lib/agent-clients/adapters/codex-lifecycle/store.ts +1 -44
  61. package/lib/agent-clients/adapters/codex.ts +10 -0
  62. package/lib/internal/cli-route-inventory.ts +1 -1
  63. package/lib/internal/manual-validation.ts +22 -26
  64. package/lib/internal/sandbox-control.ts +0 -42
  65. package/lib/internal/task-artifact.ts +1 -1
  66. package/lib/internal/task-finalization.ts +40 -1
  67. package/lib/internal/task-ledger.ts +12 -5
  68. package/lib/internal/task-lifecycle.ts +2 -2
  69. package/lib/internal/task-operation-registry.ts +8 -4
  70. package/lib/platform/completion-backfill.ts +78 -16
  71. package/lib/platform/issue-comments.ts +1 -35
  72. package/lib/platform/pr-summary.ts +10 -2
  73. package/lib/sandbox/control/client.ts +5 -68
  74. package/lib/sandbox/control/executor.ts +14 -81
  75. package/lib/sandbox/control/protocol.ts +7 -83
  76. package/lib/sandbox/control/server.ts +47 -362
  77. package/lib/sandbox/control/state.ts +1 -9
  78. package/lib/sandbox/control/task-view.ts +1 -2
  79. package/lib/sandbox/task-cleanup.ts +12 -20
  80. package/lib/task/artifact-command.ts +14 -4
  81. package/lib/task/artifact-lifecycle.ts +236 -85
  82. package/lib/task/artifact-operations.ts +1 -26
  83. package/lib/task/artifact-receipts.ts +4 -1
  84. package/lib/task/artifact-schema.ts +1 -0
  85. package/lib/task/artifact-selection.ts +53 -0
  86. package/lib/task/capabilities.ts +154 -40
  87. package/lib/task/commands/status.ts +11 -2
  88. package/lib/task/control-authority.ts +41 -48
  89. package/lib/task/control-recovery.ts +3 -43
  90. package/lib/task/decision-intents.ts +9 -0
  91. package/lib/task/delegation-receipts.ts +2 -2
  92. package/lib/task/delivery.ts +1 -40
  93. package/lib/task/events.ts +82 -64
  94. package/lib/task/finalization-artifacts.ts +1 -3
  95. package/lib/task/finalization-state.ts +1 -1
  96. package/lib/task/finalization.ts +310 -216
  97. package/lib/task/ledger-intents.ts +155 -15
  98. package/lib/task/lifecycle-path.ts +98 -0
  99. package/lib/task/lifecycle.ts +15 -2
  100. package/lib/task/local-artifact-finalization.ts +2 -25
  101. package/lib/task/manual-validation-receipt.ts +8 -2
  102. package/lib/task/orchestration.ts +56 -27
  103. package/lib/task/review-finalization.ts +3 -16
  104. package/lib/task/rework-intent.ts +75 -5
  105. package/lib/task/verification-engine.ts +19 -30
  106. package/lib/task/verification.ts +2 -1
  107. package/lib/task/workflow-warning-intents.ts +18 -6
  108. package/lib/task/workspace-snapshot.ts +3 -2
  109. package/package.json +1 -1
  110. package/templates/.agents/rules/lifecycle-orchestration.en.md +19 -5
  111. package/templates/.agents/rules/lifecycle-orchestration.zh-CN.md +19 -5
  112. package/templates/.agents/rules/review-handshake.en.md +4 -4
  113. package/templates/.agents/rules/review-handshake.zh-CN.md +4 -4
  114. package/templates/.agents/skills/analyze-task/SKILL.en.md +11 -4
  115. package/templates/.agents/skills/analyze-task/SKILL.zh-CN.md +11 -4
  116. package/templates/.agents/skills/code-task/SKILL.en.md +14 -8
  117. package/templates/.agents/skills/code-task/SKILL.zh-CN.md +18 -13
  118. package/templates/.agents/skills/code-task/reference/code-rules.en.md +2 -2
  119. package/templates/.agents/skills/code-task/reference/code-rules.zh-CN.md +2 -2
  120. package/templates/.agents/skills/code-task/reference/dual-mode.en.md +4 -4
  121. package/templates/.agents/skills/code-task/reference/dual-mode.zh-CN.md +4 -4
  122. package/templates/.agents/skills/code-task/reference/report-template.en.md +1 -1
  123. package/templates/.agents/skills/code-task/reference/report-template.zh-CN.md +1 -1
  124. package/templates/.agents/skills/complete-manual-validation/SKILL.en.md +2 -2
  125. package/templates/.agents/skills/complete-manual-validation/SKILL.zh-CN.md +2 -2
  126. package/templates/.agents/skills/complete-task/SKILL.en.md +7 -8
  127. package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +7 -8
  128. package/templates/.agents/skills/plan-task/SKILL.en.md +13 -10
  129. package/templates/.agents/skills/plan-task/SKILL.zh-CN.md +13 -10
  130. package/templates/.agents/skills/review-analysis/SKILL.en.md +5 -1
  131. package/templates/.agents/skills/review-analysis/SKILL.zh-CN.md +5 -1
  132. package/templates/.agents/skills/review-code/SKILL.en.md +5 -1
  133. package/templates/.agents/skills/review-code/SKILL.zh-CN.md +5 -1
  134. package/templates/.agents/skills/review-plan/SKILL.en.md +5 -1
  135. package/templates/.agents/skills/review-plan/SKILL.zh-CN.md +5 -1
  136. package/templates/.agents/skills/run-manual-validation/SKILL.en.md +2 -2
  137. package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +2 -2
  138. package/templates/.agents/skills/run-task/SKILL.en.md +9 -8
  139. package/templates/.agents/skills/run-task/SKILL.zh-CN.md +9 -8
  140. package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +18 -2
  141. package/templates/.agents/templates/task.en.md +2 -2
  142. package/templates/.agents/templates/task.zh-CN.md +2 -2
  143. package/templates/.agents/workflows/bug-fix.en.yaml +11 -6
  144. package/templates/.agents/workflows/bug-fix.zh-CN.yaml +11 -6
  145. package/templates/.agents/workflows/feature-development.en.yaml +11 -6
  146. package/templates/.agents/workflows/feature-development.zh-CN.yaml +11 -6
  147. package/templates/.agents/workflows/refactoring.en.yaml +11 -6
  148. package/templates/.agents/workflows/refactoring.zh-CN.yaml +11 -6
  149. package/dist/lib/sandbox/control/finalization-response.js +0 -35
  150. package/dist/lib/sandbox/control/task-workflow.js +0 -74
  151. package/dist/lib/sandbox/control/workflow-executor.js +0 -142
  152. package/dist/lib/task/lifecycle-recovery.js +0 -549
  153. package/dist/lib/task/recovery-warning.js +0 -19
  154. package/dist/lib/task/workflow-command.js +0 -21
  155. package/dist/lib/task/workflow-dispatch.js +0 -213
  156. package/lib/sandbox/control/finalization-response.ts +0 -37
  157. package/lib/sandbox/control/task-workflow.ts +0 -95
  158. package/lib/sandbox/control/workflow-executor.ts +0 -156
  159. package/lib/task/lifecycle-recovery.ts +0 -691
  160. package/lib/task/recovery-warning.ts +0 -21
  161. package/lib/task/workflow-command.ts +0 -22
  162. package/lib/task/workflow-dispatch.ts +0 -214
@@ -1,213 +0,0 @@
1
- import fs from 'node:fs';
2
- import { reconcileTaskInvalidation } from './invalidation-command.js';
3
- import { applyLedgerIntent } from './ledger-intents.js';
4
- import { isReviewStage, parseLedgerDocument, summarizeLedgerStage, validateLedgerRows } from './ledger.js';
5
- import { resolveTaskRef } from './resolve-ref.js';
6
- import { TaskExecutionLockError, withTaskExecutionLock } from './task-execution-lock.js';
7
- import { applyWorkflowWarningIntent } from './workflow-warning-intents.js';
8
- function failed(code, message) {
9
- return { status: 'failed', changed: false, error: { code, message } };
10
- }
11
- function isFailure(value) {
12
- return Boolean(value) && typeof value === 'object' && value.status === 'failed';
13
- }
14
- function options(args, allowed) {
15
- const values = {};
16
- for (let index = 2; index < args.length; index += 1) {
17
- const flag = args[index];
18
- if (flag === '--dry-run') {
19
- if (!Object.hasOwn(allowed, flag) || values[flag] !== undefined)
20
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', `invalid option '${flag}'`);
21
- values[flag] = true;
22
- continue;
23
- }
24
- const key = allowed[flag];
25
- if (!key || values[flag] !== undefined)
26
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', `invalid option '${flag}'`);
27
- const value = args[++index];
28
- if (value === undefined || value.startsWith('--'))
29
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', `option '${flag}' requires a value`);
30
- if (flag === '--needs-implementation' && value !== 'true' && value !== 'false') {
31
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', "option '--needs-implementation' must be true or false");
32
- }
33
- values[flag] = value;
34
- }
35
- return values;
36
- }
37
- function value(values, flag) {
38
- const candidate = values[flag];
39
- return typeof candidate === 'string' ? candidate : undefined;
40
- }
41
- function required(values, flags) {
42
- const missing = flags.find((flag) => value(values, flag) === undefined);
43
- return missing ? failed('TASK_WORKFLOW_PAYLOAD_INVALID', `option '${missing}' is required`) : null;
44
- }
45
- function resultForLock(error) {
46
- if (error instanceof TaskExecutionLockError)
47
- return failed(error.code, error.message);
48
- throw error;
49
- }
50
- function ledgerIntent(operation, args) {
51
- const [taskRef, kind] = args;
52
- const mappings = {
53
- 'ledger-finding-response': {
54
- kind: 'finding-respond', required: ['--id', '--round', '--status', '--evidence'],
55
- flags: { '--id': 'id', '--round': 'round', '--status': 'status', '--evidence': 'evidence', '--dry-run': 'dryRun' }
56
- },
57
- 'ledger-finding-review': {
58
- kind: 'finding-review', required: ['--id', '--status', '--evidence'],
59
- flags: { '--id': 'id', '--status': 'status', '--evidence': 'evidence', '--needs-implementation': 'needsImplementation', '--dry-run': 'dryRun' }
60
- },
61
- 'ledger-finding-upsert': {
62
- kind: 'finding-upsert', required: ['--stage', '--review-artifact', '--ordinal', '--severity', '--evidence'],
63
- flags: { '--stage': 'stage', '--review-artifact': 'reviewArtifact', '--ordinal': 'ordinal', '--severity': 'severity', '--evidence': 'evidence', '--dry-run': 'dryRun' }
64
- },
65
- 'decision-next-id': { kind: 'decision-next-id', required: [], flags: {} },
66
- 'decision-upsert': {
67
- kind: 'decision-upsert', required: ['--id', '--stage', '--artifact'],
68
- flags: { '--id': 'id', '--stage': 'stage', '--artifact': 'artifact', '--needs-implementation': 'needsImplementation', '--dry-run': 'dryRun' }
69
- }
70
- };
71
- const mapping = mappings[operation];
72
- if (!mapping || !taskRef || kind === undefined)
73
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', 'task workflow ledger request is invalid');
74
- const values = options(args, mapping.flags);
75
- if (isFailure(values))
76
- return values;
77
- const missing = required(values, mapping.required);
78
- if (missing)
79
- return missing;
80
- const dryRun = values['--dry-run'] === true;
81
- if (mapping.kind === 'decision-next-id')
82
- return { kind: mapping.kind, taskRef };
83
- if (mapping.kind === 'finding-respond')
84
- return {
85
- kind: mapping.kind, taskRef, id: value(values, '--id'), round: Number(value(values, '--round')),
86
- status: value(values, '--status'), evidence: value(values, '--evidence'), ...(dryRun ? { dryRun } : {})
87
- };
88
- if (mapping.kind === 'finding-review')
89
- return {
90
- kind: mapping.kind, taskRef, id: value(values, '--id'), status: value(values, '--status'),
91
- evidence: value(values, '--evidence'), ...(value(values, '--needs-implementation') === 'true' ? { needsImplementation: true } : {}),
92
- ...(dryRun ? { dryRun } : {})
93
- };
94
- if (mapping.kind === 'finding-upsert')
95
- return {
96
- kind: mapping.kind, taskRef, stage: value(values, '--stage'), reviewArtifact: value(values, '--review-artifact'),
97
- ordinal: Number(value(values, '--ordinal')), severity: value(values, '--severity'), evidence: value(values, '--evidence'),
98
- ...(dryRun ? { dryRun } : {})
99
- };
100
- return {
101
- kind: mapping.kind, taskRef, id: value(values, '--id'), stage: value(values, '--stage'),
102
- artifact: value(values, '--artifact'), ...(value(values, '--needs-implementation') === 'true' ? { needsImplementation: true } : {}),
103
- ...(dryRun ? { dryRun } : {})
104
- };
105
- }
106
- function warningIntent(args) {
107
- const [taskRef, kind] = args;
108
- if (!taskRef || !['add', 'list', 'set-status'].includes(kind ?? '')) {
109
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', 'task workflow warning request is invalid');
110
- }
111
- if (kind === 'list') {
112
- const values = options(args, { '--status': 'status' });
113
- if (isFailure(values))
114
- return values;
115
- return { kind, taskRef, ...(value(values, '--status') ? { status: value(values, '--status') } : {}) };
116
- }
117
- if (kind === 'set-status') {
118
- const values = options(args, { '--id': 'id', '--status': 'status', '--resolution': 'resolution', '--dry-run': 'dryRun' });
119
- if (isFailure(values))
120
- return values;
121
- const missing = required(values, ['--id', '--status', '--resolution']);
122
- if (missing)
123
- return missing;
124
- return {
125
- kind, taskRef, id: value(values, '--id'), status: value(values, '--status'),
126
- resolution: value(values, '--resolution'), ...(values['--dry-run'] === true ? { dryRun: true } : {})
127
- };
128
- }
129
- const values = options(args, {
130
- '--step': 'step', '--severity': 'severity', '--code': 'code', '--target': 'target',
131
- '--message': 'message', '--action': 'action', '--dry-run': 'dryRun'
132
- });
133
- if (isFailure(values))
134
- return values;
135
- const missing = required(values, ['--step', '--severity', '--code', '--target', '--message', '--action']);
136
- if (missing)
137
- return missing;
138
- return {
139
- kind: 'add', taskRef, step: value(values, '--step'), severity: value(values, '--severity'),
140
- code: value(values, '--code'), target: value(values, '--target'), message: value(values, '--message'),
141
- action: value(values, '--action'), ...(values['--dry-run'] === true ? { dryRun: true } : {})
142
- };
143
- }
144
- function stageStatus(repoRoot, args) {
145
- const [taskRef, kind] = args;
146
- if (!taskRef || kind !== 'stage-status')
147
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', 'task workflow ledger request is invalid');
148
- const values = options(args, { '--stage': 'stage' });
149
- if (isFailure(values))
150
- return values;
151
- const stage = value(values, '--stage');
152
- if (!stage || !isReviewStage(stage))
153
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', 'stage-status requires a valid review stage');
154
- const resolved = resolveTaskRef(taskRef, { repoRoot });
155
- if (!resolved.ok)
156
- return failed(resolved.code, resolved.message);
157
- try {
158
- const ledger = parseLedgerDocument(fs.readFileSync(resolved.taskMdPath, 'utf8'));
159
- if (!ledger.present)
160
- return failed('LEDGER_SECTION_MISSING', 'review disagreement ledger section is missing');
161
- const invalid = validateLedgerRows(ledger.rows);
162
- if (invalid)
163
- return failed(invalid.code, invalid.message);
164
- return { status: 'ready', changed: false, taskId: resolved.taskId, stageStatus: summarizeLedgerStage(ledger.rows, stage), error: null };
165
- }
166
- catch (error) {
167
- return failed('LEDGER_DOCUMENT_INVALID', error instanceof Error ? error.message : String(error));
168
- }
169
- }
170
- /**
171
- * The caller has already selected and authorized the execution boundary.
172
- * This function deliberately invokes task domains in that process: starting a
173
- * second CLI process would discard the broker binding and could misclassify a
174
- * sandbox process with cleared environment variables as direct-host.
175
- */
176
- export function dispatchWorkflowCommand(repoRoot, operation, args) {
177
- const taskRef = args[0];
178
- if (!taskRef)
179
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', 'task ref is required');
180
- try {
181
- if (operation === 'invalidation-reconcile') {
182
- const values = options(args, { '--max-targets': 'maxTargets', '--dry-run': 'dryRun' });
183
- if (isFailure(values))
184
- return values;
185
- const maxTargets = value(values, '--max-targets');
186
- if (maxTargets !== undefined && (!Number.isSafeInteger(Number(maxTargets)) || Number(maxTargets) < 1)) {
187
- return failed('TASK_WORKFLOW_PAYLOAD_INVALID', '--max-targets must be a positive integer');
188
- }
189
- return withTaskExecutionLock(repoRoot, taskRef, 'task-invalidation.reconcile', () => reconcileTaskInvalidation(taskRef, {
190
- repoRoot, ...(maxTargets === undefined ? {} : { maxTargets: Number(maxTargets) }),
191
- ...(values['--dry-run'] === true ? { dryRun: true } : {})
192
- }));
193
- }
194
- if (operation === 'ledger-stage-status')
195
- return stageStatus(repoRoot, args);
196
- if (operation === 'warning-add' || operation === 'warning-list' || operation === 'warning-set-status') {
197
- const intent = warningIntent(args);
198
- if (isFailure(intent))
199
- return intent;
200
- if (intent.kind === 'list')
201
- return applyWorkflowWarningIntent(intent, { repoRoot });
202
- return withTaskExecutionLock(repoRoot, taskRef, `task-warning.${intent.kind}`, () => applyWorkflowWarningIntent(intent, { repoRoot }));
203
- }
204
- const intent = ledgerIntent(operation, args);
205
- if (isFailure(intent))
206
- return intent;
207
- return withTaskExecutionLock(repoRoot, taskRef, `task-ledger.${intent.kind}`, () => applyLedgerIntent(intent, { repoRoot }));
208
- }
209
- catch (error) {
210
- return resultForLock(error);
211
- }
212
- }
213
- //# sourceMappingURL=workflow-dispatch.js.map
@@ -1,37 +0,0 @@
1
- import type { TaskFinalizationReceipt } from '../../task/finalization.ts';
2
- import type { SandboxControlResponse } from './protocol.ts';
3
-
4
- export function finalizationTerminalResponse(taskId: string, requestId: string, receipt: TaskFinalizationReceipt): SandboxControlResponse {
5
- const pendingSteps = [
6
- receipt.taskComment === 'pending' ? 'task-comment' : null,
7
- receipt.verification === 'pending' ? 'verification' : null,
8
- receipt.summary === 'pending' ? 'summary' : null,
9
- receipt.postSummaryVerification === 'pending' ? 'post-summary-verification' : null
10
- ].filter((step): step is string => step !== null);
11
- const completedSteps = [
12
- 'lifecycle', receipt.taskComment === 'pending' ? null : 'task-comment',
13
- receipt.verification === 'pending' ? null : 'verification', receipt.summary === 'pending' ? null : 'summary',
14
- receipt.postSummaryVerification === 'pending' ? null : 'post-summary-verification'
15
- ]
16
- .filter((step): step is string => step !== null);
17
- const warnings = receipt.warnings
18
- .filter((warning) => warning.status === 'open')
19
- .map(({ status: _status, resolvedAt: _resolvedAt, ...warning }) => warning);
20
- const result = {
21
- status: 'completed', changed: false, taskId,
22
- lifecycle: { status: 'no-op', changed: false, error: null },
23
- taskComment: receipt.taskComment === 'pending' ? null : { status: 'no-op', changed: false, error: null },
24
- verification: receipt.verification === 'pending' ? null : { status: 'no-op', changed: false, error: null },
25
- summary: receipt.summary === 'pending' ? null : { status: 'no-op', changed: false, error: null },
26
- postSummaryVerification: receipt.postSummaryVerification === 'pending' ? null : { status: 'no-op', changed: false, error: null },
27
- completedSteps, pendingSteps,
28
- result: pendingSteps.length > 0 || receipt.warningProjection === 'pending' || warnings.length > 0
29
- ? 'completed_with_warnings' : 'completed',
30
- warnings, error: null
31
- };
32
- return {
33
- version: 2, id: requestId, phase: 'completed', exitCode: 0,
34
- stdout: `${JSON.stringify({ version: 1, status: 'completed', changed: false, accepted: true, result, error: null })}\n`,
35
- stderr: '', error: null
36
- };
37
- }
@@ -1,95 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
-
5
- import { readStableFile, SecureFileError, writeAtomicFile } from '../../task/secure-fs.ts';
6
-
7
- import { TASK_WORKFLOW_COMMANDS, TASK_WORKFLOW_OPERATIONS, type TaskWorkflowOperation, type WorkflowCommand } from '../../task/workflow-command.ts';
8
-
9
- export type TaskWorkflowRequest = Readonly<{
10
- version: 1;
11
- id: string;
12
- taskId: string;
13
- generation: string;
14
- operation: TaskWorkflowOperation;
15
- args: readonly string[];
16
- }>;
17
-
18
- export function validateTaskWorkflowRequest(value: unknown): TaskWorkflowRequest {
19
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('TASK_WORKFLOW_REQUEST_INVALID');
20
- const request = value as TaskWorkflowRequest;
21
- if (Object.keys(request).sort().join(',') !== 'args,generation,id,operation,taskId,version'
22
- || request.version !== 1 || typeof request.id !== 'string' || !/^[a-f0-9-]{16,64}$/u.test(request.id)
23
- || typeof request.taskId !== 'string' || !/^TASK-\d{8}-\d{6}$/u.test(request.taskId)
24
- || typeof request.generation !== 'string' || !request.generation
25
- || !Object.hasOwn(TASK_WORKFLOW_COMMANDS, request.operation)
26
- || !Array.isArray(request.args) || request.args.length < 2 || request.args.length > 128
27
- || !request.args.every((arg) => typeof arg === 'string' && !/[\r\n]/u.test(arg))
28
- || request.args[0] !== request.taskId) throw new Error('TASK_WORKFLOW_REQUEST_INVALID');
29
- const [, selector] = TASK_WORKFLOW_COMMANDS[request.operation];
30
- if (selector !== null && request.args[1] !== selector) throw new Error('TASK_WORKFLOW_REQUEST_INVALID');
31
- return request;
32
- }
33
-
34
- /** Preserve argv verbatim; the domain command owns option parsing and validation. */
35
- export function createTaskWorkflowRequest(
36
- command: WorkflowCommand | undefined,
37
- args: readonly string[],
38
- taskId: string,
39
- generation: string
40
- ): TaskWorkflowRequest {
41
- const operation = TASK_WORKFLOW_OPERATIONS.find((key) => {
42
- const [name, selector] = TASK_WORKFLOW_COMMANDS[key];
43
- return name === command && (selector === null || selector === args[1]);
44
- });
45
- if (!operation) throw new Error('TASK_WORKFLOW_OPERATION_UNSUPPORTED');
46
- return validateTaskWorkflowRequest({ version: 1, id: randomUUID(), taskId, generation, operation, args: [...args] });
47
- }
48
-
49
- export function canonicalArtifactName(value: string): boolean {
50
- return /^(?:analysis|plan|code|review-analysis|review-plan|review-code)(?:-r[1-9]\d*)?\.md$/u.test(value)
51
- && path.basename(value) === value;
52
- }
53
-
54
- function assertTaskArtifactDirectory(directory: string): string {
55
- const resolved = path.resolve(directory);
56
- let stat: fs.Stats;
57
- try {
58
- stat = fs.lstatSync(resolved);
59
- } catch {
60
- throw new SecureFileError('TASK_ARTIFACT_WRITE_DENIED', 'task directory is unavailable');
61
- }
62
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
63
- throw new SecureFileError('TASK_ARTIFACT_WRITE_DENIED', 'task directory must be a real directory');
64
- }
65
- return resolved;
66
- }
67
-
68
- export async function readTaskArtifact(
69
- taskDir: string,
70
- input: Readonly<{
71
- artifact: string;
72
- expectedSha256?: string;
73
- }>
74
- ): Promise<Readonly<{ artifact: string; bytes: Buffer; sha256: string }>> {
75
- if (!canonicalArtifactName(input.artifact)) throw new SecureFileError('TASK_ARTIFACT_WRITE_DENIED', 'artifact must be a canonical top-level basename');
76
- const root = assertTaskArtifactDirectory(taskDir);
77
- const candidate = path.join(root, input.artifact);
78
- if (path.dirname(candidate) !== root) throw new SecureFileError('TASK_ARTIFACT_WRITE_DENIED', 'artifact escapes task directory');
79
- const stable = await readStableFile(candidate, {
80
- maxBytes: 1024 * 1024,
81
- ...(input.expectedSha256 ? { expectedSha256: input.expectedSha256 } : {})
82
- });
83
- return { artifact: input.artifact, bytes: stable.bytes, sha256: stable.sha256 };
84
- }
85
-
86
- export async function writeTaskArtifact(
87
- taskDir: string,
88
- artifact: Readonly<{ artifact: string; bytes: Buffer; expectedSha256?: string }>
89
- ): Promise<void> {
90
- if (!canonicalArtifactName(artifact.artifact)) throw new SecureFileError('TASK_ARTIFACT_WRITE_DENIED', 'artifact must be a canonical top-level basename');
91
- const root = assertTaskArtifactDirectory(taskDir);
92
- const target = path.join(root, artifact.artifact);
93
- if (path.dirname(target) !== root) throw new SecureFileError('TASK_ARTIFACT_WRITE_DENIED', 'artifact escapes task directory');
94
- await writeAtomicFile(target, artifact.bytes, 0o600, artifact.expectedSha256);
95
- }
@@ -1,156 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
-
5
- import { TASK_WORKFLOW_COMMANDS } from '../../task/workflow-command.ts';
6
-
7
- import { parseArtifactCommand, executeArtifactCommand } from '../../task/artifact-command.ts';
8
- import { parseReviewCommand } from '../../task/review-command.ts';
9
- import { prepareLocalArtifact, preflightLocalArtifact, commitLocalArtifactProvenance } from '../../task/local-artifact-finalization.ts';
10
- import {
11
- prepareReviewSummaryCandidate,
12
- preflightReviewSummary
13
- } from '../../task/review-finalization.ts';
14
- import { withTaskExecutionLock } from '../../task/task-execution-lock.ts';
15
- import { dispatchWorkflowCommand } from '../../task/workflow-dispatch.ts';
16
- import { assertSandboxTaskSource } from '../workspace-view.ts';
17
- import { appendDiagnosticAudit } from './audit.ts';
18
- import {
19
- readTaskArtifact, type TaskWorkflowRequest
20
- } from './task-workflow.ts';
21
- import type { SandboxControlManifest } from './protocol.ts';
22
- import type { SandboxControlExecutionResult } from './executor.ts';
23
- import type { LifecycleRecoveryAttestationV1 } from '../../task/control-authority.ts';
24
- import { applyTaskEvent } from '../../task/events.ts';
25
- import { parseTaskEventRequest } from '../../internal/task-event.ts';
26
-
27
- export type TaskWorkflowFaultWindow =
28
- | 'before-call'
29
- | 'before-domain-write'
30
- | 'after-atomic-rename'
31
- | 'before-result-return';
32
-
33
- export type TaskWorkflowExecutionOptions = Readonly<{
34
- /** Deterministic test seam; production callers leave this unset. */
35
- faultWindow?: TaskWorkflowFaultWindow;
36
- }>;
37
-
38
- function executionResult(result: Record<string, unknown>): SandboxControlExecutionResult {
39
- return { exitCode: result.status === 'failed' || result.status === 'refused' ? 1 : 0, stdout: `${JSON.stringify(result)}\n`, stderr: '' };
40
- }
41
-
42
- function replaceCurrentArtifactAtomically(file: string, content: string): void {
43
- const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomUUID()}.tmp`);
44
- try {
45
- fs.writeFileSync(temporary, content, { encoding: 'utf8', flag: 'wx' });
46
- fs.renameSync(temporary, file);
47
- } finally {
48
- try { fs.unlinkSync(temporary); } catch (error) {
49
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
50
- }
51
- }
52
- }
53
-
54
- /** The broker already authorized this host executor; domain operations own validation. */
55
- export async function executeTaskWorkflow(
56
- manifest: SandboxControlManifest,
57
- request: TaskWorkflowRequest,
58
- lifecycleRecoveryAttestation: LifecycleRecoveryAttestationV1 | null = null,
59
- options: TaskWorkflowExecutionOptions = {}
60
- ): Promise<SandboxControlExecutionResult> {
61
- let publicationCommitted = false;
62
- let faultTriggered = false;
63
- const fault = (window: TaskWorkflowFaultWindow): void => {
64
- if (faultTriggered || options.faultWindow !== window) return;
65
- faultTriggered = true;
66
- throw new Error(`TASK_WORKFLOW_FAULT_INJECTED:${window}`);
67
- };
68
- const response = (result: Record<string, unknown>): SandboxControlExecutionResult => {
69
- fault('before-result-return');
70
- return executionResult(result);
71
- };
72
- try {
73
- fault('before-call');
74
- const taskDir = assertSandboxTaskSource(manifest.repoRoot, request.taskId);
75
- const [command] = TASK_WORKFLOW_COMMANDS[request.operation];
76
- if (request.operation === 'event') {
77
- const eventRequest = parseTaskEventRequest(request.args);
78
- const boundEventRequest = lifecycleRecoveryAttestation && eventRequest.requestId === undefined
79
- ? { ...eventRequest, requestId: lifecycleRecoveryAttestation.lifecycleRequestId }
80
- : eventRequest;
81
- fault('before-domain-write');
82
- const result = applyTaskEvent(boundEventRequest, {
83
- repoRoot: manifest.repoRoot,
84
- lifecycleRecoveryAttestation,
85
- deferLifecycleRecoveryConsumption: true
86
- });
87
- publicationCommitted = result.changed;
88
- fault('after-atomic-rename');
89
- return response(result);
90
- }
91
- if (command !== 'task-artifact' && command !== 'task-review') {
92
- // The broker owns this short-lived executor; no global service or worker
93
- // credential participates in the command's authority or recovery path.
94
- fault('before-domain-write');
95
- const result = dispatchWorkflowCommand(manifest.repoRoot, request.operation, request.args);
96
- publicationCommitted = result.changed === true;
97
- fault('after-atomic-rename');
98
- return response(result);
99
- }
100
- const input = command === 'task-artifact' ? parseArtifactCommand(request.args) : parseReviewCommand(request.args);
101
- if (command === 'task-artifact' && 'operation' in input && input.operation === 'inspect') {
102
- fault('before-domain-write');
103
- const result = executeArtifactCommand(input, { repoRoot: manifest.repoRoot });
104
- publicationCommitted = result.changed === true;
105
- fault('after-atomic-rename');
106
- return response(result);
107
- }
108
- if ('operation' in input && input.operation === 'init') {
109
- fault('before-domain-write');
110
- const result = executeArtifactCommand(input, { repoRoot: manifest.repoRoot, artifactDir: taskDir });
111
- publicationCommitted = result.changed === true;
112
- fault('after-atomic-rename');
113
- return response(result);
114
- }
115
- return await withTaskExecutionLock(manifest.repoRoot, request.taskId, `sandbox-control.${request.operation}`, async () => {
116
- const artifact = await readTaskArtifact(taskDir, { artifact: input.artifact });
117
- const content = artifact.bytes.toString('utf8');
118
- fault('before-domain-write');
119
- let result: Record<string, unknown>;
120
- if ('operation' in input) {
121
- const { family } = input;
122
- if (family !== 'analysis' && family !== 'plan' && family !== 'code') throw new Error('ARTIFACT_IDENTITY_INVALID');
123
- const local = { taskRef: request.taskId, family, artifact: input.artifact, repoRoot: manifest.repoRoot, lockAlreadyHeld: true } as const;
124
- if (input.operation === 'preflight') {
125
- const result = preflightLocalArtifact(local);
126
- return response(result);
127
- }
128
- const prepared = prepareLocalArtifact(local, content);
129
- result = commitLocalArtifactProvenance(prepared);
130
- } else {
131
- if (input.overrideTicket) throw new Error('TASK_WORKFLOW_OVERRIDE_UNSUPPORTED');
132
- const family = `review-${input.stage}` as 'review-analysis' | 'review-plan' | 'review-code';
133
- if (request.operation === 'review-preflight') {
134
- const result = preflightReviewSummary(input, { repoRoot: manifest.repoRoot, lockAlreadyHeld: true });
135
- return response(result);
136
- }
137
- const prepared = prepareReviewSummaryCandidate(input, content, { repoRoot: manifest.repoRoot, lockAlreadyHeld: true });
138
- if (input.dryRun || prepared.result.status === 'planned') return executionResult(prepared.result);
139
- if (prepared.result.status === 'failed') return executionResult(prepared.result);
140
- if (prepared.result.changed) replaceCurrentArtifactAtomically(path.join(taskDir, input.artifact), prepared.content);
141
- result = prepared.result;
142
- }
143
- publicationCommitted ||= result.changed === true;
144
- if (result.status !== 'failed') appendDiagnosticAudit(manifest, 'task-workflow-artifact-finalized', {
145
- requestId: request.id, sandboxTaskId: request.taskId, workflowOperation: request.operation,
146
- artifact: input.artifact, sha256: result.artifactSha256 as string, semanticDigest: result.semanticDigest as string
147
- });
148
- fault('after-atomic-rename');
149
- return response(result);
150
- });
151
- } catch (error) {
152
- const message = error instanceof Error ? error.message : String(error);
153
- const code = (error as { code?: string })?.code ?? /^([A-Z][A-Z0-9_]+)/u.exec(message)?.[1] ?? 'TASK_WORKFLOW_REQUEST_INVALID';
154
- return executionResult({ status: 'failed', changed: publicationCommitted ? null : false, error: { code, message } });
155
- }
156
- }