@fitlab-ai/agent-infra 0.9.8 → 0.9.10

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 (182) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/dist/bin/internal-cli.js +11 -1
  4. package/dist/lib/agent-clients/adapters/codex-lifecycle/app-server.js +58 -21
  5. package/dist/lib/agent-clients/adapters/codex-lifecycle/build-identity.js +25 -11
  6. package/dist/lib/agent-clients/adapters/codex-lifecycle/capability-store.js +173 -10
  7. package/dist/lib/agent-clients/adapters/codex-lifecycle/controller-context.js +127 -0
  8. package/dist/lib/agent-clients/adapters/codex-lifecycle/evidence.js +14 -0
  9. package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +63 -92
  10. package/dist/lib/agent-clients/adapters/codex-sandbox.js +72 -11
  11. package/dist/lib/agent-clients/adapters/index.js +3 -1
  12. package/dist/lib/agent-clients/adapters/traecli.js +66 -0
  13. package/dist/lib/agent-clients/tokens.js +2 -2
  14. package/dist/lib/agent-clients/types.js +2 -1
  15. package/dist/lib/defaults.json +5 -0
  16. package/dist/lib/git/workflow.js +10 -1
  17. package/dist/lib/internal/codex-lifecycle.js +20 -6
  18. package/dist/lib/internal/codex-sandbox-controller.js +9 -15
  19. package/dist/lib/internal/git-workflow.js +5 -7
  20. package/dist/lib/internal/platform-pr.js +20 -7
  21. package/dist/lib/internal/release-workflow.js +2 -1
  22. package/dist/lib/internal/sandbox-control.js +79 -2
  23. package/dist/lib/internal/task-finalization.js +54 -0
  24. package/dist/lib/internal/task-orchestration.js +156 -291
  25. package/dist/lib/{task/commands/validate.js → internal/task-validate.js} +75 -42
  26. package/dist/lib/platform/pr-summary.js +48 -10
  27. package/dist/lib/platform/pull-requests.js +205 -41
  28. package/dist/lib/run/tui.js +5 -2
  29. package/dist/lib/sandbox/commands/rm.js +316 -55
  30. package/dist/lib/sandbox/control/client.js +190 -6
  31. package/dist/lib/sandbox/control/controller-registration.js +275 -0
  32. package/dist/lib/sandbox/control/executor.js +140 -5
  33. package/dist/lib/sandbox/control/lifecycle.js +3 -1
  34. package/dist/lib/sandbox/control/protocol.js +67 -6
  35. package/dist/lib/sandbox/index.js +5 -3
  36. package/dist/lib/sandbox/managed-fs.js +5 -0
  37. package/dist/lib/sandbox/task-resolver.js +50 -6
  38. package/dist/lib/sandbox/workspace-identity.js +27 -0
  39. package/dist/lib/sandbox/worktree-safety.js +215 -2
  40. package/dist/lib/task/codex-orchestration.js +161 -39
  41. package/dist/lib/task/commands/status.js +59 -1
  42. package/dist/lib/task/commit-operation.js +335 -0
  43. package/dist/lib/task/commit-policy.js +18 -0
  44. package/dist/lib/task/delegation-receipts.js +248 -6
  45. package/dist/lib/task/finalization.js +593 -0
  46. package/dist/lib/task/index.js +0 -9
  47. package/dist/lib/task/operation-outcome.js +33 -0
  48. package/dist/lib/task/orchestration.js +187 -761
  49. package/dist/lib/task/short-id.js +59 -1
  50. package/dist/lib/task/task-execution-lock.js +6 -1
  51. package/dist/lib/task/verification-engine.js +110 -60
  52. package/dist/lib/task/verification.js +2 -1
  53. package/dist/lib/task/workflow-warning-intents.js +50 -1
  54. package/dist/lifecycle-build-manifest.json +3 -3
  55. package/lib/agent-clients/adapters/codex-lifecycle/app-server.ts +61 -19
  56. package/lib/agent-clients/adapters/codex-lifecycle/build-identity.ts +37 -10
  57. package/lib/agent-clients/adapters/codex-lifecycle/capability-store.ts +276 -12
  58. package/lib/agent-clients/adapters/codex-lifecycle/controller-context.ts +163 -0
  59. package/lib/agent-clients/adapters/codex-lifecycle/evidence.ts +19 -0
  60. package/lib/agent-clients/adapters/codex-lifecycle/manifest-files.json +9 -1
  61. package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +91 -118
  62. package/lib/agent-clients/adapters/codex-sandbox.ts +89 -14
  63. package/lib/agent-clients/adapters/index.ts +3 -1
  64. package/lib/agent-clients/adapters/traecli.ts +67 -0
  65. package/lib/agent-clients/tokens.ts +2 -2
  66. package/lib/agent-clients/types.ts +2 -1
  67. package/lib/defaults.json +5 -0
  68. package/lib/git/workflow.ts +11 -2
  69. package/lib/internal/codex-lifecycle.ts +19 -6
  70. package/lib/internal/codex-sandbox-controller.ts +9 -14
  71. package/lib/internal/git-workflow.ts +5 -6
  72. package/lib/internal/platform-pr.ts +14 -7
  73. package/lib/internal/release-workflow.ts +2 -1
  74. package/lib/internal/sandbox-control.ts +92 -2
  75. package/lib/internal/task-finalization.ts +68 -0
  76. package/lib/internal/task-orchestration.ts +20 -103
  77. package/lib/{task/commands/validate.ts → internal/task-validate.ts} +75 -40
  78. package/lib/platform/pr-summary.ts +55 -11
  79. package/lib/platform/pull-requests.ts +211 -41
  80. package/lib/run/tui.ts +5 -3
  81. package/lib/sandbox/commands/rm.ts +413 -61
  82. package/lib/sandbox/control/client.ts +255 -6
  83. package/lib/sandbox/control/controller-registration.ts +352 -0
  84. package/lib/sandbox/control/executor.ts +169 -5
  85. package/lib/sandbox/control/lifecycle.ts +2 -1
  86. package/lib/sandbox/control/protocol.ts +80 -7
  87. package/lib/sandbox/index.ts +5 -3
  88. package/lib/sandbox/managed-fs.ts +5 -0
  89. package/lib/sandbox/task-resolver.ts +58 -7
  90. package/lib/sandbox/workspace-identity.ts +50 -2
  91. package/lib/sandbox/workspace-view.ts +3 -3
  92. package/lib/sandbox/worktree-safety.ts +236 -2
  93. package/lib/task/codex-orchestration.ts +168 -40
  94. package/lib/task/commands/status.ts +78 -1
  95. package/lib/task/commit-operation.ts +430 -0
  96. package/lib/task/commit-policy.ts +30 -0
  97. package/lib/task/delegation-receipts.ts +263 -4
  98. package/lib/task/finalization.ts +761 -0
  99. package/lib/task/index.ts +0 -8
  100. package/lib/task/operation-outcome.ts +48 -0
  101. package/lib/task/orchestration.ts +218 -982
  102. package/lib/task/short-id.ts +65 -1
  103. package/lib/task/task-execution-lock.ts +10 -1
  104. package/lib/task/verification-engine.ts +115 -63
  105. package/lib/task/verification.ts +3 -2
  106. package/lib/task/workflow-warning-intents.ts +57 -2
  107. package/package.json +2 -2
  108. package/templates/.agents/QUICKSTART.en.md +3 -4
  109. package/templates/.agents/QUICKSTART.zh-CN.md +3 -4
  110. package/templates/.agents/hooks/lifecycle-delegation.js +1 -21
  111. package/templates/.agents/rules/README.en.md +1 -0
  112. package/templates/.agents/rules/README.zh-CN.md +1 -0
  113. package/templates/.agents/rules/compatibility-policy.en.md +39 -0
  114. package/templates/.agents/rules/compatibility-policy.zh-CN.md +39 -0
  115. package/templates/.agents/rules/lifecycle-orchestration.en.md +4 -4
  116. package/templates/.agents/rules/lifecycle-orchestration.zh-CN.md +4 -4
  117. package/templates/.agents/rules/pr-sync.en.md +1 -1
  118. package/templates/.agents/rules/pr-sync.github.en.md +2 -1
  119. package/templates/.agents/rules/pr-sync.github.zh-CN.md +2 -0
  120. package/templates/.agents/rules/pr-sync.zh-CN.md +1 -0
  121. package/templates/.agents/rules/review-method.en.md +1 -0
  122. package/templates/.agents/rules/review-method.zh-CN.md +1 -0
  123. package/templates/.agents/rules/task-management.en.md +2 -2
  124. package/templates/.agents/rules/task-management.zh-CN.md +2 -2
  125. package/templates/.agents/skills/analyze-task/SKILL.en.md +1 -0
  126. package/templates/.agents/skills/analyze-task/SKILL.zh-CN.md +1 -0
  127. package/templates/.agents/skills/block-task/SKILL.en.md +2 -4
  128. package/templates/.agents/skills/block-task/SKILL.zh-CN.md +2 -4
  129. package/templates/.agents/skills/cancel-task/SKILL.en.md +3 -3
  130. package/templates/.agents/skills/cancel-task/SKILL.zh-CN.md +3 -3
  131. package/templates/.agents/skills/close-codescan/SKILL.en.md +6 -2
  132. package/templates/.agents/skills/close-codescan/SKILL.zh-CN.md +6 -2
  133. package/templates/.agents/skills/close-dependabot/SKILL.en.md +6 -2
  134. package/templates/.agents/skills/close-dependabot/SKILL.zh-CN.md +6 -2
  135. package/templates/.agents/skills/code-task/SKILL.en.md +1 -0
  136. package/templates/.agents/skills/code-task/SKILL.zh-CN.md +2 -0
  137. package/templates/.agents/skills/commit/SKILL.en.md +41 -125
  138. package/templates/.agents/skills/commit/SKILL.zh-CN.md +52 -123
  139. package/templates/.agents/skills/commit/reference/commit-message.en.md +1 -1
  140. package/templates/.agents/skills/commit/reference/commit-message.zh-CN.md +1 -1
  141. package/templates/.agents/skills/commit/reference/commit-orchestration.en.md +14 -43
  142. package/templates/.agents/skills/commit/reference/commit-orchestration.zh-CN.md +14 -49
  143. package/templates/.agents/skills/commit/reference/pr-summary-sync.en.md +1 -1
  144. package/templates/.agents/skills/commit/reference/pr-summary-sync.zh-CN.md +1 -1
  145. package/templates/.agents/skills/commit/reference/task-status-update.en.md +2 -35
  146. package/templates/.agents/skills/commit/reference/task-status-update.zh-CN.md +2 -35
  147. package/templates/.agents/skills/complete-task/SKILL.en.md +31 -38
  148. package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +31 -38
  149. package/templates/.agents/skills/complete-task/config/verify.en.json +1 -0
  150. package/templates/.agents/skills/complete-task/config/verify.zh-CN.json +1 -0
  151. package/templates/.agents/skills/complete-task/reference/external-delivery.en.md +1 -1
  152. package/templates/.agents/skills/complete-task/reference/external-delivery.zh-CN.md +1 -1
  153. package/templates/.agents/skills/create-pr/SKILL.en.md +17 -9
  154. package/templates/.agents/skills/create-pr/SKILL.zh-CN.md +17 -9
  155. package/templates/.agents/skills/create-pr/reference/change-report.en.md +41 -0
  156. package/templates/.agents/skills/create-pr/reference/change-report.zh-CN.md +41 -0
  157. package/templates/.agents/skills/create-pr/reference/comment-publish.en.md +2 -2
  158. package/templates/.agents/skills/create-pr/reference/comment-publish.zh-CN.md +2 -2
  159. package/templates/.agents/skills/plan-task/SKILL.en.md +2 -1
  160. package/templates/.agents/skills/plan-task/SKILL.zh-CN.md +2 -1
  161. package/templates/.agents/skills/review-code/reference/migration-risks.en.md +8 -6
  162. package/templates/.agents/skills/review-code/reference/migration-risks.zh-CN.md +8 -6
  163. package/templates/.agents/skills/run-manual-validation/SKILL.en.md +3 -3
  164. package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +3 -3
  165. package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.en.md +1 -1
  166. package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.zh-CN.md +1 -1
  167. package/templates/.agents/skills/run-manual-validation/reference/report-template.en.md +2 -2
  168. package/templates/.agents/skills/run-manual-validation/reference/report-template.zh-CN.md +2 -2
  169. package/templates/.agents/skills/run-task/SKILL.en.md +6 -6
  170. package/templates/.agents/skills/run-task/SKILL.zh-CN.md +6 -6
  171. package/templates/.agents/skills/run-task/reference/host-validation.en.md +2 -2
  172. package/templates/.agents/skills/run-task/reference/host-validation.zh-CN.md +2 -2
  173. package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +24 -0
  174. package/templates/.agents/skills/watch-pr/reference/monitor-and-heal.en.md +1 -1
  175. package/templates/.agents/skills/watch-pr/reference/monitor-and-heal.zh-CN.md +1 -1
  176. package/templates/.codex/hooks.json +4 -4
  177. package/templates/.trae/skills/update-agent-infra.en.md +8 -0
  178. package/templates/.trae/skills/update-agent-infra.zh-CN.md +8 -0
  179. package/dist/lib/task/commit-finalization.js +0 -305
  180. package/dist/lib/task/commit-intent.js +0 -165
  181. package/lib/task/commit-finalization.ts +0 -419
  182. package/lib/task/commit-intent.ts +0 -230
@@ -1,419 +0,0 @@
1
- import { execFileSync, spawnSync } from 'node:child_process';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
-
5
- import {
6
- locateActivityLog,
7
- appendActivityEntry,
8
- pairEntries,
9
- parseCommitAttemptStarted
10
- } from './activity-log.ts';
11
- import type { CommitAttempt } from './activity-log.ts';
12
- import { commitIntentPath, digest, readCommitIntent } from './commit-intent.ts';
13
- import type { CommitIntent } from './commit-intent.ts';
14
- import { parseTypedTaskFrontmatter } from './frontmatter.ts';
15
- import { artifactName, maxRound, parseReviewSummary } from './review-artifacts.ts';
16
- import {
17
- extractReviewBaseline,
18
- extractReviewedSnapshotTree,
19
- findAuthoritativeReviewCodeArtifact,
20
- parseReviewedGitTree
21
- } from './review-fingerprint.ts';
22
- import type { TaskMutation } from './write.ts';
23
-
24
- type CommitFinalizationDisposition =
25
- | 'idle'
26
- | 'prepared'
27
- | 'recoverable'
28
- | 'invalid'
29
- | 'conflict'
30
- | 'retryable-start'
31
- | 'orphaned-start';
32
-
33
- type CommitFinalizationCode =
34
- | 'COMMIT_FINALIZATION_PENDING'
35
- | 'COMMIT_FINALIZATION_EVIDENCE_MISSING'
36
- | 'COMMIT_FINALIZATION_EVIDENCE_INVALID'
37
- | 'COMMIT_FINALIZATION_CONFLICT';
38
-
39
- type CommitFinalizationInspection = Readonly<{
40
- disposition: CommitFinalizationDisposition;
41
- code: CommitFinalizationCode | null;
42
- message: string;
43
- currentHead: string;
44
- committedHead: string | null;
45
- commitNote: string | null;
46
- activityNote: string | null;
47
- needsAnchor: boolean;
48
- needsLog: boolean;
49
- intent: CommitIntent | null;
50
- intentDigest: string | null;
51
- attempt: CommitAttempt | null;
52
- }>;
53
-
54
- type CreatePrCommitGate = Readonly<{
55
- allowed: boolean;
56
- code: CommitFinalizationCode | null;
57
- message: string;
58
- disposition: CommitFinalizationDisposition;
59
- action: 'continue' | 'rerun-commit' | 'rerun-review-code';
60
- }>;
61
-
62
- type CommitTaskFinalizationPlan = Readonly<{
63
- mutations: readonly TaskMutation[];
64
- commitNote: string;
65
- }>;
66
-
67
- const SHA_RE = /^[a-f0-9]{40,64}$/;
68
-
69
- function git(repoRoot: string, args: string[]): string {
70
- return execFileSync('git', args, {
71
- cwd: repoRoot,
72
- encoding: 'utf8',
73
- stdio: ['ignore', 'pipe', 'pipe']
74
- }).trim();
75
- }
76
-
77
- function commitExists(repoRoot: string, value: string): boolean {
78
- return SHA_RE.test(value) && spawnSync('git', ['cat-file', '-e', `${value}^{commit}`], {
79
- cwd: repoRoot,
80
- stdio: 'ignore'
81
- }).status === 0;
82
- }
83
-
84
- function isAncestor(repoRoot: string, ancestor: string, descendant: string): boolean {
85
- return spawnSync('git', ['merge-base', '--is-ancestor', ancestor, descendant], {
86
- cwd: repoRoot,
87
- stdio: 'ignore'
88
- }).status === 0;
89
- }
90
-
91
- function hasMatchingApprovedReview(
92
- taskDir: string,
93
- beforeRound: number,
94
- baseline: string,
95
- tree: string
96
- ): boolean {
97
- const entries = fs.readdirSync(taskDir);
98
- for (let round = Math.min(beforeRound - 1, maxRound(entries, 'review-code')); round >= 1; round -= 1) {
99
- const file = path.join(taskDir, artifactName('review-code', round));
100
- if (!fs.existsSync(file)) continue;
101
- const content = fs.readFileSync(file, 'utf8');
102
- const summary = parseReviewSummary(content);
103
- if (
104
- summary.ok
105
- && summary.summary.verdict === 'Approved'
106
- && extractReviewBaseline(content) === baseline
107
- && extractReviewedSnapshotTree(content) === tree
108
- ) return true;
109
- }
110
- return false;
111
- }
112
-
113
- function outcome(
114
- disposition: CommitFinalizationDisposition,
115
- overrides: Partial<CommitFinalizationInspection> = {}
116
- ): CommitFinalizationInspection {
117
- return {
118
- disposition,
119
- code: null,
120
- message: disposition,
121
- currentHead: '',
122
- committedHead: null,
123
- commitNote: null,
124
- activityNote: null,
125
- needsAnchor: false,
126
- needsLog: false,
127
- intent: null,
128
- intentDigest: null,
129
- attempt: null,
130
- ...overrides
131
- };
132
- }
133
-
134
- function invalid(
135
- message: string,
136
- currentHead = '',
137
- code: CommitFinalizationCode = 'COMMIT_FINALIZATION_EVIDENCE_INVALID',
138
- overrides: Partial<CommitFinalizationInspection> = {}
139
- ): CommitFinalizationInspection {
140
- return outcome('invalid', { code, message, currentHead, ...overrides });
141
- }
142
-
143
- function inspectCommitFinalization(
144
- taskDir: string,
145
- repoRoot: string,
146
- taskId: string
147
- ): CommitFinalizationInspection {
148
- let currentHead: string;
149
- let taskContent: string;
150
- let metadata: ReturnType<typeof parseTypedTaskFrontmatter>;
151
- try {
152
- currentHead = git(repoRoot, ['rev-parse', 'HEAD']);
153
- taskContent = fs.readFileSync(path.join(taskDir, 'task.md'), 'utf8');
154
- metadata = parseTypedTaskFrontmatter(taskContent);
155
- } catch (error) {
156
- return invalid(error instanceof Error ? error.message : String(error));
157
- }
158
-
159
- const activity = locateActivityLog(taskContent);
160
- if (!activity) return invalid('task activity log is missing or ambiguous', currentHead);
161
- const commitRows = pairEntries(activity.entries).filter((row) => row.step === 'Commit');
162
- const openRows = commitRows.filter((row) => row.started !== '' && row.done === '');
163
- const file = commitIntentPath(taskDir);
164
- if (!fs.existsSync(file)) {
165
- if (openRows.length === 1) {
166
- const attempt = parseCommitAttemptStarted(openRows[0]!.note);
167
- if (attempt && attempt.baseline === currentHead) {
168
- return outcome('retryable-start', {
169
- message: 'a structured Commit attempt can be safely reused',
170
- currentHead,
171
- attempt
172
- });
173
- }
174
- }
175
- if (openRows.length > 0) {
176
- return outcome('orphaned-start', {
177
- code: 'COMMIT_FINALIZATION_EVIDENCE_MISSING',
178
- message: 'an open Commit activity entry exists without a commit intent',
179
- currentHead
180
- });
181
- }
182
- return outcome('idle', { message: 'no active commit finalization exists', currentHead });
183
- }
184
-
185
- let raw: string;
186
- let intent: CommitIntent;
187
- try {
188
- raw = fs.readFileSync(file, 'utf8');
189
- intent = readCommitIntent(taskDir, taskId);
190
- } catch (error) {
191
- return invalid(error instanceof Error ? error.message : String(error), currentHead);
192
- }
193
- const intentDigest = digest(raw);
194
- const shared = { currentHead, intent, intentDigest, committedHead: intent.committedHead };
195
-
196
- if (!commitExists(repoRoot, intent.baselineHead)) {
197
- return invalid('commit intent baseline is not a valid Git commit', currentHead, 'COMMIT_FINALIZATION_EVIDENCE_INVALID', shared);
198
- }
199
-
200
- if (intent.phase === 'prepared') {
201
- if (intent.committedHead !== null || intent.pushEvidence !== null) {
202
- return invalid('prepared commit intent contains commit or push evidence', currentHead, 'COMMIT_FINALIZATION_EVIDENCE_INVALID', shared);
203
- }
204
- if (currentHead !== intent.baselineHead || openRows.length !== 1) {
205
- return outcome('conflict', {
206
- ...shared,
207
- code: 'COMMIT_FINALIZATION_CONFLICT',
208
- message: 'prepared commit intent does not match HEAD and exactly one open Commit entry'
209
- });
210
- }
211
- return outcome('prepared', { ...shared, message: 'prepared commit intent can be safely retried' });
212
- }
213
-
214
- if (!intent.committedHead || !commitExists(repoRoot, intent.committedHead)) {
215
- return invalid('committed intent head is missing or invalid', currentHead, 'COMMIT_FINALIZATION_EVIDENCE_INVALID', shared);
216
- }
217
- if (intent.phase === 'committed' && intent.pushEvidence !== null) {
218
- return invalid('committed intent contains premature push evidence', currentHead, 'COMMIT_FINALIZATION_EVIDENCE_INVALID', shared);
219
- }
220
- if (
221
- intent.phase === 'pushed'
222
- && (
223
- intent.pushEvidence === null
224
- || intent.pushEvidence.head !== intent.committedHead
225
- || !intent.pushEvidence.remote
226
- || !intent.pushEvidence.ref
227
- )
228
- ) {
229
- return invalid('pushed intent evidence is missing or inconsistent', currentHead, 'COMMIT_FINALIZATION_EVIDENCE_INVALID', shared);
230
- }
231
- if (currentHead !== intent.committedHead || !isAncestor(repoRoot, intent.baselineHead, intent.committedHead)) {
232
- return outcome('conflict', {
233
- ...shared,
234
- code: 'COMMIT_FINALIZATION_CONFLICT',
235
- message: 'repository HEAD or ancestry conflicts with the commit intent'
236
- });
237
- }
238
-
239
- const commitNote = git(repoRoot, ['show', '-s', '--format=%h%x20%s', intent.committedHead]);
240
- const matchingDone = commitRows.filter((row) => row.done !== '' && row.note === commitNote);
241
- const pushOnlyRetry = intent.phase === 'pushed'
242
- && intent.baselineHead === intent.committedHead
243
- && matchingDone.length === 1
244
- && openRows.length === 1;
245
- const review = findAuthoritativeReviewCodeArtifact(taskDir);
246
- let needsAnchor = false;
247
- if (review.ok && review.path) {
248
- let reviewContent: string;
249
- try {
250
- reviewContent = fs.readFileSync(review.path, 'utf8');
251
- } catch (error) {
252
- return invalid(error instanceof Error ? error.message : String(error), currentHead, 'COMMIT_FINALIZATION_EVIDENCE_MISSING', shared);
253
- }
254
- const summary = parseReviewSummary(reviewContent);
255
- const reviewBaseline = extractReviewBaseline(reviewContent);
256
- const reviewTree = extractReviewedSnapshotTree(reviewContent);
257
- if (!summary.ok || summary.summary.verdict !== 'Approved' || !commitExists(repoRoot, reviewBaseline) || !parseReviewedGitTree(reviewTree)) {
258
- return invalid('authoritative review-code evidence is not a valid approved snapshot', currentHead, 'COMMIT_FINALIZATION_EVIDENCE_INVALID', shared);
259
- }
260
- const committedTree = git(repoRoot, ['rev-parse', `${intent.committedHead}^{tree}`]);
261
- const matchingCurrentReview = reviewBaseline === intent.baselineHead && reviewTree === committedTree;
262
- if (
263
- !matchingCurrentReview
264
- && !hasMatchingApprovedReview(
265
- taskDir,
266
- review.round,
267
- intent.baselineHead,
268
- committedTree
269
- )
270
- ) {
271
- return outcome('conflict', {
272
- ...shared,
273
- code: 'COMMIT_FINALIZATION_CONFLICT',
274
- message: 'review baseline or snapshot tree conflicts with the committed intent'
275
- });
276
- }
277
-
278
- const anchor = String(metadata.last_reviewed_commit ?? '').trim();
279
- if (anchor && anchor !== intent.committedHead && anchor !== intent.baselineHead) {
280
- return outcome('conflict', {
281
- ...shared,
282
- code: 'COMMIT_FINALIZATION_CONFLICT',
283
- message: 'task review anchor conflicts with the committed intent'
284
- });
285
- }
286
- needsAnchor = anchor !== intent.committedHead;
287
- }
288
- const needsLog = (matchingDone.length === 0 && openRows.length === 1) || pushOnlyRetry;
289
- if (!(needsLog || (matchingDone.length === 1 && openRows.length === 0))) {
290
- return outcome('conflict', {
291
- ...shared,
292
- code: 'COMMIT_FINALIZATION_CONFLICT',
293
- message: 'Commit activity identity is missing, duplicated, or ambiguous',
294
- commitNote
295
- });
296
- }
297
- return outcome('recoverable', {
298
- ...shared,
299
- message: 'commit finalization can be recovered',
300
- commitNote,
301
- activityNote: pushOnlyRetry ? `Pushed ${commitNote}` : commitNote,
302
- needsAnchor,
303
- needsLog
304
- });
305
- }
306
-
307
- function planCommitTaskFinalization(
308
- taskDir: string,
309
- inspection: CommitFinalizationInspection,
310
- agent: string,
311
- timestamp: string
312
- ): CommitTaskFinalizationPlan {
313
- if (
314
- inspection.disposition !== 'recoverable'
315
- || !inspection.committedHead
316
- || !inspection.commitNote
317
- || !inspection.activityNote
318
- ) {
319
- throw new Error('commit finalization task mutations require a recoverable inspection');
320
- }
321
- const taskContent = fs.readFileSync(path.join(taskDir, 'task.md'), 'utf8');
322
- const frontmatter: Record<string, string> = { assigned_to: agent };
323
- if (inspection.needsAnchor) frontmatter.last_reviewed_commit = inspection.committedHead;
324
- const mutations: TaskMutation[] = [{
325
- kind: 'frontmatter',
326
- set: frontmatter
327
- }];
328
- if (inspection.needsLog) {
329
- const activity = locateActivityLog(taskContent);
330
- if (!activity) throw new Error('task activity log is missing or ambiguous');
331
- mutations.push({
332
- kind: 'section',
333
- aliases: ['活动日志', 'Activity Log'],
334
- heading: activity.heading,
335
- body: appendActivityEntry(activity, {
336
- time: timestamp,
337
- step: 'Commit',
338
- agent,
339
- note: inspection.activityNote
340
- })
341
- });
342
- }
343
- return { mutations, commitNote: inspection.commitNote };
344
- }
345
-
346
- function inspectCreatePrCommitGate(taskDir: string, repoRoot: string, taskId: string): CreatePrCommitGate {
347
- const lifecycle = inspectCommitFinalization(taskDir, repoRoot, taskId);
348
- if (lifecycle.disposition !== 'idle') {
349
- const pending = lifecycle.disposition === 'prepared' || lifecycle.disposition === 'recoverable';
350
- return {
351
- allowed: false,
352
- code: pending ? 'COMMIT_FINALIZATION_PENDING' : lifecycle.code ?? 'COMMIT_FINALIZATION_CONFLICT',
353
- message: pending ? 'commit finalization must complete before creating a pull request' : lifecycle.message,
354
- disposition: lifecycle.disposition,
355
- action: 'rerun-commit'
356
- };
357
- }
358
-
359
- const review = findAuthoritativeReviewCodeArtifact(taskDir);
360
- if (!review.ok || !review.path) {
361
- return { allowed: true, code: null, message: 'no review-code history requires an anchor', disposition: 'idle', action: 'continue' };
362
- }
363
- try {
364
- const content = fs.readFileSync(review.path, 'utf8');
365
- const summary = parseReviewSummary(content);
366
- if (!summary.ok || summary.summary.verdict !== 'Approved') {
367
- return {
368
- allowed: false,
369
- code: 'COMMIT_FINALIZATION_EVIDENCE_INVALID',
370
- message: 'latest authoritative review-code is not approved',
371
- disposition: 'idle',
372
- action: 'rerun-review-code'
373
- };
374
- }
375
- const task = parseTypedTaskFrontmatter(fs.readFileSync(path.join(taskDir, 'task.md'), 'utf8'));
376
- const currentHead = git(repoRoot, ['rev-parse', 'HEAD']);
377
- const anchor = String(task.last_reviewed_commit ?? '').trim();
378
- if (!anchor || !commitExists(repoRoot, anchor)) {
379
- return {
380
- allowed: false,
381
- code: 'COMMIT_FINALIZATION_EVIDENCE_MISSING',
382
- message: 'approved review snapshot is not anchored to a Git commit',
383
- disposition: 'idle',
384
- action: 'rerun-commit'
385
- };
386
- }
387
- if (anchor !== currentHead || extractReviewedSnapshotTree(content) !== git(repoRoot, ['rev-parse', 'HEAD^{tree}'])) {
388
- return {
389
- allowed: false,
390
- code: 'COMMIT_FINALIZATION_CONFLICT',
391
- message: 'approved review anchor or tree does not match repository HEAD',
392
- disposition: 'idle',
393
- action: 'rerun-review-code'
394
- };
395
- }
396
- return { allowed: true, code: null, message: 'commit finalization evidence is complete', disposition: 'idle', action: 'continue' };
397
- } catch (error) {
398
- return {
399
- allowed: false,
400
- code: 'COMMIT_FINALIZATION_EVIDENCE_INVALID',
401
- message: error instanceof Error ? error.message : String(error),
402
- disposition: 'idle',
403
- action: 'rerun-review-code'
404
- };
405
- }
406
- }
407
-
408
- export {
409
- inspectCommitFinalization,
410
- inspectCreatePrCommitGate,
411
- planCommitTaskFinalization
412
- };
413
- export type {
414
- CommitFinalizationCode,
415
- CommitFinalizationDisposition,
416
- CommitFinalizationInspection,
417
- CommitTaskFinalizationPlan,
418
- CreatePrCommitGate
419
- };
@@ -1,230 +0,0 @@
1
- import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
-
5
- import type { DelegationReceipt } from './delegation-receipts.ts';
6
-
7
- type CommitIntentPhase = 'prepared' | 'committed' | 'pushed';
8
- type PushEvidence = Readonly<{ remote: string; ref: string; head: string }>;
9
- type CommitIntentOrchestration = Readonly<{
10
- runId: string;
11
- receiptId: string;
12
- authorizationIssuedAt: string;
13
- sourceRunDigest: string;
14
- plannedRunDigest: string;
15
- completionUpdatedAt: string;
16
- plannedReceipt: DelegationReceipt;
17
- }>;
18
- type CommitIntent = Readonly<{
19
- schemaVersion: 1;
20
- taskId: string;
21
- mode: 'standalone' | 'orchestrated';
22
- phase: CommitIntentPhase;
23
- tokenDigest: string;
24
- baselineHead: string;
25
- committedHead: string | null;
26
- pushEvidence: PushEvidence | null;
27
- orchestration: CommitIntentOrchestration | null;
28
- createdAt: string;
29
- updatedAt: string;
30
- }>;
31
- type CommitIntentInput = Omit<CommitIntent, 'schemaVersion' | 'tokenDigest'>;
32
-
33
- class CommitIntentError extends Error {
34
- readonly code: string;
35
-
36
- constructor(code: string, message: string) {
37
- super(message);
38
- this.name = 'CommitIntentError';
39
- this.code = code;
40
- }
41
- }
42
-
43
- function commitIntentPath(taskDir: string): string {
44
- return path.join(taskDir, 'commit-intent.json');
45
- }
46
-
47
- function digest(value: string | Buffer): string {
48
- return createHash('sha256').update(value).digest('hex');
49
- }
50
-
51
- function serialize(value: unknown): string {
52
- return `${JSON.stringify(value, null, 2)}\n`;
53
- }
54
-
55
- function atomicWrite(file: string, value: CommitIntent): void {
56
- const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
57
- try {
58
- fs.writeFileSync(temp, serialize(value), { encoding: 'utf8', flag: 'wx', mode: 0o600 });
59
- const handle = fs.openSync(temp, 'r+');
60
- try {
61
- fs.fsyncSync(handle);
62
- } finally {
63
- fs.closeSync(handle);
64
- }
65
- fs.renameSync(temp, file);
66
- fs.chmodSync(file, 0o600);
67
- try {
68
- const directory = fs.openSync(path.dirname(file), 'r');
69
- try {
70
- fs.fsyncSync(directory);
71
- } finally {
72
- fs.closeSync(directory);
73
- }
74
- } catch (error) {
75
- const code = (error as NodeJS.ErrnoException).code;
76
- if (!['EACCES', 'EISDIR', 'EINVAL', 'EPERM'].includes(code ?? '')) throw error;
77
- }
78
- } finally {
79
- if (fs.existsSync(temp)) fs.unlinkSync(temp);
80
- }
81
- }
82
-
83
- function isRecord(value: unknown): value is Record<string, unknown> {
84
- return typeof value === 'object' && value !== null && !Array.isArray(value);
85
- }
86
-
87
- function keysEqual(value: Record<string, unknown>, expected: readonly string[]): boolean {
88
- return Object.keys(value).sort().join('\0') === [...expected].sort().join('\0');
89
- }
90
-
91
- function validPushEvidence(value: unknown): value is PushEvidence | null {
92
- return value === null || (
93
- isRecord(value)
94
- && keysEqual(value, ['remote', 'ref', 'head'])
95
- && ['remote', 'ref', 'head'].every((key) => typeof value[key] === 'string' && value[key] !== '')
96
- );
97
- }
98
-
99
- function validOrchestration(value: unknown): value is CommitIntentOrchestration | null {
100
- if (value === null) return true;
101
- if (!isRecord(value) || !keysEqual(value, [
102
- 'runId', 'receiptId', 'authorizationIssuedAt', 'sourceRunDigest', 'plannedRunDigest',
103
- 'completionUpdatedAt', 'plannedReceipt'
104
- ])) return false;
105
- return [
106
- 'runId', 'receiptId', 'authorizationIssuedAt', 'sourceRunDigest', 'plannedRunDigest', 'completionUpdatedAt'
107
- ].every((key) => typeof value[key] === 'string' && value[key] !== '') && isRecord(value.plannedReceipt);
108
- }
109
-
110
- function parseIntent(raw: string, taskId: string): CommitIntent {
111
- let value: unknown;
112
- try {
113
- value = JSON.parse(raw);
114
- } catch {
115
- throw new CommitIntentError('ORCHESTRATION_COMMIT_INTENT_INVALID', 'commit intent is not valid JSON');
116
- }
117
- if (!isRecord(value) || !keysEqual(value, [
118
- 'schemaVersion', 'taskId', 'mode', 'phase', 'tokenDigest', 'baselineHead', 'committedHead',
119
- 'pushEvidence', 'orchestration', 'createdAt', 'updatedAt'
120
- ])) {
121
- throw new CommitIntentError('ORCHESTRATION_COMMIT_INTENT_INVALID', 'commit intent has an invalid schema');
122
- }
123
- if (
124
- value.schemaVersion !== 1
125
- || value.taskId !== taskId
126
- || !['standalone', 'orchestrated'].includes(String(value.mode))
127
- || !['prepared', 'committed', 'pushed'].includes(String(value.phase))
128
- || typeof value.tokenDigest !== 'string'
129
- || !/^[a-f0-9]{64}$/.test(value.tokenDigest)
130
- || typeof value.baselineHead !== 'string'
131
- || (value.committedHead !== null && typeof value.committedHead !== 'string')
132
- || !validPushEvidence(value.pushEvidence)
133
- || !validOrchestration(value.orchestration)
134
- || typeof value.createdAt !== 'string'
135
- || typeof value.updatedAt !== 'string'
136
- || (value.mode === 'standalone') !== (value.orchestration === null)
137
- ) {
138
- throw new CommitIntentError('ORCHESTRATION_COMMIT_INTENT_INVALID', 'commit intent has invalid field values');
139
- }
140
- return value as CommitIntent;
141
- }
142
-
143
- function tokenMatches(actualDigest: string, token: string): boolean {
144
- const actual = Buffer.from(actualDigest, 'hex');
145
- const supplied = Buffer.from(digest(token), 'hex');
146
- return actual.length === supplied.length && timingSafeEqual(actual, supplied);
147
- }
148
-
149
- function readCommitIntent(taskDir: string, taskId: string, token?: string): CommitIntent {
150
- const file = commitIntentPath(taskDir);
151
- const intent = parseIntent(fs.readFileSync(file, 'utf8'), taskId);
152
- if (token !== undefined && !tokenMatches(intent.tokenDigest, token)) {
153
- throw new CommitIntentError('ORCHESTRATION_COMMIT_INTENT_TOKEN_MISMATCH', 'commit intent token does not match');
154
- }
155
- return intent;
156
- }
157
-
158
- function createCommitIntent(
159
- taskDir: string,
160
- input: CommitIntentInput,
161
- options: Readonly<{ token?: () => string }> = {}
162
- ): Readonly<{ intent: CommitIntent; token: string }> {
163
- const file = commitIntentPath(taskDir);
164
- if (fs.existsSync(file)) {
165
- throw new CommitIntentError('ORCHESTRATION_COMMIT_INTENT_BUSY', 'an active commit intent already exists');
166
- }
167
- const token = (options.token ?? (() => randomBytes(32).toString('base64url')))();
168
- const intent: CommitIntent = Object.freeze({ schemaVersion: 1, ...input, tokenDigest: digest(token) });
169
- atomicWrite(file, intent);
170
- return { intent, token };
171
- }
172
-
173
- function updateCommitIntent(
174
- taskDir: string,
175
- taskId: string,
176
- token: string,
177
- updates: Partial<Pick<CommitIntent, 'phase' | 'committedHead' | 'pushEvidence' | 'updatedAt'>>
178
- ): CommitIntent {
179
- const current = readCommitIntent(taskDir, taskId, token);
180
- const nextPhase = updates.phase ?? current.phase;
181
- const transitions: Record<CommitIntentPhase, readonly CommitIntentPhase[]> = {
182
- prepared: ['prepared', 'committed', 'pushed'],
183
- committed: ['committed', 'pushed'],
184
- pushed: ['pushed']
185
- };
186
- if (!transitions[current.phase].includes(nextPhase)) {
187
- throw new CommitIntentError('ORCHESTRATION_COMMIT_INTENT_STATE_INVALID', `cannot move commit intent from ${current.phase} to ${nextPhase}`);
188
- }
189
- const updated = Object.freeze({ ...current, ...updates, phase: nextPhase });
190
- atomicWrite(commitIntentPath(taskDir), updated);
191
- return updated;
192
- }
193
-
194
- function removeCommitIntent(taskDir: string, taskId: string, token: string): void {
195
- readCommitIntent(taskDir, taskId, token);
196
- fs.unlinkSync(commitIntentPath(taskDir));
197
- }
198
-
199
- function removeCommitIntentByDigest(taskDir: string, taskId: string, expectedDigest: string): void {
200
- const file = commitIntentPath(taskDir);
201
- const raw = fs.readFileSync(file);
202
- parseIntent(raw.toString('utf8'), taskId);
203
- const actual = digest(raw);
204
- const expected = Buffer.from(expectedDigest, 'hex');
205
- const observed = Buffer.from(actual, 'hex');
206
- if (
207
- !/^[a-f0-9]{64}$/.test(expectedDigest)
208
- || expected.length !== observed.length
209
- || !timingSafeEqual(expected, observed)
210
- ) {
211
- throw new CommitIntentError(
212
- 'ORCHESTRATION_COMMIT_RECOVERY_REQUIRED',
213
- 'commit intent changed after recovery inspection'
214
- );
215
- }
216
- fs.unlinkSync(file);
217
- }
218
-
219
- export {
220
- CommitIntentError,
221
- commitIntentPath,
222
- createCommitIntent,
223
- digest,
224
- readCommitIntent,
225
- removeCommitIntent,
226
- removeCommitIntentByDigest,
227
- serialize,
228
- updateCommitIntent
229
- };
230
- export type { CommitIntent, CommitIntentInput, CommitIntentOrchestration, CommitIntentPhase, PushEvidence };