@ygrishajev/jig 1.1.0 → 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 (36) 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/run-store/composite-run-store.js +68 -14
  6. package/dist/adapters/run-store/git-remote-run-store.js +34 -129
  7. package/dist/app/run-jig.js +28 -7
  8. package/dist/app/run-stores.js +4 -3
  9. package/dist/cli/main.js +3 -15
  10. package/dist/domain/apply-outcome.js +30 -13
  11. package/dist/domain/diagnostics.js +104 -0
  12. package/dist/domain/errors.js +8 -0
  13. package/dist/domain/final-check.js +21 -1
  14. package/dist/domain/run-id.js +4 -1
  15. package/dist/domain/run-state.js +43 -1
  16. package/dist/domain/slice.js +8 -2
  17. package/dist/integrations/github/cli.js +20 -0
  18. package/dist/integrations/github/command.js +68 -0
  19. package/dist/integrations/github/errors.js +19 -0
  20. package/dist/integrations/github/findings-comment.js +53 -0
  21. package/dist/integrations/github/github-port.js +1 -0
  22. package/dist/integrations/github/implement-issue.js +281 -0
  23. package/dist/integrations/github/octokit-github.js +101 -0
  24. package/dist/integrations/github/orchestration-state.js +132 -0
  25. package/dist/integrations/github/orchestration-store.js +109 -0
  26. package/dist/integrations/github/repository-identity.js +27 -0
  27. package/dist/integrations/github/request-snapshot.js +3 -0
  28. package/dist/integrations/github/run-branch-publication.js +102 -0
  29. package/dist/ports/run-code.js +1 -0
  30. package/dist/prompts/design-review.js +2 -0
  31. package/dist/prompts/planning.js +5 -1
  32. package/dist/prompts/pull-request.js +4 -1
  33. package/dist/prompts/slice.js +11 -0
  34. package/dist/steps/pull-request-description.js +1 -1
  35. package/dist/steps/slice.js +1 -0
  36. package/package.json +5 -4
@@ -3,12 +3,20 @@ import { z } from 'zod';
3
3
  import { completionEvidenceSchema } from './completion-reuse.js';
4
4
  import { designDocsSchema } from './design-docs.js';
5
5
  import { designReviewProgressAt, designReviewProgressSchema } from './design-review.js';
6
+ import { failedFinalVerificationSchema } from './diagnostics.js';
6
7
  import { finalCheckFailed } from './final-check.js';
7
8
  import { runIdSchema } from './run-id.js';
8
9
  import { sliceStopReason } from './settings.js';
9
10
  import { sliceSchema, slicesInOrder } from './slice.js';
10
11
  export function startRun(input) {
11
- return { ...input, merge: input.merge ?? true, revision: 0, phase: 'context', slices: [] };
12
+ return {
13
+ ...input,
14
+ merge: input.merge ?? true,
15
+ revision: 0,
16
+ diagnosticSequence: 0,
17
+ phase: 'context',
18
+ slices: [],
19
+ };
12
20
  }
13
21
  /** Moves a run into `phase`, checking it carries everything `phase` guarantees. */
14
22
  export function enterPhase(state, phase) {
@@ -18,6 +26,7 @@ export function enterPhase(state, phase) {
18
26
  }
19
27
  return entered.data;
20
28
  }
29
+ export const codePublicationSchema = z.enum(['deferred']);
21
30
  export const runContextSchema = z.object({ classification: z.string(), repoSummary: z.string() });
22
31
  export const featurePlanSchema = z.object({
23
32
  summary: z.string(),
@@ -45,12 +54,24 @@ const runFields = z.object({
45
54
  request: z.string(),
46
55
  /** Whether the run merges its branch when it finishes; a run saved before the choice existed merges. */
47
56
  merge: z.boolean().default(true),
57
+ /**
58
+ * `deferred` keeps the run's code off the remote: saves publish state only, recording the
59
+ * commit the run branch held as `codeRevision`, and the code is published by whoever owns it.
60
+ */
61
+ codePublication: codePublicationSchema.optional(),
62
+ /** The commit the run started from; absent on runs saved before it was recorded. */
63
+ startingCommit: z.string().min(1).optional(),
64
+ /** The run branch's commit at the last deferred save: the checkpoint a resume restores. */
65
+ codeRevision: z.string().min(1).optional(),
48
66
  context: runContextSchema.optional(),
49
67
  plan: featurePlanSchema.optional(),
50
68
  docs: designDocsSchema.optional(),
51
69
  designReview: designReviewProgressSchema.optional(),
52
70
  slices: z.array(sliceSchema),
53
71
  finalCheck: finalCheckResultSchema.optional(),
72
+ failedFinalVerification: failedFinalVerificationSchema.optional(),
73
+ /** Counts the send-backs and final checks the run recorded; each failure takes its count as `at`. */
74
+ diagnosticSequence: z.number().int().nonnegative().default(0),
54
75
  /**
55
76
  * What an eligible slice review recorded about the whole request, bound to the work it saw.
56
77
  * Evidence saved before it carried its review scope loads as none, so the run declines reuse.
@@ -139,6 +160,10 @@ export function currentSlice(state) {
139
160
  export function runMerges(state) {
140
161
  return state.merge;
141
162
  }
163
+ /** Whether saves keep the run's code off the remote, leaving its publication to the caller. */
164
+ export function defersCodePublication(state) {
165
+ return state.codePublication === 'deferred';
166
+ }
142
167
  export function runStopReason(state) {
143
168
  const slice = stuckSlice(state);
144
169
  if (slice)
@@ -152,3 +177,20 @@ export function runStopReason(state) {
152
177
  export function stuckSlice(state) {
153
178
  return state.slices.find((slice) => slice.status === 'stuck');
154
179
  }
180
+ export function canRecoverInitialCheckpoint(state) {
181
+ return (state.phase === 'context' &&
182
+ state.slices.length === 0 &&
183
+ state.diagnosticSequence === 0 &&
184
+ [
185
+ state.context,
186
+ state.plan,
187
+ state.docs,
188
+ state.designReview,
189
+ state.finalCheck,
190
+ state.failedFinalVerification,
191
+ state.completionReuse,
192
+ state.completionReuseAuthorized,
193
+ state.prDescription,
194
+ state.blockedReason,
195
+ ].every((evidence) => evidence === undefined));
196
+ }
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { capturedOutputSchema, diagnosticOrderSchema, OUTPUT_UNAVAILABLE, rejectedReviewSchema, } from './diagnostics.js';
2
3
  import { workObservationsSchema } from './work-facts.js';
3
4
  /** Slice ids become lookup keys in state and log lines, so they are restricted to safe characters. */
4
5
  export const SLICE_ID_PATTERN = /^[a-z0-9-]+$/;
@@ -15,12 +16,16 @@ export const verificationRecordSchema = z.object({
15
16
  observed: workObservationsSchema.optional(),
16
17
  });
17
18
  /**
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.
19
+ * What a slice's last failed verification ran, reported and left behind: a failing command can
20
+ * change the work it failed on, so the facts around it are recorded for the audit. It stays after
21
+ * a later verification passes, marked `passedSince`; one saved before output was kept has none.
20
22
  */
21
23
  export const failedVerificationSchema = z.object({
22
24
  command: z.string().min(1),
23
25
  observed: workObservationsSchema,
26
+ output: capturedOutputSchema.default(OUTPUT_UNAVAILABLE),
27
+ at: diagnosticOrderSchema,
28
+ passedSince: z.boolean().default(false),
24
29
  });
25
30
  export const sliceSchema = plannedSliceSchema.extend({
26
31
  order: z.number().int().nonnegative(),
@@ -35,6 +40,7 @@ export const sliceSchema = plannedSliceSchema.extend({
35
40
  commit: z.string().optional(),
36
41
  verification: verificationRecordSchema.optional(),
37
42
  failedVerification: failedVerificationSchema.optional(),
43
+ rejectedReview: rejectedReviewSchema.optional(),
38
44
  });
39
45
  export function sliceFromPlan(planned, order) {
40
46
  return {
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { exitWhenDone } from '../../cli/exit-when-done.js';
5
+ import { buildCli } from '../../cli/main.js';
6
+ import { registerGithubCommands } from './command.js';
7
+ export function buildJigCli(io, githubFor) {
8
+ const program = buildCli();
9
+ registerGithubCommands(program, io, githubFor);
10
+ return program;
11
+ }
12
+ /**
13
+ * A globally installed CLI is invoked through a symlink, so the invoked path is resolved
14
+ * before comparing it with this module's own path.
15
+ */
16
+ const isMainModule = process.argv[1] !== undefined && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
17
+ if (isMainModule) {
18
+ await buildJigCli().parseAsync(process.argv);
19
+ await exitWhenDone();
20
+ }
@@ -0,0 +1,68 @@
1
+ import { Result } from 'better-result';
2
+ import { z } from 'zod';
3
+ import { appAction } from '../../cli/app-action.js';
4
+ import { configInputSchema, configOption, presetInputSchema, presetOption, } from '../../cli/config-option.js';
5
+ import { logFormatInputSchema, logFormatOption } from '../../cli/log-format-option.js';
6
+ import { GithubSetupInvalid } from './errors.js';
7
+ import { implementIssue } from './implement-issue.js';
8
+ import { OctokitGithub } from './octokit-github.js';
9
+ import { repositoryIdentity } from './repository-identity.js';
10
+ export function registerGithubCommands(program, io, githubFor = OctokitGithub.authenticated) {
11
+ program
12
+ .command('github')
13
+ .description('Implement GitHub issues as pull requests')
14
+ .command('implement')
15
+ .description('Implement an issue and open a pull request')
16
+ .option('--issue <number>', 'issue number')
17
+ .addOption(configOption())
18
+ .addOption(presetOption())
19
+ .addOption(logFormatOption())
20
+ .action(appAction(githubInputSchema, async ({ issue }, app, { token, repository }) => {
21
+ const result = await implementIssue(app, githubFor(token), repository, issue);
22
+ return result.map((outcome) => {
23
+ console.log(describeIssueOutcome(outcome));
24
+ });
25
+ }, io, prepare));
26
+ }
27
+ const githubInputSchema = logFormatInputSchema
28
+ .merge(configInputSchema)
29
+ .merge(presetInputSchema)
30
+ .extend({ issue: z.coerce.number().int().positive() });
31
+ export function describeIssueOutcome(outcome) {
32
+ if (outcome.kind === 'commented')
33
+ return `${outcome.outcome}: ${outcome.url}`;
34
+ if (outcome.kind === 'refused')
35
+ return `Refused, changes workflows (${outcome.paths.join(', ')}): ${outcome.url}`;
36
+ if (outcome.kind === 'draftPullRequest')
37
+ return `${outcome.reused ? 'Reused draft PR' : 'Draft PR'} (stuck): ${outcome.url}, findings: ${outcome.findingsUrl}`;
38
+ return `${outcome.reused ? 'Reused PR' : 'PR'}: ${outcome.url}`;
39
+ }
40
+ function prepare(_input, { cwd, environment }) {
41
+ return Result.gen(async function* () {
42
+ const parsed = githubEnvironmentSchema.safeParse(environment);
43
+ if (!parsed.success)
44
+ return Result.err(new GithubSetupInvalid({
45
+ message: parsed.error.issues.map(({ message }) => message).join('; '),
46
+ }));
47
+ const { token, ...identity } = parsed.data;
48
+ const repository = yield* Result.await(repositoryIdentity(cwd, identity));
49
+ return Result.ok({ token, repository });
50
+ });
51
+ }
52
+ const githubEnvironmentSchema = z
53
+ .object({
54
+ GITHUB_TOKEN: z.string().min(1).optional(),
55
+ GH_TOKEN: z.string().min(1).optional(),
56
+ GITHUB_REPOSITORY: z.string().optional(),
57
+ })
58
+ .transform(({ GITHUB_TOKEN, GH_TOKEN, GITHUB_REPOSITORY }, context) => {
59
+ const token = GITHUB_TOKEN ?? GH_TOKEN;
60
+ if (!token) {
61
+ context.addIssue({
62
+ code: z.ZodIssueCode.custom,
63
+ message: 'Set GITHUB_TOKEN or GH_TOKEN to implement a GitHub issue.',
64
+ });
65
+ return z.NEVER;
66
+ }
67
+ return { token, GITHUB_REPOSITORY };
68
+ });
@@ -0,0 +1,19 @@
1
+ import { TaggedError } from 'better-result';
2
+ export class GithubUnavailable extends TaggedError('GithubUnavailable') {
3
+ }
4
+ export class GithubRefused extends TaggedError('GithubRefused') {
5
+ }
6
+ export class GithubNotFound extends TaggedError('GithubNotFound') {
7
+ }
8
+ export class GithubSetupInvalid extends TaggedError('GithubSetupInvalid') {
9
+ }
10
+ export class BaseBranchMismatch extends TaggedError('BaseBranchMismatch') {
11
+ }
12
+ export class OrchestrationStateInvalid extends TaggedError('OrchestrationStateInvalid') {
13
+ }
14
+ /** Another job holds the lease to publish the same accepted request. */
15
+ export class PublicationInProgress extends TaggedError('PublicationInProgress') {
16
+ }
17
+ /** The run branch could not be inspected, or moved away from what was inspected, so nothing was pushed. */
18
+ export class RunBranchUnpublishable extends TaggedError('RunBranchUnpublishable') {
19
+ }
@@ -0,0 +1,53 @@
1
+ import { runDiagnostics, } from '../../domain/diagnostics.js';
2
+ import { runStopReason } from '../../domain/run-state.js';
3
+ /**
4
+ * The single PR-level comment a draft PR carries: why the run stopped and what is still
5
+ * unresolved, with command output kept verbatim so the file and line references in it survive.
6
+ */
7
+ export function findingsCommentBody(state, revision) {
8
+ const diagnostics = runDiagnostics(state);
9
+ return [
10
+ `Run ${state.runId} stopped as ${state.phase} at ${revision}: ${stuckReason(state)}`,
11
+ ...unresolvedReviewSections(diagnostics),
12
+ ...outstandingGapSection(diagnostics),
13
+ ...verificationFailureSection(diagnostics.lastVerificationFailure),
14
+ ].join('\n\n');
15
+ }
16
+ /** Why a stuck run stopped, for a run saved before the reason could be told. */
17
+ export function stuckReason(state) {
18
+ return runStopReason(state) ?? 'The run exhausted its attempts.';
19
+ }
20
+ function unresolvedReviewSections({ unresolvedReviews }) {
21
+ return unresolvedReviews.map(({ sliceId, feedback }) => `### Unresolved review of slice \`${sliceId}\`\n\n${feedback}`);
22
+ }
23
+ function outstandingGapSection({ outstandingGaps }) {
24
+ if (outstandingGaps.length === 0)
25
+ return [];
26
+ return [`### Outstanding gaps\n\n${outstandingGaps.map((gap) => `- ${gap}`).join('\n')}`];
27
+ }
28
+ function verificationFailureSection(failure) {
29
+ if (!failure)
30
+ return [];
31
+ const status = failure.current ? 'still failing' : 'passed since';
32
+ const command = failure.command ? `\`${failure.command}\`` : 'The verify command';
33
+ return [
34
+ `### Last verification failure (${status})\n\n${command} failed in ${scopeOf(failure)}.\n\n${outputOf(failure.output)}`,
35
+ ];
36
+ }
37
+ function scopeOf({ scope }) {
38
+ return scope.kind === 'slice'
39
+ ? `slice \`${scope.sliceId}\``
40
+ : `round ${scope.round} of the final check`;
41
+ }
42
+ function outputOf(output) {
43
+ if (!output.captured)
44
+ return 'Its output was not kept by the version of jig that ran it.';
45
+ const lead = output.truncated ? 'The end of its output:' : 'Its output:';
46
+ return `${lead}\n\n${fenced(output.tail)}`;
47
+ }
48
+ /** Fences `text` with more backticks than any run inside it, so the output cannot close the block. */
49
+ function fenced(text) {
50
+ const longestRun = Math.max(0, ...Array.from(text.matchAll(/`+/g), ([run]) => run.length));
51
+ const fence = '`'.repeat(Math.max(3, longestRun + 1));
52
+ return `${fence}text\n${text}\n${fence}`;
53
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,281 @@
1
+ import { panic, Result } from 'better-result';
2
+ import { getCurrentBranch } from '../../adapters/git/branch.js';
3
+ import { exactHead } from '../../adapters/git/run-history.js';
4
+ import { runJig } from '../../app/run-jig.js';
5
+ import { openRunStore } from '../../app/run-stores.js';
6
+ import { runIdFor } from '../../domain/run-id.js';
7
+ import { runBranchFor } from '../../domain/run-state.js';
8
+ import { outcomeIsComplete } from '../../flow/engine.js';
9
+ import { BaseBranchMismatch, GithubRefused, } from './errors.js';
10
+ import { findingsCommentBody, stuckReason } from './findings-comment.js';
11
+ import { acceptedRequest, acceptRequest, commentMarker, commentReceipt, findingsCommentReceipt, findingsMarker, pullRequestReceipt, refusalCommentReceipt, refusalMarker, refusalOf, withComment, withFindingsComment, withPullRequest, withRefusal, withRefusalComment, } from './orchestration-state.js';
12
+ import { OrchestrationStore } from './orchestration-store.js';
13
+ import { requestText } from './request-snapshot.js';
14
+ import { hasWorkBeyondStart, inspectRunBranch, publishRunBranch, } from './run-branch-publication.js';
15
+ export function implementIssue(app, github, repository, issueNumber) {
16
+ return Result.gen(async function* () {
17
+ app.cradle.logger.info({ event: 'githubIssuePreparationStarted', issueNumber, repository }, `Checking GitHub issue #${issueNumber} in ${repository.owner}/${repository.repo}`);
18
+ const base = yield* Result.await(github.getDefaultBranch(repository));
19
+ const current = yield* Result.await(getCurrentBranch(app.cradle.repoRoot));
20
+ if (current !== base)
21
+ return Result.err(new BaseBranchMismatch({
22
+ message: `Check out the default branch "${base}" before implementing an issue (currently "${current}").`,
23
+ }));
24
+ const store = new OrchestrationStore(app.cradle.repoRoot);
25
+ const key = `${repository.owner}/${repository.repo}#${issueNumber}`;
26
+ app.cradle.logger.info({ event: 'githubIssueRequestStarted', issueNumber }, `Loading accepted request or fetching GitHub issue #${issueNumber}`);
27
+ const accepted = yield* Result.await(acceptedRequestFor(store, github, repository, key, issueNumber));
28
+ app.cradle.logger.info({ event: 'githubIssueRequestAccepted', issueNumber, runId: accepted.runId }, `GitHub issue #${issueNumber} is ready as run ${accepted.runId}`);
29
+ const report = yield* Result.await(runJig(app, {
30
+ start: { text: accepted.text, merge: false, codePublication: 'deferred' },
31
+ runId: accepted.runId,
32
+ requiredStores: REQUIRED_STORES,
33
+ }));
34
+ app.cradle.logger.info({
35
+ event: 'githubIssueRunFinished',
36
+ issueNumber,
37
+ runId: accepted.runId,
38
+ status: report.status,
39
+ }, `Run ${accepted.runId} finished ${report.status}; publishing the GitHub outcome`);
40
+ const target = { github, repository, issueNumber, key, base, title: accepted.title };
41
+ return store.withPublicationOwnership(key, app.cradle.logger, (whileOwned) => publishOutcome(app, store, { ...target, whileOwned }, report));
42
+ });
43
+ }
44
+ function acceptedRequestFor(store, github, repository, key, issueNumber) {
45
+ return Result.gen(async function* () {
46
+ const existing = yield* Result.await(store.read());
47
+ const accepted = acceptedRequest(existing, key);
48
+ if (accepted)
49
+ return Result.ok(accepted);
50
+ const issue = yield* Result.await(github.getIssue(repository, issueNumber));
51
+ const state = yield* Result.await(store.update((state) => acceptRequest(state, key, {
52
+ runId: runIdFor({ name: issue.title, key }),
53
+ title: issue.title,
54
+ text: requestText(issue),
55
+ })));
56
+ const request = acceptedRequest(state, key);
57
+ if (!request)
58
+ panic('Accepting a request must preserve its snapshot');
59
+ return Result.ok(request);
60
+ });
61
+ }
62
+ /** Issue runs always keep their state on the remote, so a retried job on another clone resumes it. */
63
+ const REQUIRED_STORES = ['git-remote'];
64
+ /**
65
+ * Publishes what the run left: a ready PR for a completed run with approved changes, a draft PR
66
+ * with a findings comment for a stuck run that committed work, a refusal for one that changes a
67
+ * workflow, and a status comment otherwise. Every run with code is inspected before any receipt is
68
+ * reused, and its code reaches the remote only through `publishRunBranch`.
69
+ */
70
+ function publishOutcome(app, store, target, report) {
71
+ return Result.gen(async function* () {
72
+ const { repoRoot } = app.cradle;
73
+ const checkpoint = yield* Result.await(codeCheckpointOf(app, report));
74
+ const publication = yield* Result.await(publicationFor(repoRoot, report, checkpoint));
75
+ if (publication.kind === 'comment')
76
+ return publishStatus(repoRoot, store, target, { report, revision: publication.revision });
77
+ const { revision } = publication;
78
+ const pushed = yield* Result.await(target.whileOwned(() => publishRunBranch(repoRoot, {
79
+ runId: report.state.runId,
80
+ revision,
81
+ defaultBranch: target.base,
82
+ pushUnchanged: publication.kind === 'draft',
83
+ })));
84
+ if (pushed.kind === 'refused')
85
+ return refuse(store, target, { runId: report.state.runId, revision, paths: pushed.paths });
86
+ if (pushed.kind === 'unchanged')
87
+ return publishComment(store, target, { report, revision });
88
+ const pullRequest = pullRequestFor(report, target, publication.kind === 'draft');
89
+ if (publication.kind === 'ready')
90
+ return publishReady(store, target, pullRequest);
91
+ return publishDraft(store, target, {
92
+ report,
93
+ revision,
94
+ pullRequest,
95
+ changesFiles: pushed.changesFiles,
96
+ });
97
+ });
98
+ }
99
+ /**
100
+ * The code checkpoint the run's saved state records, which the run branch must still hold. A run
101
+ * saved before checkpoints were recorded has none, so its branch here is what gets inspected, and
102
+ * it has no starting commit to tell its work by.
103
+ */
104
+ function codeCheckpointOf(app, report) {
105
+ return Result.gen(async function* () {
106
+ const { runId } = report.state;
107
+ const store = yield* Result.await(openRunStore(app.cradle, REQUIRED_STORES));
108
+ const saved = yield* Result.await(store.peek(runId));
109
+ if (saved?.codeRevision)
110
+ return Result.ok({ startingCommit: saved.startingCommit, codeRevision: saved.codeRevision });
111
+ const head = yield* Result.await(exactHead(app.cradle.repoRoot, `refs/heads/${runBranchFor(runId)}`));
112
+ return Result.ok({ codeRevision: head });
113
+ });
114
+ }
115
+ /**
116
+ * A completed run with code is offered as a ready PR and a stuck run with commits past where it
117
+ * started as a draft; every other run, and one with no code, is reported in an issue comment.
118
+ */
119
+ function publicationFor(repoRoot, report, checkpoint) {
120
+ return Result.gen(async function* () {
121
+ const revision = checkpoint.codeRevision;
122
+ if (!revision)
123
+ return Result.ok({ kind: 'comment' });
124
+ if (outcomeIsComplete(report.status))
125
+ return Result.ok({ kind: 'ready', revision });
126
+ if (report.status !== 'stuck')
127
+ return Result.ok({ kind: 'comment', revision });
128
+ const committed = yield* Result.await(hasWorkBeyondStart(repoRoot, checkpoint));
129
+ return Result.ok({ kind: committed ? 'draft' : 'comment', revision });
130
+ });
131
+ }
132
+ function publishStatus(repoRoot, store, target, { report, revision }) {
133
+ return Result.gen(async function* () {
134
+ if (!revision)
135
+ return publishComment(store, target, { report });
136
+ const { runId } = report.state;
137
+ const inspection = yield* Result.await(inspectRunBranch(repoRoot, { runId, revision, defaultBranch: target.base }));
138
+ if (inspection.kind === 'refused')
139
+ return refuse(store, target, { runId, revision, paths: inspection.paths });
140
+ return publishComment(store, target, { report, revision });
141
+ });
142
+ }
143
+ function publishComment(store, target, { report, revision }) {
144
+ return Result.gen(async function* () {
145
+ const identity = {
146
+ runId: report.state.runId,
147
+ outcome: report.status,
148
+ revision: revision ?? NO_CODE_REVISION,
149
+ };
150
+ const state = yield* Result.await(store.read());
151
+ const url = yield* Result.await(commentOnce(target, target.issueNumber, {
152
+ receipt: commentReceipt(state, identity),
153
+ marker: commentMarker(identity),
154
+ body: statusCommentBody(report),
155
+ save: (url) => store.update((state) => withComment(state, identity, url)),
156
+ }));
157
+ return Result.ok({ kind: 'commented', outcome: report.status, url });
158
+ });
159
+ }
160
+ /** Stands in for the revision of a run that has no code yet, so its comment is still keyed. */
161
+ const NO_CODE_REVISION = 'none';
162
+ /**
163
+ * Posts a comment on issue or PR `number` at most once: a saved receipt is reused, and a comment
164
+ * posted before its receipt was saved is found again by its marker instead of being posted twice.
165
+ */
166
+ function commentOnce({ github, repository, whileOwned }, number, comment) {
167
+ return Result.gen(async function* () {
168
+ if (comment.receipt)
169
+ return Result.ok(comment.receipt);
170
+ const found = yield* Result.await(github.findIssueComment(repository, number, comment.marker));
171
+ const url = found ??
172
+ (yield* Result.await(whileOwned(() => github.commentOnIssue(repository, number, `${comment.body}\n\n${comment.marker}`))));
173
+ yield* Result.await(comment.save(url));
174
+ return Result.ok(url);
175
+ });
176
+ }
177
+ function statusCommentBody(report) {
178
+ return `Run ${report.state.runId}: ${report.status}. ${statusCommentReason(report)}`;
179
+ }
180
+ function statusCommentReason(report) {
181
+ switch (report.status) {
182
+ case 'blocked':
183
+ return report.reason;
184
+ case 'halted':
185
+ return 'Paused at the design checkpoint.';
186
+ case 'stuck':
187
+ return stuckReason(report.state);
188
+ case 'completed':
189
+ case 'done':
190
+ return 'No changes were committed.';
191
+ }
192
+ }
193
+ /** Records the refusal before announcing it, so a crash in between still never publishes the code. */
194
+ function refuse(store, target, refusal) {
195
+ return Result.gen(async function* () {
196
+ const { key } = target;
197
+ const state = yield* Result.await(store.update((state) => withRefusal(state, key, refusal)));
198
+ const recorded = refusalOf(state, key, refusal.revision) ?? refusal;
199
+ const url = yield* Result.await(commentOnce(target, target.issueNumber, {
200
+ receipt: refusalCommentReceipt(state, key, refusal.revision),
201
+ marker: refusalMarker(key, refusal.revision),
202
+ body: refusalCommentBody(recorded),
203
+ save: (url) => store.update((state) => withRefusalComment(state, key, refusal.revision, url)),
204
+ }));
205
+ return Result.ok({ kind: 'refused', paths: recorded.paths, url });
206
+ });
207
+ }
208
+ function refusalCommentBody({ runId, revision, paths }) {
209
+ const listed = paths.map((path) => `- \`${path}\``).join('\n');
210
+ return `Run ${runId} was not published: revision ${revision} changes GitHub workflows, which jig does not push for review.\n\n${listed}`;
211
+ }
212
+ function pullRequestFor(report, { title, issueNumber }, draft) {
213
+ return {
214
+ head: runBranchFor(report.state.runId),
215
+ base: report.state.baseBranch,
216
+ title,
217
+ body: `${report.state.prDescription ?? ''}\n\nCloses #${issueNumber}`,
218
+ draft,
219
+ };
220
+ }
221
+ function publishReady(store, target, publication) {
222
+ return Result.gen(async function* () {
223
+ const { receipt, reused } = yield* Result.await(openPullRequestOnce(store, target, publication));
224
+ return Result.ok({ kind: 'pullRequest', url: receipt.url, reused });
225
+ });
226
+ }
227
+ /** Reuses the issue's recorded PR, or one open for the same head, before opening a new one. */
228
+ function openPullRequestOnce(store, { github, repository, key, whileOwned }, publication) {
229
+ return Result.gen(async function* () {
230
+ const state = yield* Result.await(store.read());
231
+ const recorded = pullRequestReceipt(state, key);
232
+ if (recorded)
233
+ return Result.ok({ receipt: recorded, reused: true });
234
+ const found = yield* Result.await(github.findOpenPullRequestByHead(repository, publication.head));
235
+ const pr = found ??
236
+ (yield* Result.await(whileOwned(() => github.openPullRequest(repository, publication))));
237
+ yield* Result.await(store.update((state) => withPullRequest(state, key, pr)));
238
+ return Result.ok({ receipt: { number: pr.number, url: pr.url }, reused: !!found });
239
+ });
240
+ }
241
+ /**
242
+ * Opens the draft, then makes sure it carries its findings comment: a PR whose comment failed, or
243
+ * one recorded before findings were posted, still gets exactly one.
244
+ */
245
+ function publishDraft(store, target, draft) {
246
+ return Result.gen(async function* () {
247
+ const { report, revision } = draft;
248
+ const opened = await openPullRequestOnce(store, target, draft.pullRequest);
249
+ if (opened.isErr())
250
+ return Result.err(explainRefusedDraft(opened.error, draft));
251
+ const { receipt, reused } = opened.value;
252
+ const identity = {
253
+ repository: target.repository,
254
+ pullRequest: receipt.number,
255
+ runId: report.state.runId,
256
+ outcome: report.status,
257
+ revision,
258
+ };
259
+ const state = yield* Result.await(store.read());
260
+ const findingsUrl = yield* Result.await(commentOnce(target, receipt.number, {
261
+ receipt: findingsCommentReceipt(state, identity),
262
+ marker: findingsMarker(identity),
263
+ body: findingsCommentBody(report.state, revision),
264
+ save: (url) => store.update((state) => withFindingsComment(state, identity, url)),
265
+ }));
266
+ return Result.ok({
267
+ kind: 'draftPullRequest',
268
+ url: receipt.url,
269
+ reused,
270
+ findingsUrl,
271
+ });
272
+ });
273
+ }
274
+ /** GitHub may refuse a PR whose commits change no files; say so rather than leave it a puzzle. */
275
+ function explainRefusedDraft(error, { pullRequest, changesFiles }) {
276
+ if (changesFiles || error._tag !== 'GithubRefused')
277
+ return error;
278
+ return new GithubRefused({
279
+ message: `${error.message} The commits on ${pullRequest.head} change no files against ${pullRequest.base}, so there is no diff for a draft PR; inspect the branch by hand.`,
280
+ });
281
+ }
@@ -0,0 +1,101 @@
1
+ import { Octokit } from '@octokit/rest';
2
+ import { Result } from 'better-result';
3
+ import { z } from 'zod';
4
+ import { retryResult } from '../../domain/retry.js';
5
+ import { GithubNotFound, GithubRefused, GithubUnavailable } from './errors.js';
6
+ export class OctokitGithub {
7
+ client;
8
+ constructor(client) {
9
+ this.client = client;
10
+ }
11
+ static authenticated(token) {
12
+ return new OctokitGithub(new Octokit({ auth: token }).rest);
13
+ }
14
+ getIssue(repository, number) {
15
+ return this.call(`getIssue ${repository.owner}/${repository.repo}#${number}`, async () => {
16
+ const { data } = await this.client.issues.get({ ...repository, issue_number: number });
17
+ return { number: data.number, title: data.title, body: data.body ?? '', url: data.html_url };
18
+ });
19
+ }
20
+ call(subject, operation) {
21
+ return retryResult(() => this.attempt(subject, operation), {
22
+ retries: GITHUB_RETRIES,
23
+ delayMs: GITHUB_RETRY_DELAY_MS,
24
+ shouldRetry: (error) => error._tag === 'GithubUnavailable',
25
+ });
26
+ }
27
+ attempt(subject, operation) {
28
+ return Result.tryPromise({ try: operation, catch: (cause) => githubFailure(subject, cause) });
29
+ }
30
+ getDefaultBranch(repository) {
31
+ return this.call(`getDefaultBranch ${repository.owner}/${repository.repo}`, async () => (await this.client.repos.get({ ...repository })).data.default_branch);
32
+ }
33
+ findOpenPullRequestByHead(repository, head) {
34
+ return this.call(`findOpenPullRequestByHead ${repository.owner}/${repository.repo}:${head}`, async () => {
35
+ const { data } = await this.client.pulls.list({
36
+ ...repository,
37
+ head: `${repository.owner}:${head}`,
38
+ state: 'open',
39
+ });
40
+ return data[0] ? { number: data[0].number, url: data[0].html_url } : undefined;
41
+ });
42
+ }
43
+ openPullRequest(repository, input) {
44
+ return this.call(`openPullRequest ${repository.owner}/${repository.repo}: ${input.head} -> ${input.base}`, async () => {
45
+ const { data } = await this.client.pulls.create({ ...repository, ...input });
46
+ return { number: data.number, url: data.html_url };
47
+ });
48
+ }
49
+ commentOnIssue(repository, number, body) {
50
+ return this.attempt(`commentOnIssue ${repository.owner}/${repository.repo}#${number}`, async () => {
51
+ const { data } = await this.client.issues.createComment({
52
+ ...repository,
53
+ issue_number: number,
54
+ body,
55
+ });
56
+ return data.html_url;
57
+ });
58
+ }
59
+ findIssueComment(repository, number, marker) {
60
+ return this.call(`findIssueComment ${repository.owner}/${repository.repo}#${number}`, async () => {
61
+ for (let page = 1;; page++) {
62
+ const { data } = await this.client.issues.listComments({
63
+ ...repository,
64
+ issue_number: number,
65
+ per_page: COMMENTS_PER_PAGE,
66
+ page,
67
+ });
68
+ const found = data.find(({ body }) => body?.includes(marker));
69
+ if (found)
70
+ return found.html_url;
71
+ if (data.length < COMMENTS_PER_PAGE)
72
+ return undefined;
73
+ }
74
+ });
75
+ }
76
+ }
77
+ /** Short outages should not abort an unattended job, while retries remain bounded. */
78
+ const GITHUB_RETRIES = 3;
79
+ /** Back off from an unavailable API rather than immediately sending the request again. */
80
+ const GITHUB_RETRY_DELAY_MS = 1000;
81
+ function githubFailure(subject, cause) {
82
+ const parsed = z
83
+ .object({
84
+ status: z.number().default(0),
85
+ message: z.string().optional(),
86
+ response: z.object({ data: z.object({ message: z.string().optional() }) }).optional(),
87
+ })
88
+ .safeParse(cause);
89
+ const status = parsed.success ? parsed.data.status : 0;
90
+ const reason = parsed.success
91
+ ? (parsed.data.response?.data.message ?? parsed.data.message)
92
+ : undefined;
93
+ const context = `GitHub ${subject} failed${status ? ` (${status})` : ''}`;
94
+ if (status >= 400 && status < 500) {
95
+ const message = `${context}: ${reason ?? 'Request refused.'}`;
96
+ return status === 404 ? new GithubNotFound({ message }) : new GithubRefused({ message });
97
+ }
98
+ return new GithubUnavailable({ message: `${context}: GitHub is unavailable; try again later.` });
99
+ }
100
+ /** GitHub's largest page of issue comments, so a lookup takes as few requests as it can. */
101
+ const COMMENTS_PER_PAGE = 100;