@ygrishajev/jig 0.0.0-stage → 1.0.0

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,11 @@
1
+ export function defineSliceFlow(flow) {
2
+ return flow;
3
+ }
4
+ export function defineRunFlow(flow) {
5
+ return flow;
6
+ }
7
+ /** How the run ended, when its phase is one it never leaves; undefined while it can still move. */
8
+ export function finalStatus(flow, state) {
9
+ const node = flow[state.phase];
10
+ return 'final' in node ? node.final : undefined;
11
+ }
@@ -0,0 +1,255 @@
1
+ import { panic, Result } from 'better-result';
2
+ import { applyOutcome, updateCurrentSlice } from '../domain/apply-outcome.js';
3
+ import { isTransient, messageOf, rootCause } from '../domain/errors.js';
4
+ import { retryResult, transientRetryPolicy } from '../domain/retry.js';
5
+ import { currentSlice, enterPhase, } from '../domain/run-state.js';
6
+ /**
7
+ * Drives a run through `flow` from its saved phase until it finishes, halts, or blocks. A `fatal`
8
+ * failure, or one saving the run, ends the invocation as an `Err`.
9
+ */
10
+ export async function runEngine(flow, initial, dependencies) {
11
+ const engine = new Engine(flow, dependencies);
12
+ return engine.run(initial);
13
+ }
14
+ class Engine {
15
+ flow;
16
+ dependencies;
17
+ constructor(flow, dependencies) {
18
+ this.flow = flow;
19
+ this.dependencies = dependencies;
20
+ }
21
+ /** Every invocation that resumes a run ends it with one run-level event, a failure or a bug included. */
22
+ async run(initial) {
23
+ this.dependencies.events.publish({
24
+ type: 'runResumed',
25
+ runId: initial.runId,
26
+ phase: initial.phase,
27
+ });
28
+ let saved = initial;
29
+ let settled;
30
+ try {
31
+ settled = await this.settle(initial, (state) => (saved = state));
32
+ }
33
+ catch (error) {
34
+ const bug = rootCause(error);
35
+ this.publishRunFailed(saved, messageOf(bug));
36
+ panic(messageOf(bug), bug);
37
+ }
38
+ if (settled.isErr())
39
+ this.publishRunFailed(saved, settled.error.message);
40
+ return settled;
41
+ }
42
+ async settle(initial, onSaved) {
43
+ const resumed = await this.leaveHaltOrBlock(initial);
44
+ if (resumed.isErr())
45
+ return resumed;
46
+ let state = resumed.value;
47
+ onSaved(state);
48
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
49
+ const passed = await this.pass(state.phase, state);
50
+ if (passed.isErr())
51
+ return passed;
52
+ if ('result' in passed.value)
53
+ return Result.ok(passed.value.result);
54
+ state = passed.value.state;
55
+ const saved = await this.dependencies.store.save(state);
56
+ if (saved.isErr())
57
+ return saved;
58
+ onSaved(state);
59
+ }
60
+ panic(`Run ${state.runId} did not settle after ${MAX_PASSES} passes — the flow has a cycle.`);
61
+ }
62
+ async leaveHaltOrBlock(state) {
63
+ const node = this.flow[state.phase];
64
+ const resumed = { ...state, blockedReason: undefined };
65
+ if (!('halt' in node))
66
+ return Result.ok(resumed);
67
+ const next = this.changePhase(resumed, node.resumeAt);
68
+ return (await this.dependencies.store.save(next)).map(() => next);
69
+ }
70
+ /** `from` is where the run stood before its outcome applied, which may already have moved it. */
71
+ changePhase(state, to, from = state.phase) {
72
+ if (to !== from) {
73
+ this.dependencies.events.publish({ type: 'phaseChanged', runId: state.runId, from, to });
74
+ }
75
+ return enterPhase(state, to);
76
+ }
77
+ /** One step of the run from `phase`; generic so the phase's step sees what `phase` guarantees. */
78
+ async pass(phase, state) {
79
+ const node = this.flow[phase];
80
+ if ('final' in node)
81
+ return Result.ok({ result: this.finish(state, node.final) });
82
+ if ('halt' in node)
83
+ return Result.ok({ result: this.halt(state) });
84
+ const advanced = 'forEachSlice' in node
85
+ ? await this.advanceSlices(node, state)
86
+ : await this.advancePhase(node, state);
87
+ if (advanced.isErr())
88
+ return advanced;
89
+ if (!('blockedReason' in advanced.value))
90
+ return Result.ok(advanced.value);
91
+ return (await this.block(state, advanced.value.blockedReason)).map((result) => ({ result }));
92
+ }
93
+ finish(state, final) {
94
+ this.dependencies.events.publish({
95
+ type: 'runFinished',
96
+ runId: state.runId,
97
+ phase: state.phase,
98
+ });
99
+ return { state, status: final };
100
+ }
101
+ halt(state) {
102
+ this.dependencies.events.publish({ type: 'runHalted', runId: state.runId, phase: state.phase });
103
+ return { state, status: 'halted' };
104
+ }
105
+ async advanceSlices(node, state) {
106
+ const slice = currentSlice(state);
107
+ if (!slice)
108
+ return Result.ok({ state: this.changePhase(state, node.on.allApproved) });
109
+ const sliceNode = node.forEachSlice[slice.status];
110
+ if ('final' in sliceNode) {
111
+ return Result.ok({ state: this.changePhase(state, node.on.sliceStuck) });
112
+ }
113
+ const at = { phase: state.phase, sliceId: slice.id, sliceStatus: slice.status };
114
+ const attempted = await this.attempt(at, state.runId, () => sliceNode.step({
115
+ state,
116
+ ports: this.dependencies.ports,
117
+ settings: this.dependencies.settings,
118
+ slice,
119
+ }));
120
+ if (attempted.isErr())
121
+ return attempted;
122
+ if ('blockedReason' in attempted.value)
123
+ return Result.ok(attempted.value);
124
+ const { outcome } = attempted.value;
125
+ const applied = applyOutcome(state, outcome);
126
+ const nextStatus = this.resolve(sliceNode.on, outcome, {
127
+ state: applied,
128
+ slice: currentSlice(applied),
129
+ settings: this.dependencies.settings,
130
+ });
131
+ this.dependencies.events.publish({
132
+ type: 'sliceStatusChanged',
133
+ runId: state.runId,
134
+ sliceId: slice.id,
135
+ from: slice.status,
136
+ to: nextStatus,
137
+ });
138
+ return Result.ok({
139
+ state: updateCurrentSlice(applied, (current) => ({ ...current, status: nextStatus })),
140
+ });
141
+ }
142
+ /**
143
+ * Runs a step under the failure policy: `retry` failures are retried up to `maxStepRetries`
144
+ * and then block the run, `block` failures block it straight away, and `fatal` ones are returned.
145
+ */
146
+ async attempt(at, runId, step) {
147
+ const attempted = await retryResult(() => this.timed(at, runId, step), {
148
+ ...transientRetryPolicy(this.dependencies.settings),
149
+ onFailedAttempt: ({ error, attempt, retriesLeft }) => {
150
+ if (!isTransient(error) || retriesLeft === 0)
151
+ return;
152
+ this.dependencies.events.publish({
153
+ type: 'stepRetried',
154
+ runId,
155
+ at,
156
+ attempt,
157
+ reason: error.message,
158
+ });
159
+ },
160
+ });
161
+ if (attempted.isOk())
162
+ return Result.ok({ outcome: attempted.value });
163
+ if (attempted.error.kind === 'fatal')
164
+ return Result.err(attempted.error);
165
+ return Result.ok({ blockedReason: attempted.error.message });
166
+ }
167
+ /** A step that throws is a bug; its attempt is still reported as failed before it goes on up. */
168
+ async timed(at, runId, step) {
169
+ const startedAt = this.dependencies.clock.now();
170
+ const elapsed = () => this.dependencies.clock.now() - startedAt;
171
+ const publishFailed = (reason) => this.dependencies.events.publish({
172
+ type: 'stepFailed',
173
+ runId,
174
+ at,
175
+ reason,
176
+ durationMs: elapsed(),
177
+ });
178
+ this.dependencies.events.publish({ type: 'stepStarted', runId, at });
179
+ let stepped;
180
+ try {
181
+ stepped = await step();
182
+ }
183
+ catch (error) {
184
+ const bug = rootCause(error);
185
+ publishFailed(messageOf(bug));
186
+ panic(messageOf(bug), bug);
187
+ }
188
+ if (stepped.isErr()) {
189
+ publishFailed(stepped.error.message);
190
+ return stepped;
191
+ }
192
+ const outcome = stepped.value;
193
+ this.dependencies.events.publish({
194
+ type: 'stepFinished',
195
+ runId,
196
+ at,
197
+ outcome,
198
+ durationMs: elapsed(),
199
+ });
200
+ return stepped;
201
+ }
202
+ resolve(transitions, outcome, context) {
203
+ const target = transitions[outcome.type];
204
+ if (target === undefined)
205
+ panic(`The flow has no transition for outcome "${outcome.type}"`);
206
+ if (typeof target === 'string')
207
+ return target;
208
+ const match = target.find((entry) => !entry.when || entry.when(context));
209
+ if (!match)
210
+ panic(`The flow has no transition for outcome "${outcome.type}"`);
211
+ return match.to;
212
+ }
213
+ async advancePhase(node, state) {
214
+ return Result.gen(async function* () {
215
+ const at = { phase: state.phase };
216
+ const attempted = yield* Result.await(this.attempt(at, state.runId, () => node.step({
217
+ state,
218
+ ports: this.dependencies.ports,
219
+ settings: this.dependencies.settings,
220
+ })));
221
+ if ('blockedReason' in attempted)
222
+ return Result.ok(attempted);
223
+ const { outcome } = attempted;
224
+ const applied = applyOutcome(state, outcome);
225
+ const next = this.resolve(node.on, outcome, {
226
+ state: applied,
227
+ settings: this.dependencies.settings,
228
+ });
229
+ return Result.ok({ state: this.changePhase(applied, next, state.phase) });
230
+ }, this);
231
+ }
232
+ async block(state, reason) {
233
+ const blocked = { ...state, blockedReason: reason };
234
+ const saved = await this.dependencies.store.save(blocked);
235
+ if (saved.isErr())
236
+ return saved;
237
+ this.dependencies.events.publish({
238
+ type: 'runBlocked',
239
+ runId: state.runId,
240
+ phase: state.phase,
241
+ reason,
242
+ });
243
+ return Result.ok({ state: blocked, status: 'blocked', reason });
244
+ }
245
+ publishRunFailed(state, reason) {
246
+ this.dependencies.events.publish({
247
+ type: 'runFailed',
248
+ runId: state.runId,
249
+ phase: state.phase,
250
+ reason,
251
+ });
252
+ }
253
+ }
254
+ /** A guard against a flow that never settles; every healthy pass moves a phase or a slice forward. */
255
+ const MAX_PASSES = 1000;
@@ -0,0 +1,129 @@
1
+ import { designApproved, designNeedsRevision } from '../domain/design-review.js';
2
+ import { finalCheckFailed, finalCheckNeedsRepair } from '../domain/final-check.js';
3
+ import { stuckSlice } from '../domain/run-state.js';
4
+ import { emptyAttemptCapReached, hookFailureCapReached, reviewCapReached, ruleFixCapReached, sliceNeedsVerification, verificationFailureCapReached, } from '../domain/settings.js';
5
+ import { decideCompletionReuse } from '../steps/completion-reuse.js';
6
+ import { resolveDesign, reviewDesign, reviseDesign } from '../steps/design-review.js';
7
+ import { checkWholeRun } from '../steps/final-check.js';
8
+ import { describePullRequest, mergeRunBranch } from '../steps/finishing.js';
9
+ import { applyDesignGate, buildContext, planFeature, sliceThePlan, writeDesign, } from '../steps/planning.js';
10
+ import { implementSlice, reviewSlice, verifySlice } from '../steps/slice.js';
11
+ import { defineRunFlow, defineSliceFlow } from './define-flow.js';
12
+ const designPassedReview = ({ state }) => designApproved(state);
13
+ const designOwesRevision = ({ state }) => designNeedsRevision(state);
14
+ const sliceReachedHookFailureCap = ({ slice }) => slice !== undefined && hookFailureCapReached(slice);
15
+ const sliceReachedEmptyAttemptCap = ({ slice }) => slice !== undefined && emptyAttemptCapReached(slice);
16
+ const retryUnlessEmptyAttemptsCapped = [
17
+ { to: 'stuck', when: sliceReachedEmptyAttemptCap },
18
+ { to: 'pending' },
19
+ ];
20
+ const sliceReachedVerificationFailureCap = ({ slice }) => slice !== undefined && verificationFailureCapReached(slice);
21
+ const sliceAwaitsVerification = ({ slice, settings }) => slice !== undefined && sliceNeedsVerification(slice, settings);
22
+ const sliceReachedReviewCap = ({ slice, settings }) => slice !== undefined && reviewCapReached(slice, settings);
23
+ const backToImplementUnlessCapped = [
24
+ { to: 'stuck', when: sliceReachedReviewCap },
25
+ { to: 'pending' },
26
+ ];
27
+ const sliceReachedRuleFixCap = ({ slice }) => slice !== undefined && ruleFixCapReached(slice);
28
+ const backToImplementUnlessRuleFixesCapped = [
29
+ { to: 'stuck', when: sliceReachedRuleFixCap },
30
+ { to: 'pending' },
31
+ ];
32
+ /** One slice: implement it, verify it, have it reviewed — and loop back on any requested change. */
33
+ export const sliceFlow = defineSliceFlow({
34
+ pending: {
35
+ step: implementSlice,
36
+ on: {
37
+ implemented: 'verifying',
38
+ hookRejected: [{ to: 'stuck', when: sliceReachedHookFailureCap }, { to: 'pending' }],
39
+ nothingChanged: retryUnlessEmptyAttemptsCapped,
40
+ },
41
+ },
42
+ verifying: {
43
+ step: verifySlice,
44
+ on: {
45
+ verified: 'in_review',
46
+ verificationFailed: [
47
+ { to: 'stuck', when: sliceReachedVerificationFailureCap },
48
+ { to: 'pending' },
49
+ ],
50
+ },
51
+ },
52
+ in_review: {
53
+ step: reviewSlice,
54
+ on: {
55
+ approved: [{ to: 'verifying', when: sliceAwaitsVerification }, { to: 'approved' }],
56
+ changesRequested: backToImplementUnlessCapped,
57
+ rulesFixRequested: backToImplementUnlessRuleFixesCapped,
58
+ },
59
+ },
60
+ approved: { final: 'done' },
61
+ stuck: { final: 'stuck' },
62
+ });
63
+ const repairStillOwed = ({ state }) => finalCheckNeedsRepair(state);
64
+ const someSliceStuck = ({ state }) => stuckSlice(state) !== undefined;
65
+ const theFinalCheckFailed = ({ state }) => finalCheckFailed(state);
66
+ /**
67
+ * A whole run: plan the work, have the design reviewed — with one revision and one re-review
68
+ * when the review finds problems, blocking on any left standing — then deliver it slice by
69
+ * slice, check the whole request is fulfilled, describe it, merge it. A stuck slice bypasses the final check; a failed one sends its one
70
+ * repair back through the slices before the run is described and, still failing, stops for a
71
+ * person — so the feedback reaches whoever picks it up. A single-slice run whose combined review
72
+ * still vouches for its work finishes on that review instead of a final check; should the
73
+ * evidence stop holding before the run merges or waits for a merge, the run falls back to an
74
+ * ordinary final check with its repair still owed.
75
+ */
76
+ export const runFlow = defineRunFlow({
77
+ context: { step: buildContext, on: { contextBuilt: 'planning' } },
78
+ planning: { step: planFeature, on: { featurePlanned: 'designing' } },
79
+ designing: { step: writeDesign, on: { designWritten: 'reviewingDesign' } },
80
+ reviewingDesign: {
81
+ step: reviewDesign,
82
+ on: {
83
+ designReviewed: [
84
+ { to: 'slicing', when: designPassedReview },
85
+ { to: 'revisingDesign', when: designOwesRevision },
86
+ { to: 'resolvingDesign' },
87
+ ],
88
+ },
89
+ },
90
+ revisingDesign: { step: reviseDesign, on: { designRevised: 'reviewingDesign' } },
91
+ resolvingDesign: { step: resolveDesign, on: { continue: 'slicing' } },
92
+ slicing: { step: sliceThePlan, on: { sliced: 'gate' } },
93
+ gate: { step: applyDesignGate, on: { continue: 'slices', pause: 'paused' } },
94
+ paused: { halt: true, resumeAt: 'slices' },
95
+ slices: {
96
+ forEachSlice: sliceFlow,
97
+ on: { allApproved: 'checkingReuse', sliceStuck: 'describing' },
98
+ },
99
+ checkingReuse: {
100
+ step: decideCompletionReuse,
101
+ on: { completionReused: 'describing', completionDeclined: 'finalCheck' },
102
+ },
103
+ finalCheck: {
104
+ step: checkWholeRun,
105
+ on: { finalChecked: [{ to: 'slices', when: repairStillOwed }, { to: 'describing' }] },
106
+ },
107
+ describing: {
108
+ step: describePullRequest,
109
+ on: {
110
+ completionInvalidated: 'finalCheck',
111
+ described: [
112
+ { to: 'stuck', when: someSliceStuck },
113
+ { to: 'stuck', when: theFinalCheckFailed },
114
+ { to: 'merging' },
115
+ ],
116
+ },
117
+ },
118
+ merging: {
119
+ step: mergeRunBranch,
120
+ on: {
121
+ merged: 'done',
122
+ awaitingManualMerge: 'awaitingMerge',
123
+ completionInvalidated: 'finalCheck',
124
+ },
125
+ },
126
+ awaitingMerge: { halt: true, resumeAt: 'merging' },
127
+ done: { final: 'done' },
128
+ stuck: { final: 'stuck' },
129
+ });
@@ -0,0 +1,26 @@
1
+ import { Result } from 'better-result';
2
+ import { ConfigInvalid } from '../domain/errors.js';
3
+ import { gitCommand, openRepo } from './repository.js';
4
+ export async function getCurrentBranch(cwd) {
5
+ const status = await gitCommand('status', () => openRepo(cwd).status());
6
+ if (status.isErr()) {
7
+ return Result.err(new ConfigInvalid({
8
+ message: `Cannot tell which branch is checked out in ${cwd}: ${status.error.output}`,
9
+ }));
10
+ }
11
+ if (!status.value.current || status.value.detached) {
12
+ return Result.err(new ConfigInvalid({
13
+ message: `${cwd} has no branch checked out — check out the branch the run should start from.`,
14
+ }));
15
+ }
16
+ return Result.ok(status.value.current);
17
+ }
18
+ /** Removes a local branch, merged or not; one that is already gone is left alone. */
19
+ export function deleteBranch(cwd, name) {
20
+ return gitCommand('branch -D', async () => {
21
+ const git = openRepo(cwd);
22
+ const { all } = await git.branchLocal();
23
+ if (all.includes(name))
24
+ await git.deleteLocalBranch(name, true);
25
+ });
26
+ }
@@ -0,0 +1,92 @@
1
+ import { Result } from 'better-result';
2
+ import { execa } from 'execa';
3
+ import { GitCommandFailed, MergeFailed, messageOf, RemoteUnavailable } from '../domain/errors.js';
4
+ import { getCurrentBranch } from './branch.js';
5
+ import { gitCommand, isWorkingTreeClean, openRepoWithoutHooks } from './repository.js';
6
+ /**
7
+ * The branch's changes are in `intoBranch` when merging it there would leave the tree as it is,
8
+ * which holds after a plain, a squash or a rebase merge alike. A branch with no commits of its own
9
+ * has nothing left to land, so it counts as merged. When `intoBranch` tracks a remote, the remote's
10
+ * copy is fetched and checked too, so a merge done on the host is seen before anyone pulls it.
11
+ */
12
+ export async function isBranchMergedInto(repoRoot, branchName, intoBranch) {
13
+ return Result.gen(async function* () {
14
+ if (yield* Result.await(mergeLeavesTreeAsIs(repoRoot, branchName, intoBranch))) {
15
+ return Result.ok(true);
16
+ }
17
+ const upstream = yield* Result.await(fetchUpstreamOf(repoRoot, intoBranch));
18
+ if (upstream === undefined)
19
+ return Result.ok(false);
20
+ return Result.ok(yield* Result.await(mergeLeavesTreeAsIs(repoRoot, branchName, upstream)));
21
+ });
22
+ }
23
+ async function mergeLeavesTreeAsIs(repoRoot, branchName, intoRef) {
24
+ const merged = await git(repoRoot, ['merge-tree', '--write-tree', intoRef, branchName]);
25
+ if (wouldConflict(merged))
26
+ return Result.ok(false);
27
+ const mergeOutput = succeeded(merged);
28
+ if (mergeOutput.isErr())
29
+ return mergeOutput;
30
+ const [mergedTree] = mergeOutput.value.split('\n');
31
+ const baseTree = succeeded(await git(repoRoot, ['rev-parse', `${intoRef}^{tree}`]));
32
+ return baseTree.map((tree) => mergedTree === tree);
33
+ }
34
+ function git(cwd, args) {
35
+ return execa('git', args, { cwd, reject: false });
36
+ }
37
+ /** `git merge-tree` exits with 1 both on conflicts and on errors; only a conflict still writes a tree. */
38
+ function wouldConflict(merged) {
39
+ return merged.exitCode === 1 && merged.stdout !== '';
40
+ }
41
+ function succeeded(result) {
42
+ if (result.exitCode === 0)
43
+ return Result.ok(result.stdout.trim());
44
+ return Result.err(new GitCommandFailed({
45
+ message: `${result.command} failed: ${result.stderr}`,
46
+ command: result.command,
47
+ output: result.stderr,
48
+ }));
49
+ }
50
+ /** The ref of the branch's upstream after fetching it, or undefined when it tracks nothing. */
51
+ async function fetchUpstreamOf(repoRoot, branch) {
52
+ const remote = await git(repoRoot, ['config', '--get', `branch.${branch}.remote`]);
53
+ if (remote.exitCode === CONFIG_KEY_MISSING)
54
+ return Result.ok(undefined);
55
+ const remoteName = succeeded(remote);
56
+ if (remoteName.isErr())
57
+ return remoteName;
58
+ const mergeRef = succeeded(await git(repoRoot, ['config', '--get', `branch.${branch}.merge`]));
59
+ if (mergeRef.isErr())
60
+ return mergeRef;
61
+ const fetched = await git(repoRoot, ['fetch', '--quiet', remoteName.value, mergeRef.value]);
62
+ if (fetched.exitCode !== 0) {
63
+ return Result.err(new RemoteUnavailable({
64
+ message: `Fetching the upstream of "${branch}" failed: ${fetched.stderr}`,
65
+ }));
66
+ }
67
+ return Result.ok(`${branch}@{upstream}`);
68
+ }
69
+ /** `git config --get` exits with this when the key is not set. */
70
+ const CONFIG_KEY_MISSING = 1;
71
+ export async function mergeBranchInto(repoRoot, branchName, intoBranch, { sign = false } = {}) {
72
+ return Result.gen(async function* () {
73
+ const currentBranch = yield* Result.await(getCurrentBranch(repoRoot).then((branch) => branch.mapError(asMergeFailed)));
74
+ if (currentBranch !== intoBranch) {
75
+ return Result.err(new MergeFailed({
76
+ message: `Refusing to merge: "${intoBranch}" is not checked out in ${repoRoot} (found "${currentBranch}")`,
77
+ }));
78
+ }
79
+ if (!(yield* Result.await(isWorkingTreeClean(repoRoot)))) {
80
+ return Result.err(new MergeFailed({ message: `Refusing to merge: ${repoRoot} has uncommitted changes` }));
81
+ }
82
+ const git = openRepoWithoutHooks(repoRoot, sign ? [] : ['commit.gpgsign=false']);
83
+ yield* Result.await(Result.tryPromise({
84
+ try: () => git.merge([branchName, '--no-edit', ...(sign ? ['--gpg-sign'] : [])]),
85
+ catch: (error) => new MergeFailed({ message: messageOf(error) }),
86
+ }));
87
+ return Result.ok(yield* Result.await(gitCommand('rev-parse', async () => (await git.revparse(['HEAD'])).trim())));
88
+ });
89
+ }
90
+ function asMergeFailed(error) {
91
+ return new MergeFailed({ message: error.message });
92
+ }
@@ -0,0 +1,48 @@
1
+ import { Result } from 'better-result';
2
+ import { realpath } from 'node:fs/promises';
3
+ import { simpleGit } from 'simple-git';
4
+ import { ConfigInvalid, GitCommandFailed, messageOf } from '../domain/errors.js';
5
+ /**
6
+ * For a merge on the host: a hook can run what the branch just brought in, before anyone read it,
7
+ * whether a tracked `post-merge` script or an install that runs a new `postinstall`. simple-git
8
+ * guards this setting against untrusted values; this one is fixed and only turns hooks off.
9
+ */
10
+ export function openRepoWithoutHooks(cwd, config = []) {
11
+ return simpleGit({
12
+ baseDir: cwd,
13
+ config: ['core.hooksPath=/dev/null', ...config],
14
+ unsafe: { allowUnsafeHooksPath: true },
15
+ });
16
+ }
17
+ export function isWorkingTreeClean(cwd) {
18
+ return gitCommand('status', async () => (await openRepo(cwd).status()).isClean());
19
+ }
20
+ /** Runs simple-git work, returning whatever it throws as a failed git command. */
21
+ export function gitCommand(command, run) {
22
+ return Result.tryPromise({
23
+ try: run,
24
+ catch: (error) => new GitCommandFailed({
25
+ message: `git ${command} failed: ${messageOf(error)}`,
26
+ command: `git ${command}`,
27
+ output: messageOf(error),
28
+ }),
29
+ });
30
+ }
31
+ export function openRepo(cwd) {
32
+ return simpleGit({ baseDir: cwd });
33
+ }
34
+ /**
35
+ * jig works on the repository in the directory it was started in. Started further down, it would
36
+ * miss the config and hand the sandbox no git directory, so that is refused; a directory that is
37
+ * not a repository yet is left for `init` and git itself to judge.
38
+ */
39
+ export async function ensureRepositoryRoot(cwd) {
40
+ const root = await openRepo(cwd)
41
+ .revparse(['--show-toplevel'])
42
+ .catch(() => undefined);
43
+ if (root === undefined || root === (await realpath(cwd)))
44
+ return Result.ok();
45
+ return Result.err(new ConfigInvalid({
46
+ message: `Run jig from the repository's root, ${root} — not from ${cwd}.`,
47
+ }));
48
+ }
@@ -0,0 +1,64 @@
1
+ import { execaSync } from 'execa';
2
+ import { constants } from 'node:os';
3
+ import { deleteBranch } from './branch.js';
4
+ import { gitCommand, openRepo } from './repository.js';
5
+ /**
6
+ * Runs `use`, and removes `branch` and any worktree on it if the process exits first. A signal
7
+ * otherwise ends the process without running `finally`, and sandcastle keeps the worktree on
8
+ * purpose, for a run that can resume; a throwaway branch has nothing to resume. Removing them once
9
+ * `use` finishes is the caller's job (`discardBranch`), where a failure can be reported.
10
+ */
11
+ export async function discardBranchOnExit(cwd, branch, use, host = process) {
12
+ const discard = () => discardBranchNow(cwd, branch);
13
+ const exitOnSignal = (signal) => host.exit(128 + constants.signals[signal]);
14
+ host.on('exit', discard);
15
+ for (const signal of EXIT_SIGNALS)
16
+ host.on(signal, exitOnSignal);
17
+ try {
18
+ return await use();
19
+ }
20
+ finally {
21
+ host.off('exit', discard);
22
+ for (const signal of EXIT_SIGNALS)
23
+ host.off(signal, exitOnSignal);
24
+ }
25
+ }
26
+ /** Synchronous, because an `exit` listener cannot wait; nothing is left to report a failure to. */
27
+ function discardBranchNow(cwd, branch) {
28
+ const listed = execaSync('git', ['worktree', 'list', '--porcelain'], { cwd, reject: false });
29
+ for (const worktree of worktreesOn(String(listed.stdout), branch)) {
30
+ execaSync('git', ['worktree', 'remove', '--force', worktree], { cwd, reject: false });
31
+ }
32
+ execaSync('git', ['branch', '-D', branch], { cwd, reject: false });
33
+ }
34
+ function worktreesOn(porcelain, branch) {
35
+ return porcelain.split('\n\n').flatMap((entry) => {
36
+ const lines = entry.split('\n');
37
+ const worktree = lines.find((line) => line.startsWith('worktree '))?.slice('worktree '.length);
38
+ return worktree && lines.includes(`branch refs/heads/${branch}`) ? [worktree] : [];
39
+ });
40
+ }
41
+ /**
42
+ * Exiting from a signal is what fires `exit`; without a listener of its own, Ctrl+C before
43
+ * sandcastle registers one would kill the process without it.
44
+ */
45
+ const EXIT_SIGNALS = ['SIGINT', 'SIGTERM'];
46
+ /**
47
+ * Removes `branch` with any worktree still on it: a sandbox's close leaves its worktree in
48
+ * place when the run left uncommitted changes there or when removing it failed, and git
49
+ * refuses to delete a branch a worktree is on.
50
+ */
51
+ export async function discardBranch(cwd, branch) {
52
+ const removed = await removeWorktreesOn(cwd, branch);
53
+ if (removed.isErr())
54
+ return removed;
55
+ return deleteBranch(cwd, branch);
56
+ }
57
+ async function removeWorktreesOn(cwd, branch) {
58
+ return gitCommand('worktree remove', async () => {
59
+ const listed = String(await openRepo(cwd).raw(['worktree', 'list', '--porcelain']));
60
+ for (const worktree of worktreesOn(listed, branch)) {
61
+ await openRepo(cwd).raw(['worktree', 'remove', '--force', worktree]);
62
+ }
63
+ });
64
+ }
@@ -0,0 +1,51 @@
1
+ /** Turns run events into log lines: a readable message, with the event's data as fields. */
2
+ export class LoggingObserver {
3
+ logger;
4
+ constructor(logger) {
5
+ this.logger = logger;
6
+ }
7
+ handle(event) {
8
+ const { type, ...fields } = event;
9
+ const log = this.logger.child({ event: type });
10
+ switch (event.type) {
11
+ case 'stepStarted':
12
+ return log.info(fields, `${describe(event.at)}…`);
13
+ case 'stepFinished':
14
+ return log.info(fields, `${describe(event.at)} → ${event.outcome.type} (${seconds(event.durationMs)})`);
15
+ case 'stepFailed':
16
+ return log.debug(fields, `${describe(event.at)} failed (${seconds(event.durationMs)}): ${event.reason}`);
17
+ case 'stepRetried':
18
+ return log.warn(fields, `${describe(event.at)} failed, retrying (attempt ${event.attempt}): ${event.reason}`);
19
+ case 'phaseChanged':
20
+ return log.debug(fields, `${event.from} → ${event.to}`);
21
+ case 'sliceStatusChanged':
22
+ return log.info(fields, `slice ${event.sliceId}: ${event.from} → ${event.to}`);
23
+ case 'agentMessage':
24
+ return log.debug(fields, `${event.role}: ${event.text}`);
25
+ case 'agentToolCall':
26
+ return log.info(fields, `${event.role} → ${event.tool} ${event.args}`);
27
+ default:
28
+ return logRunLifecycle(log, event, fields);
29
+ }
30
+ }
31
+ }
32
+ function describe(at) {
33
+ return at.sliceId !== undefined ? `${at.sliceStatus} slice ${at.sliceId}` : at.phase;
34
+ }
35
+ function seconds(durationMs) {
36
+ return `${(durationMs / 1000).toFixed(1)}s`;
37
+ }
38
+ function logRunLifecycle(log, event, fields) {
39
+ switch (event.type) {
40
+ case 'runResumed':
41
+ return log.info(fields, `run ${event.runId} at ${event.phase}`);
42
+ case 'runHalted':
43
+ return log.info(fields, `run ${event.runId} waiting at ${event.phase}`);
44
+ case 'runBlocked':
45
+ return log.error(fields, `run ${event.runId} blocked at ${event.phase}: ${event.reason}`);
46
+ case 'runFinished':
47
+ return log.info(fields, `run ${event.runId} finished: ${event.phase}`);
48
+ case 'runFailed':
49
+ return log.error(fields, `run ${event.runId} failed at ${event.phase}: ${event.reason}`);
50
+ }
51
+ }