@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,109 @@
1
+ /** Records one line per step, agent call and retry, attributing agent calls to the step they ran in. */
2
+ export class MetricsObserver {
3
+ append;
4
+ clock;
5
+ location;
6
+ constructor(append, clock) {
7
+ this.append = append;
8
+ this.clock = clock;
9
+ }
10
+ handle(event) {
11
+ const at = new Date(this.clock.now()).toISOString();
12
+ switch (event.type) {
13
+ case 'stepStarted':
14
+ this.location = event.at;
15
+ return;
16
+ case 'stepFailed':
17
+ this.location = undefined;
18
+ return;
19
+ case 'stepFinished':
20
+ this.location = undefined;
21
+ return this.append({
22
+ kind: 'step',
23
+ at,
24
+ runId: event.runId,
25
+ location: event.at,
26
+ outcome: event.outcome.type,
27
+ durationMs: event.durationMs,
28
+ ...(event.outcome.type === 'implemented' ? { commit: event.outcome.commit } : {}),
29
+ });
30
+ case 'agentUsage':
31
+ return this.append({
32
+ kind: 'agentCall',
33
+ at,
34
+ runId: event.runId,
35
+ location: this.location,
36
+ role: event.role,
37
+ costUsd: event.costUsd,
38
+ tokens: event.tokens,
39
+ });
40
+ case 'stepRetried':
41
+ return this.append({
42
+ kind: 'retry',
43
+ at,
44
+ runId: event.runId,
45
+ location: event.at,
46
+ reason: event.reason,
47
+ });
48
+ }
49
+ }
50
+ }
51
+ export function summarizeMetrics(records) {
52
+ const steps = records.filter((record) => record.kind === 'step');
53
+ const calls = records.filter((record) => record.kind === 'agentCall');
54
+ const commits = steps.flatMap((step) => (step.commit ? [step.commit] : []));
55
+ return {
56
+ durationMs: sum(steps.map((step) => step.durationMs)),
57
+ steps: steps.length,
58
+ agentCalls: calls.length,
59
+ retries: records.filter((record) => record.kind === 'retry').length,
60
+ reviewRounds: steps.filter((step) => REVIEW_REJECTIONS.has(step.outcome)).length,
61
+ slicesCommitted: new Set(steps.flatMap((step) => step.commit && step.location.sliceId !== undefined ? [step.location.sliceId] : [])).size,
62
+ linesChanged: sum(commits.map((commit) => commit.insertions + commit.deletions)),
63
+ costUsd: sum(calls.map((call) => call.costUsd ?? 0)),
64
+ tokens: {
65
+ input: sum(calls.map((call) => call.tokens.input)),
66
+ output: sum(calls.map((call) => call.tokens.output)),
67
+ cacheRead: sum(calls.map((call) => call.tokens.cacheRead)),
68
+ cacheWrite: sum(calls.map((call) => call.tokens.cacheWrite)),
69
+ reasoning: sum(calls.map((call) => call.tokens.reasoning)),
70
+ },
71
+ };
72
+ }
73
+ function sum(values) {
74
+ return values.reduce((total, value) => total + value, 0);
75
+ }
76
+ /** Outcomes that send a slice back to its implementer with feedback. */
77
+ const REVIEW_REJECTIONS = new Set([
78
+ 'changesRequested',
79
+ 'rulesFixRequested',
80
+ ]);
81
+ /** One line for a PR footer or a status line, e.g. "2 slices · 1 review round · 412k tokens · $1.84 · 18m 3s". */
82
+ export function formatSummary(summary) {
83
+ const tokens = summary.tokens.input +
84
+ summary.tokens.output +
85
+ summary.tokens.cacheRead +
86
+ summary.tokens.cacheWrite;
87
+ return [
88
+ plural(summary.slicesCommitted, 'slice'),
89
+ plural(summary.reviewRounds, 'review round'),
90
+ `${compact(tokens)} tokens`,
91
+ `$${summary.costUsd.toFixed(2)}`,
92
+ duration(summary.durationMs),
93
+ ...(summary.retries > 0 ? [plural(summary.retries, 'retry', 'retries')] : []),
94
+ ].join(' · ');
95
+ }
96
+ function plural(count, singular, pluralForm = `${singular}s`) {
97
+ return `${count} ${count === 1 ? singular : pluralForm}`;
98
+ }
99
+ function compact(count) {
100
+ return new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 })
101
+ .format(count)
102
+ .toLowerCase();
103
+ }
104
+ function duration(ms) {
105
+ const totalSeconds = Math.round(ms / 1000);
106
+ const minutes = Math.floor(totalSeconds / 60);
107
+ const seconds = totalSeconds % 60;
108
+ return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
109
+ }
@@ -0,0 +1,25 @@
1
+ import { isPanic, panic } from 'better-result';
2
+ import { EventEmitter } from 'node:events';
3
+ import { messageOf } from '../domain/errors.js';
4
+ export class RunEvents extends EventEmitter {
5
+ publish(event) {
6
+ this.emit('event', event);
7
+ }
8
+ }
9
+ /**
10
+ * Subscribes an observer to every event. EventEmitter calls listeners synchronously, so a
11
+ * throwing observer would otherwise abort the run that published the event. A `Panic` is a bug,
12
+ * and still does.
13
+ */
14
+ export function observe(events, handle, onObserverError) {
15
+ events.on('event', (event) => {
16
+ try {
17
+ handle(event);
18
+ }
19
+ catch (error) {
20
+ if (isPanic(error))
21
+ panic(messageOf(error), error);
22
+ onObserverError(error);
23
+ }
24
+ });
25
+ }
@@ -0,0 +1,86 @@
1
+ import { context, SpanStatusCode, trace, } from '@opentelemetry/api';
2
+ /**
3
+ * Turns run events into a trace: one span per invocation of a run, one child span per step, with
4
+ * agent token usage and cost on the step it belongs to, named after OpenTelemetry's GenAI
5
+ * conventions where one exists.
6
+ */
7
+ export class TracingObserver {
8
+ tracer;
9
+ runSpan;
10
+ stepSpan;
11
+ constructor(tracer) {
12
+ this.tracer = tracer;
13
+ }
14
+ handle(event) {
15
+ switch (event.type) {
16
+ case 'stepStarted':
17
+ return this.startStep(event.at);
18
+ case 'agentUsage':
19
+ return this.recordAgentUsage(event);
20
+ case 'stepFailed':
21
+ this.stepSpan?.setStatus({ code: SpanStatusCode.ERROR, message: event.reason });
22
+ return this.endStep();
23
+ case 'stepRetried':
24
+ this.runSpan?.addEvent('retry', {
25
+ 'jig.retry.attempt': event.attempt,
26
+ 'jig.retry.reason': event.reason,
27
+ });
28
+ return;
29
+ case 'stepFinished':
30
+ this.stepSpan?.setAttribute('jig.outcome', event.outcome.type);
31
+ return this.endStep();
32
+ default:
33
+ return this.handleRunLifecycle(event);
34
+ }
35
+ }
36
+ startStep(at) {
37
+ this.stepSpan = this.tracer.startSpan(stepName(at), { attributes: locationAttributes(at) }, this.runSpan ? trace.setSpan(context.active(), this.runSpan) : undefined);
38
+ }
39
+ recordAgentUsage(event) {
40
+ this.stepSpan?.addEvent('agent call', {
41
+ 'gen_ai.agent.name': event.role,
42
+ 'gen_ai.usage.input_tokens': event.tokens.input,
43
+ 'gen_ai.usage.output_tokens': event.tokens.output,
44
+ 'jig.usage.cache_read_tokens': event.tokens.cacheRead,
45
+ 'jig.usage.cache_write_tokens': event.tokens.cacheWrite,
46
+ 'jig.usage.reasoning_tokens': event.tokens.reasoning,
47
+ ...(event.costUsd !== undefined ? { 'jig.usage.cost_usd': event.costUsd } : {}),
48
+ });
49
+ }
50
+ endStep() {
51
+ this.stepSpan?.end();
52
+ this.stepSpan = undefined;
53
+ }
54
+ handleRunLifecycle(event) {
55
+ switch (event.type) {
56
+ case 'runResumed':
57
+ this.runSpan = this.tracer.startSpan('jig.run', {
58
+ attributes: { 'jig.run_id': event.runId, 'jig.phase.start': event.phase },
59
+ });
60
+ return;
61
+ case 'runBlocked':
62
+ case 'runFailed':
63
+ this.runSpan?.setStatus({ code: SpanStatusCode.ERROR, message: event.reason });
64
+ return this.endRun(event.phase);
65
+ case 'runHalted':
66
+ case 'runFinished':
67
+ return this.endRun(event.phase);
68
+ }
69
+ }
70
+ endRun(phase) {
71
+ this.runSpan?.setAttribute('jig.phase.end', phase);
72
+ this.runSpan?.end();
73
+ this.runSpan = undefined;
74
+ }
75
+ }
76
+ function stepName(at) {
77
+ return at.sliceId !== undefined ? `jig.step ${at.sliceStatus}` : `jig.step ${at.phase}`;
78
+ }
79
+ function locationAttributes(at) {
80
+ return {
81
+ 'jig.phase': at.phase,
82
+ ...(at.sliceId !== undefined
83
+ ? { 'jig.slice.id': at.sliceId, 'jig.slice.status': at.sliceStatus }
84
+ : {}),
85
+ };
86
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,172 @@
1
+ export function designReviewPrompt(inputs) {
2
+ return [
3
+ 'You are the design review of an automated SDLC pipeline. A planner wrote the design and',
4
+ 'implementation plan below for the request below. Nothing has been implemented yet: decide',
5
+ 'whether this design and plan satisfy the request and hold up against this repository',
6
+ 'before the plan is broken into slices and built.',
7
+ '',
8
+ ...originalInputs(inputs),
9
+ ...documentsSection('DESIGN UNDER REVIEW', inputs.docs),
10
+ ...reviewRules(),
11
+ ...findingFormat(),
12
+ ].join('\n');
13
+ }
14
+ function originalInputs({ request, repoSummary, plan }) {
15
+ return [
16
+ '--- REQUEST START ---',
17
+ request,
18
+ '--- REQUEST END ---',
19
+ '',
20
+ '--- REPOSITORY CONTEXT ---',
21
+ repoSummary,
22
+ '',
23
+ '--- FEATURE PLAN ---',
24
+ `Summary: ${plan.summary}`,
25
+ `Approach: ${plan.approach}`,
26
+ `Affected areas: ${plan.affectedAreas.join(', ')}`,
27
+ '',
28
+ ];
29
+ }
30
+ function documentsSection(label, docs) {
31
+ return [
32
+ `--- ${label}: DESIGN START ---`,
33
+ docs.design,
34
+ `--- ${label}: DESIGN END ---`,
35
+ '',
36
+ `--- ${label}: IMPLEMENTATION PLAN START ---`,
37
+ docs.plan,
38
+ `--- ${label}: IMPLEMENTATION PLAN END ---`,
39
+ '',
40
+ ];
41
+ }
42
+ function reviewRules() {
43
+ return [
44
+ 'Explore the repository as much as you need to check the documents against it.',
45
+ '',
46
+ 'Raise a finding only for a consequential decision: one that, wrong or missing, would',
47
+ 'materially change behaviour the request requires, violate a constraint of this repository',
48
+ '(its rules, conventions or existing design), or cause costly rework. Look for requirements',
49
+ 'the documents miss as well as choices they get wrong. Do not raise stylistic preferences,',
50
+ 'naming taste, speculative future needs, or improvements the request did not ask for.',
51
+ '',
52
+ 'Every finding needs actionable evidence: quote or cite the request, or name the file and',
53
+ 'what it shows. Investigate a fact you are unsure of in the repository before relying on it.',
54
+ 'When doubt remains, say exactly what you could not confirm under "uncertainty"; never',
55
+ 'invent evidence. Give each finding an id unique within your reply.',
56
+ '',
57
+ 'Mark a finding "correction" when the planner can settle it technically within the request,',
58
+ 'and "operatorDecision" when settling it needs a choice only the person who wrote the request',
59
+ 'can make — conflicting requirements, a product preference, or scope the request leaves open.',
60
+ ...intentBoundaries(),
61
+ ...noRepositoryChanges(),
62
+ '',
63
+ ];
64
+ }
65
+ function intentBoundaries() {
66
+ return [
67
+ 'Respect the intent of the request: technical details within it may be settled, but never',
68
+ 'silently broaden its scope, override an explicit requirement, or invent a product preference',
69
+ 'to settle conflicting requirements. An explicit, bounded assumption is acceptable only when',
70
+ 'it stays within the request and leaves no consequential decision unresolved.',
71
+ ];
72
+ }
73
+ function noRepositoryChanges() {
74
+ return [
75
+ 'Do not edit, create or delete any file in the repository, and do not commit: return your',
76
+ 'answer only in your response.',
77
+ ];
78
+ }
79
+ function findingFormat() {
80
+ return [
81
+ 'Respond with JSON matching:',
82
+ '{ "findings": Array<{ "id": string, "concern": string, "failureScenario": string,',
83
+ ' "evidence": string[], "recommendation": string,',
84
+ ' "resolution": "correction" | "operatorDecision", "uncertainty": string }> }',
85
+ '"concern" names the requirement or decision affected; "failureScenario" is a concrete case',
86
+ 'that goes wrong; "uncertainty" is empty when nothing is in doubt. Return an empty findings',
87
+ 'list when the design and plan hold up — that alone approves them.',
88
+ ];
89
+ }
90
+ export function designReReviewPrompt(inputs) {
91
+ return [
92
+ 'You are the design re-review of an automated SDLC pipeline. An earlier review of the',
93
+ "planner's design and plan for the request below raised the findings listed further down.",
94
+ 'The planner has revised the documents once and answered each finding: either it addressed',
95
+ 'the finding in the documents, or it disputed it with evidence. This is the last review',
96
+ 'before the plan is sliced and built; there is no further revision.',
97
+ '',
98
+ ...originalInputs(inputs),
99
+ ...documentsSection('DESIGN AS FIRST REVIEWED', inputs.reviewedDocs),
100
+ ...documentsSection('REVISED DESIGN UNDER REVIEW', inputs.docs),
101
+ ...findingsSection(inputs.findings),
102
+ ...dispositionsSection(inputs.dispositions),
103
+ 'Check each earlier finding against the revised documents. A finding the planner addressed',
104
+ 'is resolved only when the revised documents actually settle it. A disputed finding is',
105
+ "resolved when the planner's evidence holds up when you check it in the request or the",
106
+ 'repository; then drop it. Do not insist on a recommendation just because you made it.',
107
+ 'Also check whether the revision introduced a new consequential problem.',
108
+ 'Report every finding that still stands, and every new one; keep the id of a finding that',
109
+ 'still stands, and give a new finding an id no earlier finding used.',
110
+ '',
111
+ ...reviewRules(),
112
+ ...findingFormat(),
113
+ ].join('\n');
114
+ }
115
+ function findingsSection(findings) {
116
+ return ['--- REVIEW FINDINGS ---', ...findings.flatMap(findingLines), ''];
117
+ }
118
+ function findingLines(finding) {
119
+ return [
120
+ `Finding ${finding.id} (${finding.resolution === 'operatorDecision' ? 'needs an operator decision' : 'technical correction'})`,
121
+ ` Concern: ${finding.concern}`,
122
+ ` Failure scenario: ${finding.failureScenario}`,
123
+ ...finding.evidence.map((evidence) => ` Evidence: ${evidence}`),
124
+ ` Recommendation: ${finding.recommendation}`,
125
+ ...(finding.uncertainty ? [` Uncertainty: ${finding.uncertainty}`] : []),
126
+ ];
127
+ }
128
+ function dispositionsSection(dispositions) {
129
+ return ["--- PLANNER'S DISPOSITIONS ---", ...dispositions.flatMap(dispositionLines), ''];
130
+ }
131
+ function dispositionLines(disposition) {
132
+ if (disposition.status === 'addressed') {
133
+ return [`Finding ${disposition.findingId}: addressed`, ` Change: ${disposition.change}`];
134
+ }
135
+ return [
136
+ `Finding ${disposition.findingId}: disputed`,
137
+ ` Reasoning: ${disposition.reasoning}`,
138
+ ...disposition.evidence.map((evidence) => ` Evidence: ${evidence}`),
139
+ ];
140
+ }
141
+ export function designRevisionPrompt(inputs) {
142
+ return [
143
+ 'You are the design revision step of an automated SDLC pipeline. You wrote the design and',
144
+ 'implementation plan below for the request below; an independent reviewer raised the',
145
+ 'findings listed further down. This is your one chance to revise before the plan is',
146
+ 'reviewed a last time and then sliced and built.',
147
+ '',
148
+ ...originalInputs(inputs),
149
+ ...documentsSection('DESIGN AS REVIEWED', inputs.docs),
150
+ ...findingsSection(inputs.findings),
151
+ 'Answer every finding, exactly once, by its id:',
152
+ '- "addressed": you changed the documents to settle it. Say what you changed.',
153
+ '- "disputed": the finding is wrong. Give your reasoning and evidence from the request or the',
154
+ ' repository that a reviewer can check. Investigate before you dispute; a disagreement',
155
+ ' without evidence is not a dispute.',
156
+ 'A recommendation is not automatically right: follow it, settle the finding another way, or',
157
+ 'dispute it, whichever the evidence supports.',
158
+ ...intentBoundaries(),
159
+ '',
160
+ 'Return the complete revised documents, not the changes: the whole "design", and the whole',
161
+ '"plan" with every step still under a `## Step N — <title>` heading, numbered from 1, each',
162
+ 'step describing implementation work rather than forcing a slice boundary. Related steps',
163
+ 'may belong to one coherent slice.',
164
+ ...noRepositoryChanges(),
165
+ '',
166
+ 'Respond with JSON matching:',
167
+ '{ "design": string, "plan": string, "dispositions": Array<',
168
+ ' { "findingId": string, "status": "addressed", "change": string }',
169
+ ' | { "findingId": string, "status": "disputed", "reasoning": string, "evidence": string[] }',
170
+ '> }',
171
+ ].join('\n');
172
+ }
@@ -0,0 +1,58 @@
1
+ import { FINAL_CHECK_OUTPUT_TAIL } from '../domain/final-check.js';
2
+ export function finalCheckPrompt(input) {
3
+ const { request, plan, range, verification } = input;
4
+ return [
5
+ 'You are the final check of an automated SDLC pipeline.',
6
+ 'Every planned slice has been implemented, reviewed and approved. Decide whether the',
7
+ 'whole run now fulfils the original request, so its branch can be merged.',
8
+ '',
9
+ `The run's change is exactly the commits in \`${range}\` — review all of them together`,
10
+ `(\`git log ${range}\`, \`git diff ${range}\`). Judge the run against the original request`,
11
+ "and the plan below, not against the slices' individual descriptions.",
12
+ '',
13
+ '--- REQUEST START ---',
14
+ request,
15
+ '--- REQUEST END ---',
16
+ '',
17
+ '--- PLAN START ---',
18
+ plan,
19
+ '--- PLAN END ---',
20
+ '',
21
+ ...verificationSection(verification, range),
22
+ 'Do not run mutation testing as a side effect of review.',
23
+ '',
24
+ 'Report every requirement of the request or the plan that the run leaves unmet, incomplete',
25
+ 'or broken — a gap — in one pass, not only the first or the most serious. Use focused',
26
+ 'checks to investigate a specific concern.',
27
+ '',
28
+ 'Respond with JSON matching: { "fulfilled": boolean, "gaps": string[] }.',
29
+ 'Set fulfilled to true only when the run fulfils the request as planned. List every gap,',
30
+ 'each saying exactly what is unmet or wrong; use an empty list when nothing is.',
31
+ ].join('\n');
32
+ }
33
+ function verificationSection(verification, range) {
34
+ if (verification?.command === undefined) {
35
+ return [
36
+ 'No verify command is configured: use focused checks for the changed files before deciding.',
37
+ 'Report what you checked and any remaining verification gaps.',
38
+ ];
39
+ }
40
+ if (verification.passed) {
41
+ return [
42
+ `The verify command \`${verification.command}\` passed in the sandbox for \`${range}\`.`,
43
+ 'jig owns full verification. Do not rerun the verify command or run a broader check',
44
+ '(including the same script without its arguments or a suite it skips), even when the request or repository',
45
+ 'instructions ask for it. Use focused checks to investigate a specific concern.',
46
+ ];
47
+ }
48
+ return [
49
+ `The verify command \`${verification.command}\` failed in the sandbox for \`${range}\`. Its output:`,
50
+ keepTail(verification.output ?? '', FINAL_CHECK_OUTPUT_TAIL),
51
+ 'jig owns full verification. Do not rerun the verify command or run a broader check',
52
+ '(including the same script without its arguments or a suite it skips), even when the request or',
53
+ 'repository instructions ask for it. Use focused checks to investigate the recorded failure.',
54
+ ];
55
+ }
56
+ function keepTail(text, limit) {
57
+ return text.length > limit ? `…${text.slice(-limit)}` : text;
58
+ }
@@ -0,0 +1,111 @@
1
+ export function contextPrompt(request) {
2
+ return [
3
+ 'You are the context-building step of an automated SDLC pipeline.',
4
+ 'Read the following request, then explore this repository as needed to understand',
5
+ 'the relevant existing code.',
6
+ '',
7
+ '--- REQUEST START ---',
8
+ request,
9
+ '--- REQUEST END ---',
10
+ '',
11
+ 'Produce: a one- or two-word classification of the request (e.g. "feature", "bug-fix",',
12
+ '"refactor"), and a concise summary of the repository context relevant to it.',
13
+ '',
14
+ 'Respond with JSON matching: { "classification": string, "repoSummary": string }.',
15
+ ].join('\n');
16
+ }
17
+ export function featurePlanPrompt(request, repoSummary) {
18
+ return [
19
+ 'You are the feature-planning step of an automated SDLC pipeline.',
20
+ '',
21
+ '--- REQUEST ---',
22
+ request,
23
+ '',
24
+ '--- REPOSITORY CONTEXT ---',
25
+ repoSummary,
26
+ '',
27
+ 'Produce a plan: a summary of what will change, the overall approach, and the list of',
28
+ 'affected areas of the codebase.',
29
+ '',
30
+ 'Respond with JSON matching: { "summary": string, "approach": string, "affectedAreas": string[] }.',
31
+ ].join('\n');
32
+ }
33
+ export function designPrompt(request, repoSummary, plan) {
34
+ return [
35
+ 'You are the design step of an automated SDLC pipeline.',
36
+ 'You run unattended: when you would present options to a human, evaluate 2-3 approaches,',
37
+ 'pick the recommended one, and record the alternatives with rejection rationale.',
38
+ '',
39
+ '--- REQUEST ---',
40
+ request,
41
+ '',
42
+ '--- REPOSITORY CONTEXT ---',
43
+ repoSummary,
44
+ '',
45
+ '--- PLAN SUMMARY ---',
46
+ plan.summary,
47
+ '',
48
+ '--- APPROACH ---',
49
+ plan.approach,
50
+ '',
51
+ 'Write two markdown documents. Do not create any files — return them in your response:',
52
+ '1. "design" with sections: Goal; Context; Chosen approach; Alternatives considered (each',
53
+ ' with why it was rejected); Assumptions; Non-goals; Affected areas.',
54
+ '2. "plan" — the overall implementation plan as numbered steps, each under a',
55
+ ' `## Step N — <title>` heading. Steps describe the work, not slice boundaries:',
56
+ ' related steps may belong to one slice. Keep a coherent feature or refactor together',
57
+ ' across its behavior, wiring, and tests instead of planning separate layers as slices.',
58
+ '',
59
+ 'Respond with JSON matching: { "design": string, "plan": string } (markdown in both).',
60
+ ].join('\n');
61
+ }
62
+ export function slicePlanPrompt(planMarkdown, correction) {
63
+ return [
64
+ 'You are the PR-slicing step of an automated SDLC pipeline.',
65
+ '',
66
+ '--- IMPLEMENTATION PLAN ---',
67
+ planMarkdown,
68
+ '',
69
+ 'Break this plan into an ordered sequence of slices. Each slice is one reviewable outcome;',
70
+ 'implementation and review fixes may create multiple commits within that slice.',
71
+ 'Prefer vertical slices when possible: a feature should work end to end within its slice,',
72
+ 'including its behavior, wiring, and tests. For a refactor, keep the change to one coherent',
73
+ 'responsibility and its tests together. Never split work by code layer or plan step alone.',
74
+ 'There is no required or minimum slice count. If the whole plan is naturally one such',
75
+ 'unit, return exactly one slice — do not split it just to produce more.',
76
+ 'Each slice must be a standalone deliverable: its purpose must make sense without knowing',
77
+ 'what comes after it.',
78
+ 'Fold prerequisite edits (type additions, builders, small refactors) into the slice that',
79
+ 'uses them — a slice that only prepares for later slices is forbidden.',
80
+ 'Split only where both sides are independently meaningful deliverables. For each slice',
81
+ 'after the first, explain in its description why it should land separately from the',
82
+ 'preceding slice. If there is no concrete reason, combine them.',
83
+ 'Every slice description must start by naming the plan steps it delivers, from the',
84
+ 'implementation plan above: "Implements plan step 3. …" for one step, or for several',
85
+ '"Implements plan steps 2, 4 and 5. …" — a contiguous run may be written as a range,',
86
+ '"Implements plan steps 1-3. …". End the reference with punctuation before the prose',
87
+ 'that follows it.',
88
+ 'Slices may share plan steps, and one slice may implement every step, but together the',
89
+ 'slices must cover the whole plan: every step of the plan must be implemented by at',
90
+ 'least one slice.',
91
+ ...correctionSection(correction),
92
+ '',
93
+ 'Respond with JSON matching an array of:',
94
+ '{ "id": string (kebab-case, unique), "title": string, "description": string }.',
95
+ "A slice's title becomes its commit message when the implementer leaves work uncommitted,",
96
+ "so write it as a one-line commit header in this repository's convention (its history and",
97
+ 'any commit-message lint config show it), at most 72 characters.',
98
+ 'Order the array the way the slices must be implemented.',
99
+ ].join('\n');
100
+ }
101
+ function correctionSection(problems) {
102
+ if (!problems)
103
+ return [];
104
+ return [
105
+ '',
106
+ 'A previous slice plan for this same implementation plan was rejected with these problems:',
107
+ problems,
108
+ 'Respond with a complete replacement array of slices that fixes every problem — not only',
109
+ 'the slices that would change, and not the previous array with the changes described.',
110
+ ];
111
+ }
@@ -0,0 +1,78 @@
1
+ import { reusedCompletionReport } from '../domain/completion-reuse.js';
2
+ import { unmetRequirements, wholeRunFulfillment, wholeRunVerification, } from '../domain/final-check.js';
3
+ import { slicesInOrder } from '../domain/slice.js';
4
+ export function pullRequestPrompt(input) {
5
+ const { template, plan, slices, design, verifyCommand, finalCheck, reusedCompletion } = input;
6
+ return [
7
+ 'You are the pull-request-description step of an automated SDLC pipeline.',
8
+ 'The work is done and committed in the current directory. Fill in the pull request',
9
+ 'template below so a human can review it without reading the agent run.',
10
+ '',
11
+ '--- TEMPLATE START ---',
12
+ template,
13
+ '--- TEMPLATE END ---',
14
+ '',
15
+ '--- PLAN ---',
16
+ `Summary: ${plan.summary}`,
17
+ `Approach: ${plan.approach}`,
18
+ '',
19
+ '--- SLICES ---',
20
+ ...sliceLines(slices),
21
+ '',
22
+ '--- FINAL CHECK ---',
23
+ ...finalCheckLines(finalCheck, reusedCompletion),
24
+ ...(design ? ['', '--- DESIGN ---', design] : []),
25
+ '',
26
+ 'Rules:',
27
+ '- Keep every heading of the template, in order, and keep its checkboxes. Replace the',
28
+ ' HTML comments with real content.',
29
+ '- Write the sections that describe the result and the motivation in plain words for',
30
+ ' someone who has not seen the code: no file paths, identifiers or technical terms.',
31
+ '- Keep "how" or approach sections to a few lines on the approach and notable decisions.',
32
+ ...verificationRule(verifyCommand),
33
+ '- The final-check section records what the whole-run final check decided: state that',
34
+ ' record as fact too. Put everything it reports unmet in the section for deviations.',
35
+ '- Any slice that is not approved, a whole-run verification that failed, and any',
36
+ ' requirement that was changed or not met goes in the section for deviations, with the',
37
+ ' reviewer feedback in one or two lines. Write "None" there when everything landed as',
38
+ ' planned. Do not list approved slices.',
39
+ '- Do not add a "Closes #N" line unless the template asks for one; the pipeline appends it.',
40
+ '- Do not paste the design or plan. A collapsed section with them is added after your text.',
41
+ '',
42
+ 'Respond with JSON matching: { "body": string } where body is the filled-in markdown.',
43
+ ].join('\n');
44
+ }
45
+ function sliceLines(slices) {
46
+ if (slices.length === 0)
47
+ return ['(none)'];
48
+ return slicesInOrder(slices).map((slice) => {
49
+ const verification = slice.verification ? `, verify passed: ${slice.verification.command}` : '';
50
+ const line = `- [${slice.status}${verification}] ${slice.id}: ${slice.description.split('\n')[0]}`;
51
+ return slice.lastFeedback ? `${line}\n reviewer feedback: ${slice.lastFeedback}` : line;
52
+ });
53
+ }
54
+ /** The whole-run check's recorded facts, for the describer to state as fact rather than judge. */
55
+ function finalCheckLines(finalCheck, reusedCompletion) {
56
+ if (reusedCompletion !== undefined) {
57
+ return reusedCompletionReport(reusedCompletion);
58
+ }
59
+ if (finalCheck === undefined)
60
+ return ['The whole-run final check did not run.'];
61
+ return [
62
+ `Round completed: ${finalCheck.round}`,
63
+ wholeRunVerification(finalCheck),
64
+ wholeRunFulfillment(finalCheck),
65
+ ...(finalCheck.fulfilled ? [] : unmetRequirements(finalCheck.gaps)),
66
+ ];
67
+ }
68
+ /** The describer states jig's own verification record; it runs nothing and invents nothing. */
69
+ function verificationRule(verifyCommand) {
70
+ return [
71
+ '- Each slice line shows what jig verified: where it says "verify passed: <cmd>", jig ran',
72
+ ' that command in the sandbox and it passed. State that record as fact. Do not run checks',
73
+ ' yourself, and do not claim any check passed beyond what jig recorded.',
74
+ verifyCommand
75
+ ? ` The configured verify command is \`${verifyCommand}\`.`
76
+ : ' No verify command is configured, so say jig ran no checks.',
77
+ ];
78
+ }