@ygrishajev/jig 0.0.0-stage → 1.0.1

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 (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/dist/adapters/find-symlink.js +23 -0
  4. package/dist/adapters/git/git-workspace.js +297 -0
  5. package/dist/adapters/local-store/credentials-file.js +51 -0
  6. package/dist/adapters/local-store/local-run-store.js +45 -0
  7. package/dist/adapters/local-store/local-state.js +12 -0
  8. package/dist/adapters/local-store/metrics-log.js +119 -0
  9. package/dist/adapters/local-store/run-artefacts.js +76 -0
  10. package/dist/adapters/local-store/run-lock.js +51 -0
  11. package/dist/adapters/local-store/run-paths.js +49 -0
  12. package/dist/adapters/logging/create-logger.js +29 -0
  13. package/dist/adapters/run-store/composite-run-store.js +57 -0
  14. package/dist/adapters/run-store/git-remote-run-store.js +239 -0
  15. package/dist/adapters/sandbox-image/docker-images.js +93 -0
  16. package/dist/adapters/sandbox-image/image-recipe.js +96 -0
  17. package/dist/adapters/sandbox-image/latest-agent-versions.js +9 -0
  18. package/dist/adapters/sandcastle/agents.js +100 -0
  19. package/dist/adapters/sandcastle/codex-auth.js +191 -0
  20. package/dist/adapters/sandcastle/git-hooks.js +20 -0
  21. package/dist/adapters/sandcastle/open-session.js +67 -0
  22. package/dist/adapters/sandcastle/private-clone-docker.js +232 -0
  23. package/dist/adapters/sandcastle/sandcastle-env.js +17 -0
  24. package/dist/adapters/sandcastle/sandcastle-session.js +338 -0
  25. package/dist/adapters/sandcastle/structured-output.js +35 -0
  26. package/dist/adapters/sandcastle/usage.js +65 -0
  27. package/dist/adapters/telemetry/open-telemetry.js +29 -0
  28. package/dist/adapters/terminal/ask-for-agents.js +61 -0
  29. package/dist/adapters/terminal/ask-for-credential.js +32 -0
  30. package/dist/adapters/terminal/ask-for-preset.js +15 -0
  31. package/dist/adapters/terminal/standard-input.js +7 -0
  32. package/dist/adapters/terminal/terminal.js +45 -0
  33. package/dist/app/container.js +131 -0
  34. package/dist/app/init-sandbox.js +185 -0
  35. package/dist/app/observed-events.js +10 -0
  36. package/dist/app/report-cleanup.js +10 -0
  37. package/dist/app/run-jig.js +101 -0
  38. package/dist/app/run-status.js +20 -0
  39. package/dist/app/run-stores.js +107 -0
  40. package/dist/app/sandbox-image.js +151 -0
  41. package/dist/app/throwaway-sandbox.js +49 -0
  42. package/dist/cli/app-action.js +18 -0
  43. package/dist/cli/commands/presets.js +32 -0
  44. package/dist/cli/commands/run.js +82 -0
  45. package/dist/cli/commands/sandbox.js +54 -0
  46. package/dist/cli/commands/status.js +41 -0
  47. package/dist/cli/config-option.js +18 -0
  48. package/dist/cli/exit-when-done.js +11 -0
  49. package/dist/cli/log-format-option.js +14 -0
  50. package/dist/cli/main.js +33 -0
  51. package/dist/cli/read-request.js +36 -0
  52. package/dist/cli/with-app.js +73 -0
  53. package/dist/cli/with-error-handling.js +31 -0
  54. package/dist/cli/with-input.js +27 -0
  55. package/dist/config/describe-issues.js +6 -0
  56. package/dist/config/environment.js +53 -0
  57. package/dist/config/load-config.js +122 -0
  58. package/dist/config/presets.js +150 -0
  59. package/dist/config/write-config.js +39 -0
  60. package/dist/domain/agent-role.js +12 -0
  61. package/dist/domain/apply-outcome.js +132 -0
  62. package/dist/domain/completion-reuse.js +176 -0
  63. package/dist/domain/design-docs.js +3 -0
  64. package/dist/domain/design-review-report.js +86 -0
  65. package/dist/domain/design-review.js +193 -0
  66. package/dist/domain/errors.js +139 -0
  67. package/dist/domain/events.js +8 -0
  68. package/dist/domain/final-check.js +133 -0
  69. package/dist/domain/outcome.js +26 -0
  70. package/dist/domain/plan-coverage.js +129 -0
  71. package/dist/domain/protected-paths.js +35 -0
  72. package/dist/domain/retry.js +21 -0
  73. package/dist/domain/run-id.js +42 -0
  74. package/dist/domain/run-state.js +147 -0
  75. package/dist/domain/settings.js +49 -0
  76. package/dist/domain/slice.js +63 -0
  77. package/dist/domain/usage.js +1 -0
  78. package/dist/domain/work-facts.js +22 -0
  79. package/dist/flow/define-flow.js +11 -0
  80. package/dist/flow/engine.js +255 -0
  81. package/dist/flow/run-flow.js +129 -0
  82. package/dist/git/branch.js +26 -0
  83. package/dist/git/merge.js +92 -0
  84. package/dist/git/repository.js +48 -0
  85. package/dist/git/throwaway-branch.js +64 -0
  86. package/dist/observers/logging-observer.js +51 -0
  87. package/dist/observers/metrics.js +109 -0
  88. package/dist/observers/run-events.js +25 -0
  89. package/dist/observers/tracing-observer.js +86 -0
  90. package/dist/ports/agent-session.js +1 -0
  91. package/dist/ports/observability.js +1 -0
  92. package/dist/ports/run-store.js +1 -0
  93. package/dist/ports/sandbox-git.js +1 -0
  94. package/dist/ports/sandbox-images.js +1 -0
  95. package/dist/ports/workspace.js +1 -0
  96. package/dist/prompts/design-review.js +172 -0
  97. package/dist/prompts/final-check.js +58 -0
  98. package/dist/prompts/planning.js +111 -0
  99. package/dist/prompts/pull-request.js +78 -0
  100. package/dist/prompts/slice.js +254 -0
  101. package/dist/prompts/toolchain.js +37 -0
  102. package/dist/steps/completion-reuse.js +32 -0
  103. package/dist/steps/design-review.js +38 -0
  104. package/dist/steps/final-check.js +39 -0
  105. package/dist/steps/finishing.js +72 -0
  106. package/dist/steps/planning.js +77 -0
  107. package/dist/steps/pull-request-description.js +142 -0
  108. package/dist/steps/slice.js +149 -0
  109. package/package.json +95 -4
  110. package/presets/cheap-volume.json +7 -0
  111. package/presets/claude-only.json +7 -0
  112. package/presets/codex-only.json +7 -0
  113. package/presets/codex-reviewed-opencode.json +7 -0
  114. package/presets/full-power-codex.json +7 -0
  115. package/presets/full-power.json +7 -0
  116. package/presets/long-claude.json +7 -0
  117. package/presets/open-weight.json +7 -0
@@ -0,0 +1,254 @@
1
+ import { earlierFeedback } from '../domain/slice.js';
2
+ export function implementPrompt(slice, verifyCommand) {
3
+ return [
4
+ 'You are implementing one slice of a larger, already-planned feature.',
5
+ '',
6
+ `Slice: ${slice.title}`,
7
+ `Description: ${slice.description}`,
8
+ ...previousFeedback(slice),
9
+ '',
10
+ ...houseRulesFirst(),
11
+ '',
12
+ 'Make the necessary code changes in this repository to complete this slice.',
13
+ 'Do not rebase, amend or otherwise rewrite the commits already on this branch.',
14
+ '',
15
+ ...checkAgainstHouseRulesLast(),
16
+ '',
17
+ ...commitMessageReply(),
18
+ '',
19
+ 'Before writing a script to re-derive something a tool already reported (e.g. parsing a',
20
+ "mutation-testing or coverage tool's own output by hand), re-read what it already printed.",
21
+ 'Before re-running a slow check, check whether a later, more specific step already covers it',
22
+ '(e.g. a full test-suite run right before a tool that re-runs the same suite itself).',
23
+ '',
24
+ ...verificationGuidance(verifyCommand),
25
+ 'Do not run mutation testing as a side effect of implementation or review.',
26
+ ].join('\n');
27
+ }
28
+ function previousFeedback(slice) {
29
+ if (!slice.lastFeedback)
30
+ return [];
31
+ return [
32
+ '',
33
+ 'A previous attempt at this slice was sent back with changes requested, by its review or by a failed check.',
34
+ 'Address this feedback specifically:',
35
+ slice.lastFeedback,
36
+ ...earlierRounds(slice),
37
+ ];
38
+ }
39
+ function earlierRounds(slice) {
40
+ const rounds = earlierFeedback(slice);
41
+ if (rounds.length === 0)
42
+ return [];
43
+ return [
44
+ '',
45
+ 'Earlier rounds of this slice were sent back with this feedback:',
46
+ ...rounds.map((feedback, round) => roundSection(feedback, round)),
47
+ '',
48
+ 'If the latest feedback reports a problem an earlier round already reported, the previous fix',
49
+ 'did not work: find out why before changing code again, and take a different approach rather',
50
+ 'than adjusting the same one.',
51
+ ];
52
+ }
53
+ function roundSection(feedback, round) {
54
+ return `Round ${round + 1}:\n${keepTail(feedback, EARLIER_FEEDBACK_LIMIT)}`;
55
+ }
56
+ function keepTail(text, limit) {
57
+ return text.length > limit ? `…${text.slice(-limit)}` : text;
58
+ }
59
+ /** An earlier round is history, not the task: cap each one so old rounds cannot drown the latest. */
60
+ export const EARLIER_FEEDBACK_LIMIT = 3000;
61
+ /**
62
+ * Path-scoped rule files (`.claude/rules/`, `.cursor/rules/`…) load on their own only in the tool
63
+ * they were written for; any other implementer has to be told to read them, or the reviewer
64
+ * holds the slice to rules the implementer never saw.
65
+ */
66
+ function houseRulesFirst() {
67
+ return [
68
+ "Before you change any code, read this repository's instructions for agents: AGENTS.md,",
69
+ 'CLAUDE.md or similar files at the root and in the directories you will touch, and every',
70
+ 'rule file they point to (for example under .claude/rules/) that covers a file you will create',
71
+ 'or change — tests included. Your tool may not load these on its own, so open them yourself.',
72
+ 'They are binding: the review of this slice rejects code that breaks them, even when lint',
73
+ 'passes or existing code does the same thing.',
74
+ ];
75
+ }
76
+ /** A review that finds a rule the implementer could have checked costs the slice a whole attempt. */
77
+ function checkAgainstHouseRulesLast() {
78
+ return [
79
+ 'Before you finish, review your own change the way the reviewer will: read your whole diff',
80
+ '(your commits on this branch and anything uncommitted) and, for each rule file that covers a',
81
+ 'changed file, go through it rule by rule. Fix every place your change breaks one.',
82
+ ];
83
+ }
84
+ function commitMessageReply() {
85
+ return [
86
+ 'When you are done, reply with { "commitMessage": string }: the commit message for your',
87
+ 'change. Whatever you leave uncommitted is committed with it, so write it in this',
88
+ "repository's commit convention (its history and any commit-message lint config show it): a",
89
+ 'one-line header that says what changed, then a body that says why.',
90
+ ];
91
+ }
92
+ function verificationGuidance(verifyCommand) {
93
+ if (!verifyCommand) {
94
+ return [
95
+ 'No verify command is configured: use focused tests and lint for the changed files before finishing.',
96
+ 'Report what you checked and any remaining verification gaps.',
97
+ ];
98
+ }
99
+ return [
100
+ `jig runs full verification with \`${verifyCommand}\` once you finish and records the result`,
101
+ 'for review. Use focused checks (one spec file, lint on changed files) while you work.',
102
+ 'Do not run the full verify command or a broader check, including the same script without',
103
+ 'its arguments or a suite it skips, even if the request or repository instructions ask for it.',
104
+ 'Use any recorded verification failure in the feedback above to choose what to fix and check.',
105
+ ];
106
+ }
107
+ export function nothingChangedFeedback(slice) {
108
+ return [
109
+ 'The previous attempt at this slice left the working tree unchanged, so there was nothing to review.',
110
+ ...(slice.lastFeedback ? ['It was meant to address this feedback:', slice.lastFeedback] : []),
111
+ ].join('\n');
112
+ }
113
+ export function commitRejectedFeedback(hookOutput) {
114
+ return [
115
+ "The previous attempt's work is still uncommitted: this repository's commit hooks rejected",
116
+ 'the commit made for it. Fix what the hooks report, then commit the work yourself with a',
117
+ 'message they accept. Their output:',
118
+ hookOutput,
119
+ ].join('\n');
120
+ }
121
+ export function verifyFailedFeedback(command, output) {
122
+ const trimmed = output.trim();
123
+ return [
124
+ `The verify command \`${command}\` failed in the sandbox for this slice's commits.`,
125
+ 'Fix what it reports. Its output:',
126
+ keepTail(trimmed, VERIFY_OUTPUT_TAIL),
127
+ ].join('\n');
128
+ }
129
+ export const VERIFY_OUTPUT_TAIL = 3000;
130
+ /** `range` is a git revision range holding exactly this slice's commits, e.g. `<start>..HEAD`. */
131
+ export function reviewPrompt(slice, range, protectedChanges) {
132
+ return [...sliceReviewSections(slice, range, protectedChanges), ...reviewReplyFormat()].join('\n');
133
+ }
134
+ /** What every slice review covers, shared by the ordinary one and the combined one. */
135
+ function sliceReviewSections(slice, range, protectedChanges) {
136
+ return [
137
+ 'You are the review step of an automated SDLC pipeline.',
138
+ `This slice's change is exactly the commits in \`${range}\` — review all of them together`,
139
+ `(\`git log ${range}\`, \`git diff ${range}\`), including earlier attempts that a previous`,
140
+ 'review sent back. Commits before that range belong to already-approved slices; treat them',
141
+ 'as existing context you can rely on, not something to judge or reject.',
142
+ '',
143
+ `Slice: ${slice.title}`,
144
+ `Description: ${slice.description}`,
145
+ '',
146
+ slice.verification
147
+ ? `\`${slice.verification.command}\` passed in the sandbox for the commits in \`${range}\``
148
+ : 'No verify result is recorded (no verify command is configured). Use focused tests and lint',
149
+ ...(slice.verification
150
+ ? [
151
+ 'jig owns full verification. Do not rerun the verify command or run a broader check',
152
+ '(including the same script without its arguments or a suite it skips), even when the request or repository',
153
+ 'instructions ask for it. Judge this recorded result alongside the diff; use focused',
154
+ 'checks to investigate a specific concern and report any remaining verification gaps.',
155
+ ]
156
+ : ['for the changed files and report what you checked and any remaining verification gaps.']),
157
+ 'Do not run mutation testing as a side effect of review.',
158
+ ...protectedChangesSection(protectedChanges),
159
+ '',
160
+ 'Decide whether this slice is ready to merge as-is.',
161
+ 'Reject the slice if it is not a self-explanatory, standalone deliverable — for example,',
162
+ 'pure scaffolding (types, builders, refactors) for later slices with no meaningful purpose',
163
+ 'of its own; feedback must say it must be folded into the slice that consumes it.',
164
+ '',
165
+ "Judge the change against the description and against this repository's instructions for",
166
+ 'agents (AGENTS.md, CLAUDE.md or similar, and the rule files they point to). For the rules,',
167
+ 'find every rule file that covers a file the range changes, tests included, and go through',
168
+ 'each one rule by rule against the diff — not a general read with the rules in mind. A rule',
169
+ 'broken in many places is reported at each place.',
170
+ 'Review the whole range in one pass and report every problem you find, not only the first or',
171
+ 'the most serious: each rejection costs the slice one of a few attempts, so a problem you',
172
+ 'leave for the next round may be the one it runs out on. On a later round, check the whole',
173
+ 'range again, not only what the last feedback named.',
174
+ ];
175
+ }
176
+ function protectedChangesSection(changes) {
177
+ if (changes.length === 0)
178
+ return [];
179
+ return [
180
+ '',
181
+ 'The commits under review also changed these protected files — existing tests or check',
182
+ 'configuration. Verify ran from these same edited files, so its result covers the edited',
183
+ 'versions, not the originals:',
184
+ ...changes.map(({ path, kind }) => `- ${path} (${kind})`),
185
+ "For each file, confirm that the slice's description requires its change, and that the change",
186
+ 'does not weaken a check: removed or skipped tests, loosened assertions, disabled or relaxed',
187
+ 'rules, a narrower verify script or CI. If either confirmation fails for a file, reject the',
188
+ 'slice with feedback naming that file.',
189
+ ];
190
+ }
191
+ function reviewReplyFormat() {
192
+ return [
193
+ '',
194
+ 'Respond with JSON matching:',
195
+ '{ "approved": boolean, "feedback": string, "onlyRuleFindings": boolean }.',
196
+ ...codeVerdictInstructions(),
197
+ ];
198
+ }
199
+ function codeVerdictInstructions() {
200
+ return [
201
+ 'If approved is false, feedback must list every needed change as a numbered list, each item',
202
+ 'naming the file and line and saying exactly what must change.',
203
+ 'Set onlyRuleFindings to true only when the slice already does everything its description',
204
+ "asks, correctly, and every needed change is a fix to follow the repository's rules (style,",
205
+ 'naming, test conventions, error handling conventions). Set it to false when anything is',
206
+ 'missing, wrong in behaviour, or untested, and whenever you approve.',
207
+ ];
208
+ }
209
+ /**
210
+ * The review of a run whose single slice is its whole change: everything the slice review asks,
211
+ * plus the original request and its plan, so one review can vouch for the whole run.
212
+ */
213
+ export function combinedReviewPrompt(input) {
214
+ return [
215
+ ...sliceReviewSections(input.slice, input.range, input.protectedChanges),
216
+ ...wholeRequestSections(input),
217
+ ...combinedReplyFormat(),
218
+ ].join('\n');
219
+ }
220
+ /** The whole request a combined review also judges, with the plan it was planned against. */
221
+ function wholeRequestSections({ request, plan }) {
222
+ return [
223
+ '',
224
+ "This slice is the run's only slice, so those same commits are the whole run's change: also",
225
+ 'decide whether the whole run fulfils the original request, so its branch can be merged.',
226
+ 'Judge the whole change against the request and the plan below, not only against the slice',
227
+ 'description.',
228
+ '',
229
+ '--- REQUEST START ---',
230
+ request,
231
+ '--- REQUEST END ---',
232
+ '',
233
+ '--- PLAN START ---',
234
+ plan,
235
+ '--- PLAN END ---',
236
+ '',
237
+ 'Report every requirement of the request or the plan that the run leaves unmet, incomplete',
238
+ 'or broken — a gap — in the same pass, not only the first or the most serious. Use focused',
239
+ 'checks to investigate a specific concern.',
240
+ ];
241
+ }
242
+ function combinedReplyFormat() {
243
+ return [
244
+ '',
245
+ 'Respond with JSON matching:',
246
+ '{ "approved": boolean, "feedback": string, "onlyRuleFindings": boolean,',
247
+ ' "fulfilled": boolean, "gaps": string[] }.',
248
+ ...codeVerdictInstructions(),
249
+ 'Set fulfilled to true only when the whole run fulfils the request as planned. List every',
250
+ 'gap, each saying exactly what is unmet or wrong; use an empty list when nothing is.',
251
+ 'Decide the two verdicts independently: report the request and its gaps whatever you decide',
252
+ 'about the code, and judge the code whatever the request still misses.',
253
+ ];
254
+ }
@@ -0,0 +1,37 @@
1
+ export function toolchainPrompt(input) {
2
+ const { dockerfile, setupCommand, verifyCommand, previousFailure } = input;
3
+ return [
4
+ 'You are setting up the sandbox an automated SDLC pipeline will work in for this repository.',
5
+ 'The sandbox is a Docker image built from the Dockerfile below. It already has Node.js 22,',
6
+ 'git, curl, jq and ripgrep on Debian bookworm; you are running inside the current version.',
7
+ '',
8
+ 'Explore the repository — manifests, lockfiles, version files (.nvmrc, .tool-versions,',
9
+ 'pyproject.toml, go.mod, …), CI workflows and the README — to find what it needs to install',
10
+ 'its dependencies and to run its checks.',
11
+ '',
12
+ '--- DOCKERFILE ---',
13
+ dockerfile,
14
+ '--- END DOCKERFILE ---',
15
+ '',
16
+ 'Produce:',
17
+ '- "toolchain": the Dockerfile lines that install what is missing (RUN instructions, run as',
18
+ ' root, before the agent user is created). Empty when nothing is missing. Do not repeat what',
19
+ " the base already has, and do not install the repository's own dependencies here.",
20
+ `- "setupCommand": the command that installs the repository's dependencies inside the`,
21
+ ` sandbox, run from the repository root${setupCommand ? ` (currently "${setupCommand}" — keep it unless it is wrong)` : ''}.`,
22
+ `- "verifyCommand": the command that checks a change — tests, and lint or typecheck if the`,
23
+ ` repository has them${verifyCommand ? ` (currently "${verifyCommand}" — keep it unless it is wrong)` : ''}.`,
24
+ ...(previousFailure
25
+ ? [
26
+ '',
27
+ 'The previous attempt did not work. Fix what this output shows:',
28
+ '--- FAILURE ---',
29
+ previousFailure,
30
+ '--- END FAILURE ---',
31
+ ]
32
+ : []),
33
+ '',
34
+ 'Do not change any files. Respond with JSON matching:',
35
+ '{ "toolchain": string, "setupCommand": string, "verifyCommand": string }.',
36
+ ].join('\n');
37
+ }
@@ -0,0 +1,32 @@
1
+ import { Result } from 'better-result';
2
+ import { completionReuseInPlay, completionReuseWasAuthorized, completionStillReusable, } from '../domain/completion-reuse.js';
3
+ /**
4
+ * Decides, once every slice is approved, whether the run finishes on the evidence its combined
5
+ * review recorded or goes through an ordinary final check. It runs no command and asks no agent.
6
+ */
7
+ export const decideCompletionReuse = (context) => Result.gen(async function* () {
8
+ const reusable = yield* Result.await(evidenceStillHolds(context));
9
+ return Result.ok({ type: reusable ? 'completionReused' : 'completionDeclined' });
10
+ });
11
+ /** Observes the work as it stands now and asks the domain whether the recorded evidence still vouches for it. */
12
+ function evidenceStillHolds({ state, ports, settings, }) {
13
+ if (!completionReuseInPlay(state, settings))
14
+ return Promise.resolve(Result.ok(false));
15
+ return Result.gen(async function* () {
16
+ const observed = yield* Result.await(ports.workspace.collectFacts());
17
+ const forkPoint = yield* Result.await(ports.workspace.forkPoint());
18
+ return Result.ok(completionStillReusable(state, observed, settings, forkPoint));
19
+ });
20
+ }
21
+ /**
22
+ * Whether finishing must stop acting on reused evidence: the run was authorized to finish on it
23
+ * and the work, sources or settings no longer match it. A run finishing otherwise is never
24
+ * invalidated, and nothing is observed for it.
25
+ */
26
+ export function completionInvalidated(context) {
27
+ return Result.gen(async function* () {
28
+ if (!completionReuseWasAuthorized(context.state))
29
+ return Result.ok(false);
30
+ return Result.ok(!(yield* Result.await(evidenceStillHolds(context))));
31
+ });
32
+ }
@@ -0,0 +1,38 @@
1
+ import { designReReview, designReviewSchema, designRevisionSchemaFor, findingsToRevise, resolveDesignReview, } from '../domain/design-review.js';
2
+ import { designReReviewPrompt, designReviewPrompt, designRevisionPrompt, } from '../prompts/design-review.js';
3
+ /**
4
+ * Has a fresh reviewer check the design and plan before slicing: the documents as written, or —
5
+ * once the planner has revised them — the revision against the findings and dispositions.
6
+ */
7
+ export const reviewDesign = async ({ state, ports }) => {
8
+ const inputs = designInputs(state);
9
+ const reReview = designReReview(state);
10
+ const review = await ports.agent.runForOutput({
11
+ role: 'reviewer',
12
+ prompt: reReview
13
+ ? designReReviewPrompt({ ...inputs, ...reReview })
14
+ : designReviewPrompt(inputs),
15
+ schema: designReviewSchema,
16
+ });
17
+ return review.map((reviewed) => ({ type: 'designReviewed', review: reviewed }));
18
+ };
19
+ function designInputs(state) {
20
+ return {
21
+ request: state.request,
22
+ repoSummary: state.context.repoSummary,
23
+ plan: state.plan,
24
+ docs: state.docs,
25
+ };
26
+ }
27
+ /** The planner's one revision: revised documents and a disposition for every finding. */
28
+ export const reviseDesign = async ({ state, ports }) => {
29
+ const findings = findingsToRevise(state.designReview);
30
+ const revision = await ports.agent.runForOutput({
31
+ role: 'planner',
32
+ prompt: designRevisionPrompt({ ...designInputs(state), findings }),
33
+ schema: designRevisionSchemaFor(findings),
34
+ });
35
+ return revision.map((revised) => ({ type: 'designRevised', revision: revised }));
36
+ };
37
+ /** Lets a reviewed design on to slicing, or blocks the run on the findings still standing. */
38
+ export const resolveDesign = async ({ state }) => resolveDesignReview(state.designReview).map(() => ({ type: 'continue' }));
@@ -0,0 +1,39 @@
1
+ import { Result } from 'better-result';
2
+ import { fulfillmentVerdictSchema } from '../domain/final-check.js';
3
+ import { finalCheckPrompt } from '../prompts/final-check.js';
4
+ /**
5
+ * The whole-run final check: runs the configured verification once in the sandbox, then has the
6
+ * reviewer judge the entire run against its request even when verification failed. It commits
7
+ * nothing and imports nothing — any repair goes back through the slices.
8
+ */
9
+ export const checkWholeRun = ({ state, ports, settings }) => Result.gen(async function* () {
10
+ const command = settings.verifyCommand;
11
+ const ran = command ? yield* Result.await(ports.agent.exec(command)) : undefined;
12
+ const verification = ran && command ? verificationOf(command, ran) : undefined;
13
+ const start = yield* Result.await(ports.workspace.forkPoint());
14
+ const verdict = yield* Result.await(ports.agent.runForOutput({
15
+ role: 'reviewer',
16
+ prompt: finalCheckPrompt({
17
+ request: state.request,
18
+ plan: state.docs.plan,
19
+ range: `${start}..HEAD`,
20
+ verification,
21
+ }),
22
+ schema: fulfillmentVerdictSchema,
23
+ }));
24
+ return Result.ok({
25
+ type: 'finalChecked',
26
+ verified: verification?.passed ?? true,
27
+ command: verification?.command,
28
+ output: verification?.output,
29
+ fulfilled: verdict.fulfilled,
30
+ gaps: verdict.gaps,
31
+ });
32
+ });
33
+ function verificationOf(command, ran) {
34
+ return {
35
+ command,
36
+ passed: ran.exitCode === 0,
37
+ ...(ran.exitCode === 0 ? {} : { output: ran.output }),
38
+ };
39
+ }
@@ -0,0 +1,72 @@
1
+ import { Result } from 'better-result';
2
+ import { z } from 'zod';
3
+ import { reusedCompletion } from '../domain/completion-reuse.js';
4
+ import { slicesInOrder } from '../domain/slice.js';
5
+ import { pullRequestPrompt } from '../prompts/pull-request.js';
6
+ import { completionInvalidated } from './completion-reuse.js';
7
+ import { DEFAULT_PR_TEMPLATE, renderPullRequest } from './pull-request-description.js';
8
+ /**
9
+ * Best effort: if the describer fails, the run still gets a description built from its own state.
10
+ * A run finishing on reused evidence first checks that evidence still holds, and describes nothing
11
+ * when it does not.
12
+ */
13
+ export const describePullRequest = (context) => Result.gen(async function* () {
14
+ if (yield* Result.await(completionInvalidated(context))) {
15
+ return Result.ok({ type: 'completionInvalidated' });
16
+ }
17
+ const { state, ports, settings } = context;
18
+ const template = await findTemplate(ports);
19
+ const filled = await fillTemplate(state, ports, template ?? DEFAULT_PR_TEMPLATE, settings.verifyCommand);
20
+ return Result.ok({
21
+ type: 'described',
22
+ body: renderPullRequest(state, { filled, template, verifyCommand: settings.verifyCommand }),
23
+ });
24
+ });
25
+ async function findTemplate(ports) {
26
+ for (const relativePath of TEMPLATE_PATHS) {
27
+ const template = await ports.workspace.readRepoFile(relativePath);
28
+ if (template !== undefined)
29
+ return template.trim();
30
+ }
31
+ return undefined;
32
+ }
33
+ const TEMPLATE_PATHS = [
34
+ '.github/pull_request_template.md',
35
+ '.github/PULL_REQUEST_TEMPLATE.md',
36
+ 'pull_request_template.md',
37
+ ];
38
+ async function fillTemplate(state, ports, template, verifyCommand) {
39
+ const described = await ports.agent.runForOutput({
40
+ role: 'describer',
41
+ prompt: pullRequestPrompt({
42
+ template,
43
+ plan: state.plan,
44
+ slices: state.slices,
45
+ design: state.docs.design,
46
+ verifyCommand,
47
+ finalCheck: state.finalCheck,
48
+ reusedCompletion: reusedCompletion(state),
49
+ }),
50
+ schema: descriptionSchema,
51
+ });
52
+ return described.isOk() ? described.value.body.trim() : undefined;
53
+ }
54
+ const descriptionSchema = z.object({ body: z.string().min(1) });
55
+ /**
56
+ * A branch the operator already merged is done. Otherwise a run finishing on reused evidence
57
+ * checks it still holds before it merges or waits for a person to, resumed waits included.
58
+ */
59
+ export const mergeRunBranch = (context) => Result.gen(async function* () {
60
+ const { state, ports, settings } = context;
61
+ if (yield* Result.await(ports.workspace.isRunBranchMerged())) {
62
+ return Result.ok({ type: 'merged' });
63
+ }
64
+ if (yield* Result.await(completionInvalidated(context))) {
65
+ return Result.ok({ type: 'completionInvalidated' });
66
+ }
67
+ if (settings.mergeMode === 'manual')
68
+ return Result.ok({ type: 'awaitingManualMerge' });
69
+ const approved = slicesInOrder(state.slices).at(-1)?.commit;
70
+ yield* Result.await(ports.workspace.mergeRunBranch({ approved }));
71
+ return Result.ok({ type: 'merged' });
72
+ });
@@ -0,0 +1,77 @@
1
+ import { Result } from 'better-result';
2
+ import { z } from 'zod';
3
+ import { designDocsSchema } from '../domain/design-docs.js';
4
+ import { AgentOutputInvalid, PlanNotCovered } from '../domain/errors.js';
5
+ import { checkPlanCoverage } from '../domain/plan-coverage.js';
6
+ import { retryResult } from '../domain/retry.js';
7
+ import { featurePlanSchema, runContextSchema } from '../domain/run-state.js';
8
+ import { plannedSliceSchema } from '../domain/slice.js';
9
+ import { contextPrompt, designPrompt, featurePlanPrompt, slicePlanPrompt, } from '../prompts/planning.js';
10
+ export const buildContext = async ({ state, ports }) => {
11
+ const context = await ports.agent.runForOutput({
12
+ role: 'planner',
13
+ prompt: contextPrompt(state.request),
14
+ schema: runContextSchema,
15
+ });
16
+ return context.map((built) => ({ type: 'contextBuilt', context: built }));
17
+ };
18
+ export const planFeature = async ({ state, ports }) => {
19
+ const plan = await ports.agent.runForOutput({
20
+ role: 'planner',
21
+ prompt: featurePlanPrompt(state.request, state.context.repoSummary),
22
+ schema: featurePlanSchema,
23
+ });
24
+ return plan.map((planned) => ({ type: 'featurePlanned', plan: planned }));
25
+ };
26
+ export const writeDesign = async ({ state, ports }) => {
27
+ const docs = await ports.agent.runForOutput({
28
+ role: 'planner',
29
+ prompt: designPrompt(state.request, state.context.repoSummary, state.plan),
30
+ schema: designDocsSchema,
31
+ });
32
+ return docs.map((written) => ({ type: 'designWritten', docs: written }));
33
+ };
34
+ /**
35
+ * One correction attempt for a plan its slices do not cover; whatever survives it is the planner's
36
+ * invalid output, so the check's PlanNotCovered surfaces as AgentOutputInvalid.
37
+ */
38
+ export const sliceThePlan = async ({ state, ports }) => {
39
+ const plan = state.docs.plan;
40
+ let correction;
41
+ const sliced = await retryResult(() => slicePlanAttempt(plan, ports, correction), {
42
+ retries: 1,
43
+ delayMs: 0,
44
+ shouldRetry: (error) => error instanceof PlanNotCovered,
45
+ onFailedAttempt: ({ error }) => {
46
+ if (error instanceof PlanNotCovered)
47
+ correction = error.message;
48
+ },
49
+ });
50
+ return sliced.mapError((error) => error instanceof PlanNotCovered ? new AgentOutputInvalid({ message: error.message }) : error);
51
+ };
52
+ function slicePlanAttempt(plan, ports, correction) {
53
+ return Result.gen(async function* () {
54
+ const slices = yield* Result.await(ports.agent.runForOutput({
55
+ role: 'planner',
56
+ prompt: slicePlanPrompt(plan, correction),
57
+ schema: plannedSlicesSchema,
58
+ }));
59
+ yield* requireUniqueIds(slices);
60
+ yield* checkPlanCoverage(plan, slices);
61
+ return Result.ok({ type: 'sliced', slices });
62
+ });
63
+ }
64
+ const plannedSlicesSchema = z
65
+ .array(plannedSliceSchema)
66
+ .min(1, 'the plan must produce at least one slice');
67
+ /** Duplicate ids would make two slices share one status, so the run could never finish them both. */
68
+ function requireUniqueIds(slices) {
69
+ const ids = slices.map((slice) => slice.id);
70
+ const duplicates = ids.filter((id, index) => ids.indexOf(id) !== index);
71
+ if (duplicates.length === 0)
72
+ return Result.ok();
73
+ return Result.err(new AgentOutputInvalid({
74
+ message: `The slice plan repeats slice ids: ${[...new Set(duplicates)].join(', ')}`,
75
+ }));
76
+ }
77
+ export const applyDesignGate = async ({ settings }) => Result.ok(settings.designGate === 'checkpoint' ? { type: 'pause' } : { type: 'continue' });