@ygrishajev/jig 1.0.5 → 1.2.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 (41) hide show
  1. package/README.md +16 -0
  2. package/dist/adapters/git/remote-ref.js +125 -0
  3. package/dist/adapters/git/run-code.js +66 -0
  4. package/dist/adapters/git/run-history.js +79 -0
  5. package/dist/adapters/local-store/run-artefacts.js +2 -1
  6. package/dist/adapters/run-store/composite-run-store.js +68 -14
  7. package/dist/adapters/run-store/git-remote-run-store.js +34 -129
  8. package/dist/app/run-jig.js +28 -7
  9. package/dist/app/run-stores.js +4 -3
  10. package/dist/cli/commands/run.js +20 -7
  11. package/dist/cli/commands/status.js +3 -0
  12. package/dist/cli/main.js +3 -15
  13. package/dist/domain/apply-outcome.js +30 -13
  14. package/dist/domain/diagnostics.js +104 -0
  15. package/dist/domain/errors.js +8 -0
  16. package/dist/domain/final-check.js +21 -1
  17. package/dist/domain/run-id.js +4 -1
  18. package/dist/domain/run-state.js +51 -2
  19. package/dist/domain/slice.js +8 -2
  20. package/dist/flow/engine.js +4 -0
  21. package/dist/flow/run-flow.js +6 -2
  22. package/dist/integrations/github/cli.js +20 -0
  23. package/dist/integrations/github/command.js +68 -0
  24. package/dist/integrations/github/errors.js +19 -0
  25. package/dist/integrations/github/findings-comment.js +53 -0
  26. package/dist/integrations/github/github-port.js +1 -0
  27. package/dist/integrations/github/implement-issue.js +281 -0
  28. package/dist/integrations/github/octokit-github.js +101 -0
  29. package/dist/integrations/github/orchestration-state.js +132 -0
  30. package/dist/integrations/github/orchestration-store.js +109 -0
  31. package/dist/integrations/github/repository-identity.js +27 -0
  32. package/dist/integrations/github/request-snapshot.js +3 -0
  33. package/dist/integrations/github/run-branch-publication.js +102 -0
  34. package/dist/ports/run-code.js +1 -0
  35. package/dist/prompts/design-review.js +2 -0
  36. package/dist/prompts/planning.js +5 -1
  37. package/dist/prompts/pull-request.js +4 -1
  38. package/dist/prompts/slice.js +11 -0
  39. package/dist/steps/pull-request-description.js +1 -1
  40. package/dist/steps/slice.js +1 -0
  41. package/package.json +5 -4
@@ -1,22 +1,24 @@
1
1
  import { Result } from 'better-result';
2
- import { execa } from 'execa';
3
- import { ConfigInvalid, GitCommandFailed, messageOf, RemoteUnavailable, RunStateConflict, } from '../../domain/errors.js';
4
- import { retryResult } from '../../domain/retry.js';
5
- import { runBranchFor, runStateSchema } from '../../domain/run-state.js';
2
+ import { ConfigInvalid, messageOf, RunStateConflict, } from '../../domain/errors.js';
3
+ import { defersCodePublication, runBranchFor, runStateSchema, } from '../../domain/run-state.js';
4
+ import { RemoteRef } from '../git/remote-ref.js';
6
5
  import { isAncestor } from '../git/repository.js';
7
6
  /**
8
7
  * Keeps each run's state as a commit on a hidden `refs/jig/<runId>` ref and pushes it, with the
9
8
  * run branch, to a remote — so another machine, such as a retried CI job, can resume the run.
10
9
  * The hidden ref keeps state commits out of the repository's branch list. A save only replaces
11
10
  * what this store last saw on the remote, so a concurrent writer is refused rather than overwritten.
11
+ * A run that defers its code publication pushes its state alone: the branch stays on this clone.
12
12
  */
13
13
  export class GitRemoteRunStore {
14
14
  repoRoot;
15
15
  remote;
16
16
  seenOnRemote = new Map();
17
+ refs;
17
18
  constructor(repoRoot, remote = 'origin') {
18
19
  this.repoRoot = repoRoot;
19
20
  this.remote = remote;
21
+ this.refs = new RemoteRef(repoRoot, remote);
20
22
  }
21
23
  load(runId) {
22
24
  return Result.gen(async function* () {
@@ -26,88 +28,39 @@ export class GitRemoteRunStore {
26
28
  return Result.ok(undefined);
27
29
  if (remoteRun.branch)
28
30
  yield* Result.await(this.catchUpRunBranch(runId, remoteRun.branch));
29
- const shown = yield* Result.await(this.required(['show', `${stateRef(runId)}:${STATE_FILE}`]));
31
+ const shown = yield* Result.await(this.refs.required(['show', `${stateRef(runId)}:${STATE_FILE}`]));
30
32
  return parseState(shown, this.remote);
31
33
  }, this);
32
34
  }
33
35
  /** Brings the run's refs over from the remote; the run branch lands on a remote-tracking ref. */
34
36
  fetchRun(runId) {
35
37
  return Result.gen(async function* () {
36
- const refsOnRemote = yield* Result.await(this.listOnRemote(runId));
38
+ const refsOnRemote = yield* Result.await(this.refs.list([stateRef(runId), branchRef(runId)]));
37
39
  if (!refsOnRemote.has(stateRef(runId)))
38
40
  return Result.ok({});
39
41
  const hasBranch = refsOnRemote.has(branchRef(runId));
40
- yield* Result.await(this.remoteCall([
41
- 'fetch',
42
- '--quiet',
43
- this.remote,
42
+ yield* Result.await(this.refs.fetch([
44
43
  `+${stateRef(runId)}:${stateRef(runId)}`,
45
44
  ...(hasBranch ? [`+${branchRef(runId)}:${this.trackingRef(runId)}`] : []),
46
45
  ]));
47
46
  return Result.ok({
48
- state: await this.revision(stateRef(runId)),
49
- branch: hasBranch ? await this.revision(this.trackingRef(runId)) : undefined,
47
+ state: await this.refs.revision(stateRef(runId)),
48
+ branch: hasBranch ? await this.refs.revision(this.trackingRef(runId)) : undefined,
50
49
  });
51
50
  }, this);
52
51
  }
53
- /** The run's refs on the remote, each with the commit it points at. */
54
- async listOnRemote(runId) {
55
- const listed = await this.remoteCall(['ls-remote', '--exit-code', this.remote, stateRef(runId), branchRef(runId)], NO_MATCHING_REFS);
56
- return listed.map((output) => {
57
- const entries = output.stdout
58
- .split('\n')
59
- .filter(Boolean)
60
- .map((line) => {
61
- const [commit = '', ref = ''] = line.split('\t');
62
- return [ref, commit];
63
- });
64
- return new Map(entries);
65
- });
66
- }
67
- /** A remote operation, retried while the failure looks like the network rather than a conflict. */
68
- remoteCall(args, alsoAcceptedExitCode) {
69
- return retryResult(async () => {
70
- const result = await this.git(args);
71
- if (result.exitCode === 0 || result.exitCode === alsoAcceptedExitCode) {
72
- return Result.ok(result);
73
- }
74
- return Result.err(isLeaseRejection(result.stderr)
75
- ? new RunStateConflict({
76
- message: `The run's state on ${this.remote} moved since it was loaded: ${result.stderr}`,
77
- })
78
- : new RemoteUnavailable({
79
- message: `git ${args[0]} to ${this.remote} failed: ${result.stderr}`,
80
- }));
81
- }, {
82
- retries: REMOTE_RETRIES,
83
- delayMs: REMOTE_RETRY_DELAY_MS,
84
- shouldRetry: (error) => error._tag === 'RemoteUnavailable',
85
- });
86
- }
87
- git(args, input) {
88
- return execa('git', args, {
89
- cwd: this.repoRoot,
90
- input,
91
- reject: false,
92
- env: COMMITTER,
93
- });
94
- }
95
52
  trackingRef(runId) {
96
53
  return `refs/remotes/${this.remote}/${runBranchFor(runId)}`;
97
54
  }
98
- async revision(ref) {
99
- const parsed = await this.git(['rev-parse', '--verify', '--quiet', ref]);
100
- return parsed.exitCode === 0 ? parsed.stdout.trim() : undefined;
101
- }
102
55
  /**
103
56
  * Moves the local run branch to the remote's when it is behind, keeps it when it is ahead with
104
57
  * commits not pushed yet, and refuses when the two have diverged.
105
58
  */
106
59
  catchUpRunBranch(runId, remoteHead) {
107
60
  return Result.gen(async function* () {
108
- const local = await this.revision(branchRef(runId));
61
+ const local = await this.refs.revision(branchRef(runId));
109
62
  if (!local) {
110
- return (await this.required(['update-ref', branchRef(runId), remoteHead, ''])).map(() => undefined);
63
+ return (await this.refs.required(['update-ref', branchRef(runId), remoteHead, ''])).map(() => undefined);
111
64
  }
112
65
  const remoteIsAncestor = yield* Result.await(isAncestor(this.repoRoot, remoteHead, local));
113
66
  if (remoteIsAncestor)
@@ -121,28 +74,18 @@ export class GitRemoteRunStore {
121
74
  return this.fastForward(runId, local, remoteHead);
122
75
  }, this);
123
76
  }
124
- async required(args, input) {
125
- const result = await this.git(args, input);
126
- if (result.exitCode === 0)
127
- return Result.ok(result.stdout.trim());
128
- return Result.err(new GitCommandFailed({
129
- message: `git ${args[0]} failed on the run's state: ${result.stderr}`,
130
- command: `git ${args.join(' ')}`,
131
- output: result.stderr,
132
- }));
133
- }
134
77
  /** Git refuses to move a branch a worktree has checked out, so that worktree is moved instead. */
135
78
  async fastForward(runId, from, to) {
136
79
  const worktree = await this.worktreeWithCheckedOut(branchRef(runId));
137
80
  if (worktree.isErr())
138
81
  return Result.err(worktree.error);
139
82
  const moved = worktree.value
140
- ? await this.required(['-C', worktree.value, 'merge', '--ff-only', '--quiet', to])
141
- : await this.required(['update-ref', branchRef(runId), to, from]);
83
+ ? await this.refs.required(['-C', worktree.value, 'merge', '--ff-only', '--quiet', to])
84
+ : await this.refs.required(['update-ref', branchRef(runId), to, from]);
142
85
  return moved.map(() => undefined);
143
86
  }
144
87
  async worktreeWithCheckedOut(ref) {
145
- const listed = await this.required(['worktree', 'list', '--porcelain']);
88
+ const listed = await this.refs.required(['worktree', 'list', '--porcelain']);
146
89
  return listed.map((output) => {
147
90
  const entry = output
148
91
  .split('\n\n')
@@ -154,57 +97,36 @@ export class GitRemoteRunStore {
154
97
  /** Reads the remote's copy without creating or moving a ref here, not even FETCH_HEAD. */
155
98
  peek(runId) {
156
99
  return Result.gen(async function* () {
157
- const listed = yield* Result.await(this.listOnRemote(runId));
158
- const stateCommit = listed.get(stateRef(runId));
159
- if (!stateCommit)
100
+ const files = yield* Result.await(this.refs.peek(stateRef(runId)));
101
+ if (!files)
160
102
  return Result.ok(undefined);
161
- yield* Result.await(this.remoteCall([
162
- 'fetch',
163
- '--quiet',
164
- '--no-write-fetch-head',
165
- this.remote,
166
- stateRef(runId),
167
- ]));
168
- const shown = yield* Result.await(this.required(['show', `${stateCommit}:${STATE_FILE}`]));
103
+ const shown = files.get(STATE_FILE) ?? '';
169
104
  return parseState(shown, this.remote);
170
105
  }, this);
171
106
  }
172
107
  save(state) {
173
108
  return Result.gen(async function* () {
174
- const commit = yield* Result.await(this.commitState(state));
175
- const branch = await this.revision(branchRef(state.runId));
109
+ const commit = yield* Result.await(this.refs.commitFile(stateRef(state.runId), STATE_FILE, `${JSON.stringify(state, null, 2)}\n`, `jig run ${state.runId}: ${state.phase}`));
110
+ const branch = defersCodePublication(state)
111
+ ? undefined
112
+ : await this.refs.revision(branchRef(state.runId));
176
113
  const lease = this.seenOnRemote.get(state.runId) ?? {};
177
- yield* Result.await(this.remoteCall([
178
- 'push',
179
- '--quiet',
180
- '--atomic',
181
- `--force-with-lease=${stateRef(state.runId)}:${lease.state ?? ''}`,
182
- ...(branch ? [`--force-with-lease=${branchRef(state.runId)}:${lease.branch ?? ''}`] : []),
183
- this.remote,
184
- `${stateRef(state.runId)}:${stateRef(state.runId)}`,
185
- ...(branch ? [`${branchRef(state.runId)}:${branchRef(state.runId)}`] : []),
114
+ yield* Result.await(this.refs.pushLeased([
115
+ { ref: stateRef(state.runId), expected: lease.state, source: stateRef(state.runId) },
116
+ ...(branch
117
+ ? [
118
+ {
119
+ ref: branchRef(state.runId),
120
+ expected: lease.branch,
121
+ source: branchRef(state.runId),
122
+ },
123
+ ]
124
+ : []),
186
125
  ]));
187
126
  this.seenOnRemote.set(state.runId, { state: commit, branch: branch ?? lease.branch });
188
127
  return Result.ok();
189
128
  }, this);
190
129
  }
191
- commitState(state) {
192
- return Result.gen(async function* () {
193
- const ref = stateRef(state.runId);
194
- const blob = yield* Result.await(this.required(['hash-object', '-w', '--stdin'], `${JSON.stringify(state, null, 2)}\n`));
195
- const tree = yield* Result.await(this.required(['mktree'], `100644 blob ${blob}\t${STATE_FILE}\n`));
196
- const parent = await this.revision(ref);
197
- const commit = yield* Result.await(this.required([
198
- 'commit-tree',
199
- tree,
200
- ...(parent ? ['-p', parent] : []),
201
- '-m',
202
- `jig run ${state.runId}: ${state.phase}`,
203
- ]));
204
- yield* Result.await(this.required(['update-ref', ref, commit]));
205
- return Result.ok(commit);
206
- }, this);
207
- }
208
130
  }
209
131
  function stateRef(runId) {
210
132
  return `refs/jig/${runId}`;
@@ -221,20 +143,3 @@ function parseState(shown, remote) {
221
143
  function branchRef(runId) {
222
144
  return `refs/heads/${runBranchFor(runId)}`;
223
145
  }
224
- /** `git ls-remote --exit-code` exits with this when the remote has none of the refs asked for. */
225
- const NO_MATCHING_REFS = 2;
226
- /** Git reports a push whose lease no longer matches, or that is not a fast-forward, as rejected. */
227
- function isLeaseRejection(stderr) {
228
- return stderr.includes('[rejected]') || stderr.includes('stale info');
229
- }
230
- /** How many more times a fetch or push that failed on the network is tried. */
231
- const REMOTE_RETRIES = 3;
232
- /** The wait before the first retry; each one after it waits twice as long. */
233
- const REMOTE_RETRY_DELAY_MS = 1000;
234
- /** Identity for the state commits; they are jig's bookkeeping, not anyone's work. */
235
- const COMMITTER = {
236
- GIT_AUTHOR_NAME: 'jig',
237
- GIT_AUTHOR_EMAIL: 'jig@localhost',
238
- GIT_COMMITTER_NAME: 'jig',
239
- GIT_COMMITTER_EMAIL: 'jig@localhost',
240
- };
@@ -1,5 +1,6 @@
1
1
  import { Result } from 'better-result';
2
2
  import { getCurrentBranch } from '../adapters/git/branch.js';
3
+ import { exactHead } from '../adapters/git/run-history.js';
3
4
  import { MetricsLog } from '../adapters/local-store/metrics-log.js';
4
5
  import { lockRun } from '../adapters/local-store/run-lock.js';
5
6
  import { stepCredentials } from '../adapters/sandcastle/open-session.js';
@@ -35,11 +36,17 @@ function targetOf(input) {
35
36
  if ('resume' in input)
36
37
  return { runId: input.resume };
37
38
  const { start } = input;
38
- return { request: start.text, runId: input.runId ?? newRunId(start) };
39
+ return {
40
+ requiredStores: input.requiredStores,
41
+ request: start.text,
42
+ merge: start.merge,
43
+ codePublication: start.codePublication,
44
+ runId: input.runId ?? newRunId(start),
45
+ };
39
46
  }
40
47
  function runLocked(app, target) {
41
48
  return Result.gen(async function* () {
42
- const store = yield* Result.await(openRunStore(app.cradle));
49
+ const store = yield* Result.await(openRunStore(app.cradle, target.requiredStores));
43
50
  const state = yield* Result.await(startOrResume(app.cradle, store, target));
44
51
  for (const warning of validationWarnings(app.cradle.config))
45
52
  app.cradle.logger.warn(warning);
@@ -51,7 +58,7 @@ function runLocked(app, target) {
51
58
  return Result.ok(report);
52
59
  });
53
60
  }
54
- async function startOrResume(cradle, store, { runId, request }) {
61
+ async function startOrResume(cradle, store, { runId, request, merge, codePublication }) {
55
62
  const existing = await store.load(runId);
56
63
  if (existing.isErr())
57
64
  return Result.err(existing.error);
@@ -61,22 +68,36 @@ async function startOrResume(cradle, store, { runId, request }) {
61
68
  : Result.err(new RunRequestInvalid({ message: `No run found with id "${runId}".` }));
62
69
  }
63
70
  if (!existing.value)
64
- return startNewRun(cradle, store, runId, request);
71
+ return startNewRun(cradle, store, { runId, request, merge, codePublication });
65
72
  if (request !== existing.value.request) {
66
73
  return Result.err(new RunRequestInvalid({
67
74
  message: `Run "${runId}" was started from a different request — pass a new --id to start a new run.`,
68
75
  }));
69
76
  }
70
- return Result.ok(existing.value);
77
+ return Result.ok(adoptingCodePublication(existing.value, codePublication));
71
78
  }
72
- async function startNewRun(cradle, store, runId, request) {
79
+ async function startNewRun(cradle, store, input) {
73
80
  const baseBranch = await getCurrentBranch(cradle.repoRoot);
74
81
  if (baseBranch.isErr())
75
82
  return Result.err(baseBranch.error);
76
- const started = startRun({ runId, baseBranch: baseBranch.value, request });
83
+ const startingCommit = await exactHead(cradle.repoRoot, 'HEAD');
84
+ if (startingCommit.isErr())
85
+ return Result.err(startingCommit.error);
86
+ const started = startRun({
87
+ ...input,
88
+ baseBranch: baseBranch.value,
89
+ startingCommit: startingCommit.value,
90
+ });
77
91
  const saved = await store.save(started);
78
92
  return saved.isErr() ? Result.err(saved.error) : Result.ok(started);
79
93
  }
94
+ /**
95
+ * A run saved before it could defer its code keeps every recorded field, starting commit
96
+ * included, and defers from here on: what it already published stays, nothing more is pushed.
97
+ */
98
+ function adoptingCodePublication(state, codePublication) {
99
+ return codePublication && !state.codePublication ? { ...state, codePublication } : state;
100
+ }
80
101
  async function advance(app, store, state) {
81
102
  const credentials = stepCredentials(app.cradle.config, app.cradle.environment);
82
103
  if (credentials.isErr())
@@ -2,6 +2,7 @@ import { Result } from 'better-result';
2
2
  import path from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { z } from 'zod';
5
+ import { GitRunCode } from '../adapters/git/run-code.js';
5
6
  import { LocalRunStore } from '../adapters/local-store/local-run-store.js';
6
7
  import { CompositeRunStore } from '../adapters/run-store/composite-run-store.js';
7
8
  import { GitRemoteRunStore } from '../adapters/run-store/git-remote-run-store.js';
@@ -14,15 +15,15 @@ import { runStateSchema } from '../domain/run-state.js';
14
15
  * `.jig/<id>/state/` — `result.json`, `metrics.jsonl`, the logs and the markdown documents — is
15
16
  * this machine's record of the invocations it ran, not part of the run, and stays local.
16
17
  */
17
- export async function openRunStore({ repoRoot, config, }) {
18
+ export async function openRunStore({ repoRoot, config }, requiredStores = []) {
18
19
  const stores = [];
19
- for (const name of config.runStores) {
20
+ for (const name of new Set([...config.runStores, ...requiredStores])) {
20
21
  const store = await storeNamed(name, repoRoot);
21
22
  if (store.isErr())
22
23
  return Result.err(store.error);
23
24
  stores.push(store.value);
24
25
  }
25
- return Result.ok(new CompositeRunStore(stores));
26
+ return Result.ok(new CompositeRunStore(stores, new GitRunCode(repoRoot)));
26
27
  }
27
28
  async function storeNamed(name, repoRoot) {
28
29
  if (name === 'local')
@@ -13,6 +13,7 @@ export function registerRunCommand(program, io) {
13
13
  .description('Start a run from a request file (or - for standard input), or resume one with --id')
14
14
  .argument('[request]', 'markdown file describing what to build, or - to read it from standard input')
15
15
  .option('--id <id>', 'run id: resumes that run if it exists, otherwise names the new one')
16
+ .option('--no-merge', 'describe the result and stop without merging; the run ends "completed" (ignored when resuming an existing run)')
16
17
  .addOption(configOption())
17
18
  .addOption(presetOption())
18
19
  .addOption(logFormatOption())
@@ -33,9 +34,13 @@ const STANDARD_INPUT_ARGUMENT = '-';
33
34
  export const runInputSchema = logFormatInputSchema
34
35
  .merge(configInputSchema)
35
36
  .merge(presetInputSchema)
36
- .extend({ request: z.string().optional(), id: runIdSchema.optional() })
37
- .transform(({ request, id, ...options }, context) => {
38
- const run = runToDo(request, id);
37
+ .extend({
38
+ request: z.string().optional(),
39
+ id: runIdSchema.optional(),
40
+ merge: z.boolean().default(true),
41
+ })
42
+ .transform(({ request, id, merge, ...options }, context) => {
43
+ const run = runToDo(request, id, merge);
39
44
  if (run)
40
45
  return { run, ...options };
41
46
  context.addIssue({
@@ -44,10 +49,10 @@ export const runInputSchema = logFormatInputSchema
44
49
  });
45
50
  return z.NEVER;
46
51
  });
47
- function runToDo(request, id) {
52
+ function runToDo(request, id, merge) {
48
53
  if (request !== undefined) {
49
54
  const start = request === STANDARD_INPUT_ARGUMENT ? { stdin: true } : { file: request };
50
- return id ? { start, runId: id } : { start };
55
+ return id ? { start, runId: id, merge } : { start, merge };
51
56
  }
52
57
  if (id)
53
58
  return { resume: id };
@@ -59,6 +64,8 @@ export function nextStep(report) {
59
64
  switch (report.status) {
60
65
  case 'done':
61
66
  return 'Run complete.';
67
+ case 'completed':
68
+ return `Run finished without merging — review and merge "${runBranchFor(state.runId)}" yourself (its pull request description is in ${prDescriptionPath(state)}).`;
62
69
  case 'halted':
63
70
  return state.phase === 'paused'
64
71
  ? `Planning done — review the design and plan, then resume with: jig run --id ${state.runId}`
@@ -69,14 +76,20 @@ export function nextStep(report) {
69
76
  return stuckMessage(state);
70
77
  }
71
78
  }
79
+ function prDescriptionPath(state) {
80
+ return `.jig/${state.runId}/state/PR_DESCRIPTION.md`;
81
+ }
72
82
  function stuckMessage(state) {
73
83
  return (`Stuck: ${runStopReason(state) ?? 'the run exhausted its attempts'}, so jig has ended this run and will not resume it. ` +
74
- `Finish that slice and the rest by hand on "${runBranchFor(state.runId)}" (its pull request description is in .jig/${state.runId}/state/PR_DESCRIPTION.md), ` +
84
+ `Finish that slice and the rest by hand on "${runBranchFor(state.runId)}" (its pull request description is in ${prDescriptionPath(state)}), ` +
75
85
  `or start a new run with a sharper request. The failure feedback: jig status ${state.runId}`);
76
86
  }
77
87
  async function prepareRun({ run }, { cwd, standardInput }) {
78
88
  if ('resume' in run)
79
89
  return Result.ok(run);
80
90
  const start = await readRequest(run.start, { cwd, standardInput });
81
- return start.map((request) => run.runId ? { start: request, runId: run.runId } : { start: request });
91
+ return start.map((request) => {
92
+ const started = { ...request, merge: run.merge };
93
+ return run.runId ? { start: started, runId: run.runId } : { start: started };
94
+ });
82
95
  }
@@ -33,6 +33,9 @@ export function describeRun({ state, documents, metrics }) {
33
33
  return [
34
34
  `Run ${state.runId} — ${state.phase} (base: ${state.baseBranch})`,
35
35
  ...(state.blockedReason ? [`Blocked: ${state.blockedReason}`] : []),
36
+ ...(state.phase === 'completed'
37
+ ? [`Finished without merging — "${runBranchFor(state.runId)}" is ready for review.`]
38
+ : []),
36
39
  `${'branch'.padEnd(18)} ${runBranchFor(state.runId)}`,
37
40
  ...documents.map((document) => `${document.name.padEnd(18)} ${document.path}`),
38
41
  ...(slices.length > 0 ? ['Slices:', ...slices] : []),
package/dist/cli/main.js CHANGED
@@ -1,14 +1,10 @@
1
- #!/usr/bin/env node
2
1
  import { Command } from 'commander';
3
- import { readFileSync, realpathSync } from 'node:fs';
4
- import { fileURLToPath } from 'node:url';
2
+ import { readFileSync } from 'node:fs';
5
3
  import { z } from 'zod';
6
4
  import { registerPresetsCommand } from './commands/presets.js';
7
5
  import { registerRunCommand } from './commands/run.js';
8
6
  import { registerSandboxCommands } from './commands/sandbox.js';
9
7
  import { registerStatusCommand } from './commands/status.js';
10
- import { exitWhenDone } from './exit-when-done.js';
11
- const packageManifestSchema = z.object({ version: z.string() });
12
8
  export function buildCli() {
13
9
  const program = new Command();
14
10
  program.name('jig').description('Agentic SDLC pipeline orchestrator').version(packageVersion());
@@ -18,16 +14,8 @@ export function buildCli() {
18
14
  registerPresetsCommand(program);
19
15
  return program;
20
16
  }
21
- function packageVersion() {
17
+ export function packageVersion() {
22
18
  const manifest = new URL('../../package.json', import.meta.url);
23
19
  return packageManifestSchema.parse(JSON.parse(readFileSync(manifest, 'utf-8'))).version;
24
20
  }
25
- /**
26
- * A globally installed CLI is invoked through a symlink, so the invoked path is resolved
27
- * before comparing it with this module's own path.
28
- */
29
- const isMainModule = process.argv[1] !== undefined && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
30
- if (isMainModule) {
31
- await buildCli().parseAsync(process.argv);
32
- await exitWhenDone();
33
- }
21
+ const packageManifestSchema = z.object({ version: z.string() });
@@ -1,5 +1,6 @@
1
1
  import { panic } from 'better-result';
2
2
  import { recordDesignReview, recordDesignRevision } from './design-review.js';
3
+ import { captureOutput } from './diagnostics.js';
3
4
  import { recordFinalCheck } from './final-check.js';
4
5
  import { currentSlice, enterPhase } from './run-state.js';
5
6
  import { sliceFromPlan } from './slice.js';
@@ -31,20 +32,17 @@ const ATTEMPT_COUNTER_OF = {
31
32
  };
32
33
  function sendSliceBack(state, outcome) {
33
34
  const counter = ATTEMPT_COUNTER_OF[outcome.type];
34
- return withCompletionEvidence(updateCurrentSlice(state, (slice) => ({
35
+ const at = state.diagnosticSequence + 1;
36
+ const sentBack = updateCurrentSlice(state, (slice) => ({
35
37
  ...slice,
36
38
  [counter]: slice[counter] + 1,
37
39
  lastFeedback: outcome.feedback,
38
40
  feedbackHistory: [...slice.feedbackHistory, outcome.feedback],
39
41
  verification: undefined,
40
- failedVerification: failedVerificationOf(outcome, slice),
41
- })), outcome.completion);
42
- }
43
- /** The whole-request evidence a review leaves, kept as the run's record of its latest one. */
44
- function withCompletionEvidence(state, completion) {
45
- if (completion === undefined && state.completionReuse === undefined)
46
- return state;
47
- return { ...state, completionReuse: completion };
42
+ failedVerification: failedVerificationOf(outcome, slice, at),
43
+ rejectedReview: rejectedReviewOf(outcome, slice, at),
44
+ }));
45
+ return withCompletionEvidence({ ...sentBack, diagnosticSequence: at }, outcome.completion);
48
46
  }
49
47
  export function updateCurrentSlice(state, update) {
50
48
  const target = currentSlice(state);
@@ -59,14 +57,29 @@ export function updateCurrentSlice(state, update) {
59
57
  * The facts of the verification that just failed, beside the counter it spent; a failure that
60
58
  * recorded none leaves whatever earlier failure the slice already holds.
61
59
  */
62
- function failedVerificationOf(outcome, slice) {
60
+ function failedVerificationOf(outcome, slice, at) {
63
61
  if (outcome.type !== 'verificationFailed')
64
62
  return slice.failedVerification;
65
- const { command, observed } = outcome;
63
+ const { command, observed, output } = outcome;
66
64
  return command !== undefined && observed !== undefined
67
- ? { command, observed }
65
+ ? { command, observed, output: captureOutput(output), at, passedSince: false }
68
66
  : slice.failedVerification;
69
67
  }
68
+ /**
69
+ * The review changes the slice still owes: a rejection records its feedback, and the
70
+ * implementation and verification failures on the way to the next review leave it standing.
71
+ */
72
+ function rejectedReviewOf(outcome, slice, at) {
73
+ return outcome.type === 'changesRequested' || outcome.type === 'rulesFixRequested'
74
+ ? { feedback: outcome.feedback, at }
75
+ : slice.rejectedReview;
76
+ }
77
+ /** The whole-request evidence a review leaves, kept as the run's record of its latest one. */
78
+ function withCompletionEvidence(state, completion) {
79
+ if (completion === undefined && state.completionReuse === undefined)
80
+ return state;
81
+ return { ...state, completionReuse: completion };
82
+ }
70
83
  function isDesignOutcome(outcome) {
71
84
  return DESIGN_OUTCOME_TYPES.some((type) => type === outcome.type);
72
85
  }
@@ -111,7 +124,7 @@ function foldStepData(state, outcome) {
111
124
  case 'verified':
112
125
  return updateCurrentSlice(state, (slice) => verifiedSlice(slice, outcome));
113
126
  case 'approved':
114
- return withCompletionEvidence(state, outcome.completion);
127
+ return withCompletionEvidence(updateCurrentSlice(state, (slice) => ({ ...slice, rejectedReview: undefined })), outcome.completion);
115
128
  case 'finalChecked':
116
129
  return recordFinalCheck(state, outcome);
117
130
  case 'described':
@@ -125,6 +138,10 @@ function verifiedSlice(slice, outcome) {
125
138
  return {
126
139
  ...slice,
127
140
  lastFeedback: undefined,
141
+ failedVerification: slice.failedVerification && {
142
+ ...slice.failedVerification,
143
+ passedSince: true,
144
+ },
128
145
  verification: outcome.command
129
146
  ? { command: outcome.command, observed: outcome.observed }
130
147
  : undefined,
@@ -0,0 +1,104 @@
1
+ import { z } from 'zod';
2
+ export function captureOutput(output) {
3
+ if (output === undefined)
4
+ return OUTPUT_UNAVAILABLE;
5
+ const truncated = output.length > DIAGNOSTIC_OUTPUT_TAIL;
6
+ return {
7
+ captured: true,
8
+ tail: truncated ? output.slice(-DIAGNOSTIC_OUTPUT_TAIL) : output,
9
+ truncated,
10
+ };
11
+ }
12
+ export const OUTPUT_UNAVAILABLE = { captured: false };
13
+ /** How much of a failed command's output the run keeps, from its end, where failures report. */
14
+ export const DIAGNOSTIC_OUTPUT_TAIL = 3000;
15
+ /**
16
+ * Where a recorded failure falls among the run's others: the run's failure count when it was
17
+ * recorded. A failure saved before failures were counted loads as 0, earlier than any counted one.
18
+ */
19
+ export const diagnosticOrderSchema = z.number().int().nonnegative().default(0);
20
+ /** A review's requested changes, kept until a later review of the same slice approves it. */
21
+ export const rejectedReviewSchema = z.object({
22
+ feedback: z.string(),
23
+ at: diagnosticOrderSchema,
24
+ });
25
+ /**
26
+ * The tail of a failed command's output as a run keeps it, verbatim so the file and line
27
+ * references in it survive, or the admission that a run saved before output was kept has none.
28
+ */
29
+ export const capturedOutputSchema = z.discriminatedUnion('captured', [
30
+ z.object({ captured: z.literal(true), tail: z.string(), truncated: z.boolean() }),
31
+ z.object({ captured: z.literal(false) }),
32
+ ]);
33
+ /**
34
+ * The last whole-run verification that failed, kept after a later check passes so the run still
35
+ * shows what its repair addressed.
36
+ */
37
+ export const failedFinalVerificationSchema = z.object({
38
+ command: z.string().min(1).optional(),
39
+ output: capturedOutputSchema,
40
+ round: z.number().int().min(1),
41
+ at: diagnosticOrderSchema,
42
+ passedSince: z.boolean(),
43
+ });
44
+ export function runDiagnostics(state) {
45
+ return {
46
+ unresolvedReviews: state.slices.flatMap((slice) => slice.rejectedReview ? [{ sliceId: slice.id, ...slice.rejectedReview }] : []),
47
+ outstandingGaps: state.finalCheck?.fulfilled === false ? state.finalCheck.gaps : [],
48
+ lastVerificationFailure: latest([
49
+ ...state.slices.flatMap(sliceVerificationFailure),
50
+ ...finalVerificationFailure(state),
51
+ ]),
52
+ };
53
+ }
54
+ /** The failure recorded last; among failures saved before they were ordered, the later listed. */
55
+ function latest(failures) {
56
+ return failures.reduce((found, failure) => (found === undefined || failure.at >= found.at ? failure : found), undefined);
57
+ }
58
+ function sliceVerificationFailure(slice) {
59
+ const failed = slice.failedVerification;
60
+ if (!failed)
61
+ return [];
62
+ return [
63
+ {
64
+ scope: { kind: 'slice', sliceId: slice.id },
65
+ command: failed.command,
66
+ output: failed.output,
67
+ at: failed.at,
68
+ current: !failed.passedSince && slice.status !== 'approved',
69
+ },
70
+ ];
71
+ }
72
+ function finalVerificationFailure(state) {
73
+ const failed = retainedFinalVerificationFailure(state);
74
+ if (!failed)
75
+ return [];
76
+ return [
77
+ {
78
+ scope: { kind: 'finalCheck', round: failed.round },
79
+ command: failed.command,
80
+ output: failed.output,
81
+ at: failed.at,
82
+ current: !failed.passedSince,
83
+ },
84
+ ];
85
+ }
86
+ /**
87
+ * The run's last whole-run verification failure. A run saved before these were kept still
88
+ * records that its latest check failed verification, so that one stands in, unordered and with
89
+ * no output, until a later check replaces it.
90
+ */
91
+ export function retainedFinalVerificationFailure(state) {
92
+ if (state.failedFinalVerification)
93
+ return state.failedFinalVerification;
94
+ const check = state.finalCheck;
95
+ if (!check || check.verified)
96
+ return undefined;
97
+ return {
98
+ command: check.command,
99
+ output: OUTPUT_UNAVAILABLE,
100
+ round: check.round,
101
+ at: 0,
102
+ passedSince: false,
103
+ };
104
+ }