@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,133 @@
1
+ import { z } from 'zod';
2
+ import { sliceFromPlan } from './slice.js';
3
+ /** What the whole-run reviewer reports: whether the run fulfils its request, and every gap. */
4
+ export const fulfillmentVerdictSchema = z.object({
5
+ fulfilled: z.boolean(),
6
+ gaps: z.array(z.string()),
7
+ });
8
+ /**
9
+ * Folds a completed final check into the run atomically: the first failure records round 1 and
10
+ * appends one pending repair slice; any later completion records round 2 and appends nothing, so
11
+ * replaying a saved state can never add a second repair.
12
+ */
13
+ export function recordFinalCheck(state, checked) {
14
+ const round = state.finalCheck === undefined ? 1 : 2;
15
+ const repaired = repairOwed(checked, round) ? withRepairSlice(state, checked) : state;
16
+ return { ...repaired, finalCheck: completedCheck(checked, round) };
17
+ }
18
+ function repairOwed(checked, round) {
19
+ return round === 1 && checkFailed(checked);
20
+ }
21
+ /** The one way a check fails the run, whatever caused it: verification or fulfillment. */
22
+ function checkFailed(check) {
23
+ return !check.verified || !check.fulfilled;
24
+ }
25
+ function withRepairSlice(state, checked) {
26
+ const repair = sliceFromPlan(repairPlan(checked, state.slices), nextOrder(state.slices));
27
+ return { ...state, slices: [...state.slices, repair] };
28
+ }
29
+ function repairPlan(checked, slices) {
30
+ return {
31
+ id: repairId(slices),
32
+ title: REPAIR_TITLE,
33
+ description: repairDescription(checked),
34
+ };
35
+ }
36
+ function repairId(slices) {
37
+ const taken = new Set(slices.map((slice) => slice.id));
38
+ let attempt = 1;
39
+ while (taken.has(attemptedRepairId(attempt)))
40
+ attempt++;
41
+ return attemptedRepairId(attempt);
42
+ }
43
+ function attemptedRepairId(attempt) {
44
+ return attempt === 1 ? REPAIR_ID : `${REPAIR_ID}-${attempt}`;
45
+ }
46
+ /** The repair's id base, numbered past the planned slices when it is already taken. */
47
+ const REPAIR_ID = 'final-fixes';
48
+ /** Neutral — the same title whatever the check found — and short enough for one commit subject. */
49
+ const REPAIR_TITLE = 'Address the final check findings';
50
+ function repairDescription(checked) {
51
+ return [
52
+ 'A final check of the whole run found problems after every slice was approved.',
53
+ 'Repair exactly what this description lists; change nothing else in the approved work.',
54
+ ...failedVerification(checked),
55
+ ...unmetRequirements(checked.gaps),
56
+ ].join('\n');
57
+ }
58
+ function failedVerification(checked) {
59
+ if (checked.verified || checked.output === undefined)
60
+ return [];
61
+ return [
62
+ `${failedVerificationLine(checked.command)} Its output:`,
63
+ keepTail(checked.output, FINAL_CHECK_OUTPUT_TAIL),
64
+ ];
65
+ }
66
+ /** How jig words a whole-run verification failure, in a repair description and in the PR body. */
67
+ function failedVerificationLine(command) {
68
+ const named = command === undefined ? '' : ` \`${command}\``;
69
+ return `The verify command${named} failed in the sandbox for the run branch.`;
70
+ }
71
+ function keepTail(text, limit) {
72
+ return text.length > limit ? `…${text.slice(-limit)}` : text;
73
+ }
74
+ /**
75
+ * How much of a failed verification's output the run keeps showing: in the reviewer's prompt and
76
+ * in the repair's description.
77
+ */
78
+ export const FINAL_CHECK_OUTPUT_TAIL = 3000;
79
+ /** How jig lists the whole-run review's unmet requirements, wherever it reports them. */
80
+ export function unmetRequirements(gaps) {
81
+ if (gaps.length === 0)
82
+ return [];
83
+ return [
84
+ 'The review of the whole run reported these unmet requirements:',
85
+ ...gaps.map((gap, number) => `${number + 1}. ${gap}`),
86
+ ];
87
+ }
88
+ function nextOrder(slices) {
89
+ return Math.max(-1, ...slices.map((slice) => slice.order)) + 1;
90
+ }
91
+ function completedCheck(checked, round) {
92
+ return {
93
+ verified: checked.verified,
94
+ command: checked.command,
95
+ fulfilled: checked.fulfilled,
96
+ gaps: checked.gaps,
97
+ round,
98
+ };
99
+ }
100
+ /** A failed check still owes the slices its one repair: a failure on the first round. */
101
+ export function finalCheckNeedsRepair(state) {
102
+ const result = state.finalCheck;
103
+ return finalCheckFailed(state) && result?.round === 1;
104
+ }
105
+ /** The run's final check failed it: verification did not pass, or the request is unfulfilled. */
106
+ export function finalCheckFailed(state) {
107
+ const result = state.finalCheck;
108
+ return result !== undefined && checkFailed(result);
109
+ }
110
+ /** How jig states the whole-run verification result: what ran in the sandbox and what it reported. */
111
+ export function wholeRunVerification(result) {
112
+ if (result.command === undefined) {
113
+ return 'No verify command is configured, so jig ran no whole-run verification.';
114
+ }
115
+ return result.verified
116
+ ? `The verify command \`${result.command}\` passed in the sandbox for the run branch.`
117
+ : failedVerificationLine(result.command);
118
+ }
119
+ /** How jig states what the whole-run review decided about the request. */
120
+ export function wholeRunFulfillment(result) {
121
+ return result.fulfilled
122
+ ? 'The review of the whole run reported the request fulfilled.'
123
+ : 'The review of the whole run reported the request unfulfilled.';
124
+ }
125
+ /** What a completed check leaves behind, as jig reports it: a failed verification and every gap. */
126
+ export function unresolvedFindings(result) {
127
+ return [...verificationFinding(result), ...unmetRequirements(result.gaps)];
128
+ }
129
+ function verificationFinding(result) {
130
+ if (result.verified || result.command === undefined)
131
+ return [];
132
+ return [failedVerificationLine(result.command)];
133
+ }
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ export const outcomeTypeSchema = z.enum([
3
+ 'contextBuilt',
4
+ 'featurePlanned',
5
+ 'designWritten',
6
+ 'designReviewed',
7
+ 'designRevised',
8
+ 'sliced',
9
+ 'continue',
10
+ 'pause',
11
+ 'implemented',
12
+ 'approved',
13
+ 'changesRequested',
14
+ 'hookRejected',
15
+ 'verificationFailed',
16
+ 'nothingChanged',
17
+ 'rulesFixRequested',
18
+ 'verified',
19
+ 'finalChecked',
20
+ 'completionReused',
21
+ 'completionDeclined',
22
+ 'completionInvalidated',
23
+ 'described',
24
+ 'merged',
25
+ 'awaitingManualMerge',
26
+ ]);
@@ -0,0 +1,129 @@
1
+ import { Result } from 'better-result';
2
+ import { PlanNotCovered } from './errors.js';
3
+ export function checkPlanCoverage(planMarkdown, slices) {
4
+ const headings = stepHeadings(planMarkdown);
5
+ const steps = [...new Set(headings.filter((step) => step > 0))].sort((a, b) => a - b);
6
+ const claims = slices.map((slice) => claimOf(slice, steps));
7
+ const problems = [
8
+ ...planProblems(headings),
9
+ ...claims.flatMap((claim) => claim.problems),
10
+ ...coverageProblems(steps, claims.flatMap((claim) => claim.steps)),
11
+ ];
12
+ if (problems.length === 0)
13
+ return Result.ok();
14
+ return Result.err(new PlanNotCovered({ message: problems.join('; ') }));
15
+ }
16
+ function stepHeadings(planMarkdown) {
17
+ return planMarkdown
18
+ .split(/\r?\n/)
19
+ .map((line) => STEP_HEADING.exec(line.trim())?.[1])
20
+ .filter((step) => step !== undefined)
21
+ .map(Number);
22
+ }
23
+ /**
24
+ * A plan step heading, `## Step N — <title>`; the delimiter and title vary, only the number counts.
25
+ * Other heading levels do not mark plan steps, and the number must end at a word boundary — a
26
+ * digit run that runs on into letters, as in `## Step 1abc`, is not a step number.
27
+ */
28
+ const STEP_HEADING = /^##\s+step\s+(\d+)\b/i;
29
+ function claimOf(slice, steps) {
30
+ const reference = STEP_REFERENCE.exec(slice.description);
31
+ if (!reference) {
32
+ return {
33
+ steps: [],
34
+ problems: [
35
+ `Slice ${slice.id} does not open its description with an "Implements plan step …" reference.`,
36
+ ],
37
+ };
38
+ }
39
+ const claimed = parseClaimedSteps(reference[1]);
40
+ if (!claimed) {
41
+ return {
42
+ steps: [],
43
+ problems: [
44
+ `Slice ${slice.id} claims plan steps in a malformed reference: "${reference[1]}".`,
45
+ ],
46
+ };
47
+ }
48
+ const unknown = [...new Set(claimed.filter((step) => !steps.includes(step)))];
49
+ if (unknown.length > 0) {
50
+ return {
51
+ steps: claimed.filter((step) => steps.includes(step)),
52
+ problems: [
53
+ `Slice ${slice.id} claims plan step${unknown.length > 1 ? 's' : ''} ${joinNumbers(unknown)}, which the plan does not have.`,
54
+ ],
55
+ };
56
+ }
57
+ return { steps: claimed, problems: [] };
58
+ }
59
+ /**
60
+ * The reference a slice description opens with: the claimed steps, then a punctuation character
61
+ * ending the reference, then whatever prose follows. The prose may span lines. A dash never ends
62
+ * the reference — it would be indistinguishable from a range separator.
63
+ */
64
+ const STEP_REFERENCE = /^implements\s+plan\s+steps?\s+(.+?)\s*([.:;!?—])(?:\s[\s\S]*)?$/i;
65
+ function parseClaimedSteps(reference) {
66
+ const items = reference
67
+ .replace(OXFORD_CONJUNCTION, ', ')
68
+ .replace(BARE_CONJUNCTION, ', ')
69
+ .split(',')
70
+ .map((item) => item.trim());
71
+ if (items.some((item) => item === ''))
72
+ return undefined;
73
+ const claimed = [];
74
+ for (const item of items) {
75
+ const expanded = expandClaimedItem(item);
76
+ if (!expanded)
77
+ return undefined;
78
+ claimed.push(...expanded);
79
+ }
80
+ return claimed;
81
+ }
82
+ const OXFORD_CONJUNCTION = /\s*,\s+and\s+/gi;
83
+ const BARE_CONJUNCTION = /\s+and\s+/gi;
84
+ function expandClaimedItem(item) {
85
+ const range = CLAIMED_RANGE.exec(item);
86
+ if (range)
87
+ return expandClaimedRange(Number(range[1]), Number(range[2]));
88
+ const step = Number(item);
89
+ if (!DIGITS.test(item) || !Number.isSafeInteger(step))
90
+ return undefined;
91
+ return [step];
92
+ }
93
+ const CLAIMED_RANGE = /^(\d+)\s*[-–]\s*(\d+)$/;
94
+ function expandClaimedRange(start, end) {
95
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end))
96
+ return undefined;
97
+ if (start > end || end - start > MAX_RANGE_SPAN)
98
+ return undefined;
99
+ return Array.from({ length: end - start + 1 }, (_, offset) => start + offset);
100
+ }
101
+ /** A range wider than any plan has steps is a mistyped reference, not a claim to count on. */
102
+ const MAX_RANGE_SPAN = 1000;
103
+ const DIGITS = /^\d+$/;
104
+ const joinNumbers = (numbers) => numbers.join(', ');
105
+ function planProblems(headings) {
106
+ if (headings.length === 0) {
107
+ return ['The plan has no step headings for slices to implement.'];
108
+ }
109
+ const problems = [];
110
+ const belowOne = headings.filter((step) => step < 1);
111
+ if (belowOne.length > 0) {
112
+ problems.push(`Plan step headings are numbered from 1, not ${joinNumbers(belowOne)}.`);
113
+ }
114
+ const duplicated = [
115
+ ...new Set(headings.filter((step, index) => headings.indexOf(step) !== index)),
116
+ ];
117
+ if (duplicated.length > 0) {
118
+ problems.push(`These plan step numbers have more than one heading: ${joinNumbers(duplicated)}.`);
119
+ }
120
+ return problems;
121
+ }
122
+ function coverageProblems(steps, claimed) {
123
+ const unimplemented = steps.filter((step) => !claimed.includes(step));
124
+ if (unimplemented.length === 0)
125
+ return [];
126
+ return [
127
+ `No slice implements plan step${unimplemented.length > 1 ? 's' : ''} ${joinNumbers(unimplemented)}.`,
128
+ ];
129
+ }
@@ -0,0 +1,35 @@
1
+ import picomatch from 'picomatch';
2
+ /** The changes among `changes` that touch a protected path. */
3
+ export function protectedChanges(changes) {
4
+ return changes.filter(({ path, kind }) => protectedMatchers.some(({ flaggedWhen, isMatch }) => isMatch(path) && (flaggedWhen === 'changed' || kind !== 'added')));
5
+ }
6
+ /**
7
+ * The paths a slice may not quietly weaken: touching the tests that already exist, or what
8
+ * decides what gets checked, is flagged for review. A `notAdded` pattern welcomes a new file and
9
+ * flags one that was already there; a `changed` pattern flags the file however it changed.
10
+ */
11
+ export const protectedPathPatterns = [
12
+ { pattern: '**/*.spec.*', flaggedWhen: 'notAdded' },
13
+ { pattern: '**/*.test.*', flaggedWhen: 'notAdded' },
14
+ { pattern: '**/test/**', flaggedWhen: 'notAdded' },
15
+ { pattern: '**/tests/**', flaggedWhen: 'notAdded' },
16
+ { pattern: '**/__tests__/**', flaggedWhen: 'notAdded' },
17
+ { pattern: '**/*.snap', flaggedWhen: 'notAdded' },
18
+ { pattern: '**/__snapshots__/**', flaggedWhen: 'notAdded' },
19
+ { pattern: '**/package.json', flaggedWhen: 'changed' },
20
+ { pattern: '**/.eslintrc*', flaggedWhen: 'changed' },
21
+ { pattern: '**/eslint.config.*', flaggedWhen: 'changed' },
22
+ { pattern: '**/.prettierrc*', flaggedWhen: 'changed' },
23
+ { pattern: '**/prettier.config.*', flaggedWhen: 'changed' },
24
+ { pattern: '**/tsconfig*.json', flaggedWhen: 'changed' },
25
+ { pattern: '**/biome.json*', flaggedWhen: 'changed' },
26
+ { pattern: '**/vitest.*', flaggedWhen: 'changed' },
27
+ { pattern: '**/jest.config.*', flaggedWhen: 'changed' },
28
+ { pattern: '**/stryker.conf.*', flaggedWhen: 'changed' },
29
+ { pattern: '.github/workflows/**', flaggedWhen: 'changed' },
30
+ { pattern: '.husky/**', flaggedWhen: 'changed' },
31
+ ];
32
+ const protectedMatchers = protectedPathPatterns.map(({ pattern, flaggedWhen }) => ({
33
+ flaggedWhen,
34
+ isMatch: picomatch(pattern, { dot: true }),
35
+ }));
@@ -0,0 +1,21 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { isTransient } from './errors.js';
3
+ export async function retryResult(operation, policy) {
4
+ for (let attempt = 1;; attempt++) {
5
+ const result = await operation();
6
+ if (result.isOk())
7
+ return result;
8
+ const retriesLeft = policy.retries - attempt + 1;
9
+ policy.onFailedAttempt?.({ error: result.error, attempt, retriesLeft });
10
+ if (retriesLeft <= 0 || !policy.shouldRetry(result.error))
11
+ return result;
12
+ await sleep(policy.delayMs * 2 ** (attempt - 1));
13
+ }
14
+ }
15
+ export function transientRetryPolicy(settings) {
16
+ return {
17
+ retries: settings.maxStepRetries,
18
+ delayMs: settings.retryDelayMs,
19
+ shouldRetry: isTransient,
20
+ };
21
+ }
@@ -0,0 +1,42 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import path from 'node:path';
3
+ import { z } from 'zod';
4
+ /**
5
+ * `<name>-<random>`: the name, from the request's first `# heading` or else its file name, lets a
6
+ * person tell runs apart in branches and worktrees; the random part keeps two runs of the same
7
+ * request apart. A request with no heading and no file is named `stdin-<random>`.
8
+ */
9
+ export function newRunId({ text, file }) {
10
+ const name = slugOf(firstHeading(text) ?? '') || slugOf(file ? path.parse(file).name : '') || 'stdin';
11
+ return runIdSchema.parse(`${name}-${randomBytes(4).toString('hex')}`);
12
+ }
13
+ function slugOf(text) {
14
+ const slug = text
15
+ .normalize('NFKD')
16
+ .replace(/\p{Diacritic}/gu, '')
17
+ .toLowerCase()
18
+ .replace(/[^a-z0-9]+/g, '-')
19
+ .replace(/^-|-$/g, '');
20
+ return shortened(slug);
21
+ }
22
+ function shortened(slug) {
23
+ if (slug.length <= MAX_NAME_LENGTH)
24
+ return slug;
25
+ const cut = slug.slice(0, MAX_NAME_LENGTH);
26
+ const endsOnWord = slug[MAX_NAME_LENGTH] === '-';
27
+ const lastBreak = cut.lastIndexOf('-');
28
+ return endsOnWord || lastBreak < 0 ? cut.replace(/-$/, '') : cut.slice(0, lastBreak);
29
+ }
30
+ /** Keeps a branch name short enough to read in `git branch` and a terminal prompt. */
31
+ const MAX_NAME_LENGTH = 40;
32
+ function firstHeading(markdown) {
33
+ return /^#[ \t]+(.+)$/m.exec(markdown)?.[1];
34
+ }
35
+ /**
36
+ * A run id becomes a `.jig/<runId>` directory, a `jig/run/<runId>` branch and a
37
+ * `refs/jig/<runId>` ref, so only lowercase letters, digits and hyphens get through.
38
+ */
39
+ export const runIdSchema = z
40
+ .string()
41
+ .regex(/^[a-z0-9-]+$/, 'a run id is lowercase letters, digits and hyphens')
42
+ .brand();
@@ -0,0 +1,147 @@
1
+ import { panic } from 'better-result';
2
+ import { z } from 'zod';
3
+ import { completionEvidenceSchema } from './completion-reuse.js';
4
+ import { designDocsSchema } from './design-docs.js';
5
+ import { designReviewProgressAt, designReviewProgressSchema } from './design-review.js';
6
+ import { finalCheckFailed } from './final-check.js';
7
+ import { runIdSchema } from './run-id.js';
8
+ import { sliceStopReason } from './settings.js';
9
+ import { sliceSchema, slicesInOrder } from './slice.js';
10
+ export function startRun(input) {
11
+ return { ...input, revision: 0, phase: 'context', slices: [] };
12
+ }
13
+ /** Moves a run into `phase`, checking it carries everything `phase` guarantees. */
14
+ export function enterPhase(state, phase) {
15
+ const entered = runStateSchema.safeParse({ ...state, phase });
16
+ if (!entered.success) {
17
+ panic(`Run ${state.runId} cannot enter "${phase}": ${entered.error.message}`);
18
+ }
19
+ return entered.data;
20
+ }
21
+ export const runContextSchema = z.object({ classification: z.string(), repoSummary: z.string() });
22
+ export const featurePlanSchema = z.object({
23
+ summary: z.string(),
24
+ approach: z.string(),
25
+ affectedAreas: z.array(z.string()),
26
+ });
27
+ /** What the run's whole-request final check decided, recorded as each check completes. */
28
+ export const finalCheckResultSchema = z.object({
29
+ verified: z.boolean(),
30
+ command: z.string().optional(),
31
+ fulfilled: z.boolean(),
32
+ gaps: z.array(z.string()),
33
+ round: z.number().int().min(1),
34
+ });
35
+ /** What every run carries, whatever its phase; what a phase adds is required from that phase on. */
36
+ const runFields = z.object({
37
+ runId: runIdSchema,
38
+ /**
39
+ * How many times the run has been saved. When several stores hold a copy, the highest revision
40
+ * is the freshest: a counter rather than a timestamp, because the machines saving it do not
41
+ * share a clock. A run saved before revisions were counted loads as revision 0.
42
+ */
43
+ revision: z.number().int().nonnegative().default(0),
44
+ baseBranch: z.string().min(1),
45
+ request: z.string(),
46
+ context: runContextSchema.optional(),
47
+ plan: featurePlanSchema.optional(),
48
+ docs: designDocsSchema.optional(),
49
+ designReview: designReviewProgressSchema.optional(),
50
+ slices: z.array(sliceSchema),
51
+ finalCheck: finalCheckResultSchema.optional(),
52
+ /**
53
+ * What an eligible slice review recorded about the whole request, bound to the work it saw.
54
+ * Evidence saved before it carried its review scope loads as none, so the run declines reuse.
55
+ */
56
+ completionReuse: completionEvidenceSchema.optional().catch(undefined),
57
+ /**
58
+ * Set once the run was found fit to finish on `completionReuse` instead of a final check;
59
+ * cleared when finishing finds that evidence no longer holds.
60
+ */
61
+ completionReuseAuthorized: z.literal(true).optional(),
62
+ prDescription: z.string().optional(),
63
+ /** Why the last invocation stopped short; cleared when the run is resumed. */
64
+ blockedReason: z.string().optional(),
65
+ });
66
+ export const runPhaseSchema = z.enum([
67
+ 'context',
68
+ 'planning',
69
+ 'designing',
70
+ 'reviewingDesign',
71
+ 'revisingDesign',
72
+ 'resolvingDesign',
73
+ 'slicing',
74
+ 'gate',
75
+ 'paused',
76
+ 'slices',
77
+ 'checkingReuse',
78
+ 'finalCheck',
79
+ 'describing',
80
+ 'merging',
81
+ 'awaitingMerge',
82
+ 'done',
83
+ 'stuck',
84
+ ]);
85
+ const withContext = runFields.extend({ context: runContextSchema });
86
+ const withPlan = withContext.extend({ plan: featurePlanSchema });
87
+ const withDocs = withPlan.extend({ docs: designDocsSchema });
88
+ const withSettledDesign = withDocs.extend({
89
+ designReview: designReviewProgressAt.settled.optional(),
90
+ });
91
+ const withDescription = withSettledDesign.extend({ prDescription: z.string() });
92
+ /**
93
+ * A run as it is saved and loaded. Each phase guarantees what the phases before it produced, so
94
+ * a hand-edited or stale file that lacks it fails here, at the boundary, not in a later step.
95
+ */
96
+ export const runStateSchema = z.discriminatedUnion('phase', [
97
+ runFields.extend({ phase: runPhaseSchema.extract(['context']) }),
98
+ withContext.extend({ phase: runPhaseSchema.extract(['planning']) }),
99
+ withPlan.extend({ phase: runPhaseSchema.extract(['designing']) }),
100
+ withDocs.extend({
101
+ phase: runPhaseSchema.extract(['reviewingDesign']),
102
+ designReview: designReviewProgressAt.reReview.optional(),
103
+ }),
104
+ withDocs.extend({
105
+ phase: runPhaseSchema.extract(['revisingDesign']),
106
+ designReview: designReviewProgressAt.revision,
107
+ }),
108
+ withDocs.extend({
109
+ phase: runPhaseSchema.extract(['resolvingDesign']),
110
+ designReview: designReviewProgressAt.resolution,
111
+ }),
112
+ withSettledDesign.extend({
113
+ phase: runPhaseSchema.extract([
114
+ 'slicing',
115
+ 'gate',
116
+ 'paused',
117
+ 'slices',
118
+ 'checkingReuse',
119
+ 'finalCheck',
120
+ 'describing',
121
+ ]),
122
+ }),
123
+ withDescription.extend({
124
+ phase: runPhaseSchema.extract(['merging', 'awaitingMerge', 'done', 'stuck']),
125
+ }),
126
+ ]);
127
+ /** Every slice commits onto this one branch, so the whole feature lands as one merge. */
128
+ export function runBranchFor(runId) {
129
+ return `jig/run/${runId}`;
130
+ }
131
+ /** The first slice, by order, that has not been approved — a stuck slice stays current. */
132
+ export function currentSlice(state) {
133
+ return slicesInOrder(state.slices).find((slice) => slice.status !== 'approved');
134
+ }
135
+ export function runStopReason(state) {
136
+ const slice = stuckSlice(state);
137
+ if (slice)
138
+ return `slice "${slice.id}": ${sliceStopReason(slice)}`;
139
+ if (state.phase === 'stuck' && finalCheckFailed(state)) {
140
+ return 'the whole-run final check failed after repair';
141
+ }
142
+ return undefined;
143
+ }
144
+ /** The slice that exhausted an attempt budget; once there is one, the run ends and a person takes over. */
145
+ export function stuckSlice(state) {
146
+ return state.slices.find((slice) => slice.status === 'stuck');
147
+ }
@@ -0,0 +1,49 @@
1
+ /** How many times a step that failed transiently is tried again before the run blocks. */
2
+ export const MAX_STEP_RETRIES = 2;
3
+ /** Long enough for a rate limit or a container hiccup to clear. */
4
+ export const RETRY_DELAY_MS = 5000;
5
+ export function reviewCapReached(slice, settings) {
6
+ return slice.reviewCycles >= settings.reviewCycleCap;
7
+ }
8
+ /** A slice still owes its verification record when a verify command is configured and it has none. */
9
+ export function sliceNeedsVerification(slice, settings) {
10
+ return Boolean(settings.verifyCommand) && slice.verification === undefined;
11
+ }
12
+ export function sliceStopReason(slice) {
13
+ if (hookFailureCapReached(slice))
14
+ return `commit hooks failed ${slice.hookFailures} times`;
15
+ if (verificationFailureCapReached(slice))
16
+ return `verification failed ${slice.verificationFailures} times`;
17
+ if (emptyAttemptCapReached(slice))
18
+ return `implementation changed nothing ${slice.emptyAttempts} times`;
19
+ if (ruleFixCapReached(slice))
20
+ return `house-rule fixes reached the cap (${slice.ruleFixCycles})`;
21
+ return `review rejections reached the review cap (${slice.reviewCycles})`;
22
+ }
23
+ export function hookFailureCapReached(slice) {
24
+ return slice.hookFailures >= HOOK_FAILURE_CAP;
25
+ }
26
+ /** Hook failures cannot consume the allowance reserved for reviewer findings. */
27
+ export const HOOK_FAILURE_CAP = 3;
28
+ export function verificationFailureCapReached(slice) {
29
+ return slice.verificationFailures >= VERIFICATION_FAILURE_CAP;
30
+ }
31
+ /** Verification failures cannot consume the allowance reserved for reviewer findings. */
32
+ export const VERIFICATION_FAILURE_CAP = 3;
33
+ export function emptyAttemptCapReached(slice) {
34
+ return slice.emptyAttempts >= EMPTY_ATTEMPT_CAP;
35
+ }
36
+ /**
37
+ * An attempt that changes nothing is retried without spending a review cycle — an agent that
38
+ * stalls once usually works on the next try — but not forever.
39
+ */
40
+ export const EMPTY_ATTEMPT_CAP = 2;
41
+ export function ruleFixCapReached(slice) {
42
+ return slice.ruleFixCycles >= RULE_FIX_CAP;
43
+ }
44
+ /**
45
+ * A review that finds only house-rule breaks in a slice that already works sends it back without
46
+ * spending a review cycle, so which rules one review happened to notice does not decide whether
47
+ * the slice gets stuck — but not forever.
48
+ */
49
+ export const RULE_FIX_CAP = 2;
@@ -0,0 +1,63 @@
1
+ import { z } from 'zod';
2
+ import { workObservationsSchema } from './work-facts.js';
3
+ /** Slice ids become lookup keys in state and log lines, so they are restricted to safe characters. */
4
+ export const SLICE_ID_PATTERN = /^[a-z0-9-]+$/;
5
+ export const SLICE_ID_MESSAGE = 'slice id must be lowercase letters, digits and hyphens';
6
+ export const plannedSliceSchema = z.object({
7
+ id: z.string().regex(SLICE_ID_PATTERN, SLICE_ID_MESSAGE),
8
+ title: z.string().min(1),
9
+ description: z.string().min(1),
10
+ });
11
+ export const sliceStatusSchema = z.enum(['pending', 'in_review', 'verifying', 'approved', 'stuck']);
12
+ /** What a slice's verification recorded: the command that passed, and where the work stood around it. */
13
+ export const verificationRecordSchema = z.object({
14
+ command: z.string().min(1),
15
+ observed: workObservationsSchema.optional(),
16
+ });
17
+ /**
18
+ * What a slice's last failed verification ran and left behind: a failing command can change the
19
+ * work it failed on, so the facts around it are recorded for the audit.
20
+ */
21
+ export const failedVerificationSchema = z.object({
22
+ command: z.string().min(1),
23
+ observed: workObservationsSchema,
24
+ });
25
+ export const sliceSchema = plannedSliceSchema.extend({
26
+ order: z.number().int().nonnegative(),
27
+ status: sliceStatusSchema,
28
+ reviewCycles: z.number().int().nonnegative(),
29
+ hookFailures: z.number().int().nonnegative().default(0),
30
+ verificationFailures: z.number().int().nonnegative().default(0),
31
+ emptyAttempts: z.number().int().nonnegative().default(0),
32
+ ruleFixCycles: z.number().int().nonnegative().default(0),
33
+ lastFeedback: z.string().optional(),
34
+ feedbackHistory: z.array(z.string()).default([]),
35
+ commit: z.string().optional(),
36
+ verification: verificationRecordSchema.optional(),
37
+ failedVerification: failedVerificationSchema.optional(),
38
+ });
39
+ export function sliceFromPlan(planned, order) {
40
+ return {
41
+ ...planned,
42
+ order,
43
+ status: 'pending',
44
+ reviewCycles: 0,
45
+ hookFailures: 0,
46
+ verificationFailures: 0,
47
+ emptyAttempts: 0,
48
+ ruleFixCycles: 0,
49
+ feedbackHistory: [],
50
+ };
51
+ }
52
+ /**
53
+ * The rounds before the one the implementer still has to address: once `lastFeedback` is cleared
54
+ * the whole history is earlier, because every round in it was already worked on.
55
+ */
56
+ export function earlierFeedback(slice) {
57
+ if (!slice.lastFeedback)
58
+ return slice.feedbackHistory;
59
+ return slice.feedbackHistory.slice(0, -1);
60
+ }
61
+ export function slicesInOrder(slices) {
62
+ return [...slices].sort((a, b) => a.order - b.order);
63
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ import { z } from 'zod';
2
+ /** Where a repository stood when it was observed: its head, the content that head holds, and whether anything was left uncommitted. */
3
+ export const gitFactsSchema = z.object({
4
+ commit: z.string().min(1),
5
+ tree: z.string().min(1),
6
+ clean: z.boolean(),
7
+ });
8
+ /** Where the run's work stood when it was observed: the host's run branch and the sandbox clone beside it. */
9
+ export const workFactsSchema = z.object({
10
+ host: gitFactsSchema,
11
+ sandbox: gitFactsSchema,
12
+ });
13
+ /** Where the work stood before and after an operation, so mutation during it cannot hide. */
14
+ export const workObservationsSchema = z.object({
15
+ before: workFactsSchema,
16
+ after: workFactsSchema,
17
+ });
18
+ /** The exact work a piece of recorded evidence vouches for: a commit and the tree it holds. */
19
+ export const checkedWorkSchema = z.object({
20
+ commit: z.string().min(1),
21
+ tree: z.string().min(1),
22
+ });