@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.
- package/LICENSE +21 -0
- package/README.md +135 -2
- package/dist/adapters/find-symlink.js +23 -0
- package/dist/adapters/git/git-workspace.js +297 -0
- package/dist/adapters/local-store/credentials-file.js +51 -0
- package/dist/adapters/local-store/local-run-store.js +45 -0
- package/dist/adapters/local-store/local-state.js +12 -0
- package/dist/adapters/local-store/metrics-log.js +119 -0
- package/dist/adapters/local-store/run-artefacts.js +76 -0
- package/dist/adapters/local-store/run-lock.js +51 -0
- package/dist/adapters/local-store/run-paths.js +49 -0
- package/dist/adapters/logging/create-logger.js +29 -0
- package/dist/adapters/run-store/composite-run-store.js +57 -0
- package/dist/adapters/run-store/git-remote-run-store.js +239 -0
- package/dist/adapters/sandbox-image/docker-images.js +93 -0
- package/dist/adapters/sandbox-image/image-recipe.js +96 -0
- package/dist/adapters/sandbox-image/latest-agent-versions.js +9 -0
- package/dist/adapters/sandcastle/agents.js +100 -0
- package/dist/adapters/sandcastle/codex-auth.js +191 -0
- package/dist/adapters/sandcastle/git-hooks.js +20 -0
- package/dist/adapters/sandcastle/open-session.js +67 -0
- package/dist/adapters/sandcastle/private-clone-docker.js +232 -0
- package/dist/adapters/sandcastle/sandcastle-env.js +17 -0
- package/dist/adapters/sandcastle/sandcastle-session.js +338 -0
- package/dist/adapters/sandcastle/structured-output.js +35 -0
- package/dist/adapters/sandcastle/usage.js +65 -0
- package/dist/adapters/telemetry/open-telemetry.js +29 -0
- package/dist/adapters/terminal/ask-for-agents.js +61 -0
- package/dist/adapters/terminal/ask-for-credential.js +32 -0
- package/dist/adapters/terminal/ask-for-preset.js +15 -0
- package/dist/adapters/terminal/standard-input.js +7 -0
- package/dist/adapters/terminal/terminal.js +45 -0
- package/dist/app/container.js +131 -0
- package/dist/app/init-sandbox.js +185 -0
- package/dist/app/observed-events.js +10 -0
- package/dist/app/report-cleanup.js +10 -0
- package/dist/app/run-jig.js +101 -0
- package/dist/app/run-status.js +20 -0
- package/dist/app/run-stores.js +107 -0
- package/dist/app/sandbox-image.js +151 -0
- package/dist/app/throwaway-sandbox.js +49 -0
- package/dist/cli/app-action.js +18 -0
- package/dist/cli/commands/presets.js +32 -0
- package/dist/cli/commands/run.js +82 -0
- package/dist/cli/commands/sandbox.js +54 -0
- package/dist/cli/commands/status.js +41 -0
- package/dist/cli/config-option.js +18 -0
- package/dist/cli/exit-when-done.js +11 -0
- package/dist/cli/log-format-option.js +14 -0
- package/dist/cli/main.js +33 -0
- package/dist/cli/read-request.js +36 -0
- package/dist/cli/with-app.js +73 -0
- package/dist/cli/with-error-handling.js +31 -0
- package/dist/cli/with-input.js +27 -0
- package/dist/config/describe-issues.js +6 -0
- package/dist/config/environment.js +53 -0
- package/dist/config/load-config.js +122 -0
- package/dist/config/presets.js +150 -0
- package/dist/config/write-config.js +39 -0
- package/dist/domain/agent-role.js +12 -0
- package/dist/domain/apply-outcome.js +132 -0
- package/dist/domain/completion-reuse.js +176 -0
- package/dist/domain/design-docs.js +3 -0
- package/dist/domain/design-review-report.js +86 -0
- package/dist/domain/design-review.js +193 -0
- package/dist/domain/errors.js +139 -0
- package/dist/domain/events.js +8 -0
- package/dist/domain/final-check.js +133 -0
- package/dist/domain/outcome.js +26 -0
- package/dist/domain/plan-coverage.js +129 -0
- package/dist/domain/protected-paths.js +35 -0
- package/dist/domain/retry.js +21 -0
- package/dist/domain/run-id.js +42 -0
- package/dist/domain/run-state.js +147 -0
- package/dist/domain/settings.js +49 -0
- package/dist/domain/slice.js +63 -0
- package/dist/domain/usage.js +1 -0
- package/dist/domain/work-facts.js +22 -0
- package/dist/flow/define-flow.js +11 -0
- package/dist/flow/engine.js +255 -0
- package/dist/flow/run-flow.js +129 -0
- package/dist/git/branch.js +26 -0
- package/dist/git/merge.js +92 -0
- package/dist/git/repository.js +48 -0
- package/dist/git/throwaway-branch.js +64 -0
- package/dist/observers/logging-observer.js +51 -0
- package/dist/observers/metrics.js +109 -0
- package/dist/observers/run-events.js +25 -0
- package/dist/observers/tracing-observer.js +86 -0
- package/dist/ports/agent-session.js +1 -0
- package/dist/ports/observability.js +1 -0
- package/dist/ports/run-store.js +1 -0
- package/dist/ports/sandbox-git.js +1 -0
- package/dist/ports/sandbox-images.js +1 -0
- package/dist/ports/workspace.js +1 -0
- package/dist/prompts/design-review.js +172 -0
- package/dist/prompts/final-check.js +58 -0
- package/dist/prompts/planning.js +111 -0
- package/dist/prompts/pull-request.js +78 -0
- package/dist/prompts/slice.js +254 -0
- package/dist/prompts/toolchain.js +37 -0
- package/dist/steps/completion-reuse.js +32 -0
- package/dist/steps/design-review.js +38 -0
- package/dist/steps/final-check.js +39 -0
- package/dist/steps/finishing.js +72 -0
- package/dist/steps/planning.js +77 -0
- package/dist/steps/pull-request-description.js +142 -0
- package/dist/steps/slice.js +149 -0
- package/package.json +95 -4
- package/presets/cheap-volume.json +7 -0
- package/presets/claude-only.json +7 -0
- package/presets/codex-only.json +7 -0
- package/presets/codex-reviewed-opencode.json +7 -0
- package/presets/full-power-codex.json +7 -0
- package/presets/full-power.json +7 -0
- package/presets/long-claude.json +7 -0
- package/presets/open-weight.json +7 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Iaroslav Gryshaiev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,136 @@
|
|
|
1
|
-
#
|
|
1
|
+
# jig
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
jig turns a markdown request into a plan, reviewed commits, and a pull request description.
|
|
4
|
+
It runs Claude Code, OpenCode, or Codex inside a Docker sandbox, stacks the work on one
|
|
5
|
+
branch, and waits for you to merge. Automatic merging is optional.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## Why jig
|
|
10
|
+
|
|
11
|
+
jig gives agents a repeatable plan → review → implement → review loop, reviewing
|
|
12
|
+
the design before implementation, verifying and reviewing each slice, and checking
|
|
13
|
+
the complete request at the end. Agents work unattended in isolated Docker
|
|
14
|
+
containers with private repository clones, running tools without permission prompts
|
|
15
|
+
inside the sandbox. By default, the finished run branch waits for your review and
|
|
16
|
+
merge; automatic merging is an explicit opt-in.
|
|
17
|
+
|
|
18
|
+
### Built with jig
|
|
19
|
+
|
|
20
|
+
jig is used to develop itself. As of
|
|
21
|
+
[`83f185b`](https://github.com/ygrishajev/jig/commit/83f185b), the complete repository
|
|
22
|
+
history contains 354 commits, including 64 authored by `jig <jig@users.noreply.invalid>`.
|
|
23
|
+
These are examples of jig-authored work, not a claim that the entire project was
|
|
24
|
+
built autonomously:
|
|
25
|
+
|
|
26
|
+
- [`10d4886`](https://github.com/ygrishajev/jig/commit/10d4886ce87b689c4c280efceeb488a46497e0c4) — `feat(flow): review designs before slicing with one revision`
|
|
27
|
+
- [`4711bca`](https://github.com/ygrishajev/jig/commit/4711bca1664ed8fcc0624e58786c92cc7cbeeae3) — `feat(flow): verify each slice before review, never approve unverified`
|
|
28
|
+
- [`84beed8`](https://github.com/ygrishajev/jig/commit/84beed87913179c05f9659a3e911ea73966764d8) — `feat(flow): check whole-run fulfillment with one repair attempt`
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
Requires Node **20.17 or newer**, Git **2.38 or newer**, and a running Docker daemon.
|
|
33
|
+
Run jig from the target repository's root. Set your Git `user.name` and `user.email`
|
|
34
|
+
for automatic merges.
|
|
35
|
+
|
|
36
|
+
Install globally from npm:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npm install --global @ygrishajev/jig
|
|
40
|
+
jig --help
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Install from a checkout:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
git clone https://github.com/ygrishajev/jig.git
|
|
47
|
+
cd jig
|
|
48
|
+
npm ci
|
|
49
|
+
npm run install:local
|
|
50
|
+
jig --help
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
See [package installation](docs/installation.md) for usage and source installation.
|
|
54
|
+
For development setup and checks, see [Contributing](CONTRIBUTING.md).
|
|
55
|
+
|
|
56
|
+
## Quickstart
|
|
57
|
+
|
|
58
|
+
### 1. Initialize your repository
|
|
59
|
+
|
|
60
|
+
From the repository you want jig to work on:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
jig init
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Choose agents and provide their credentials when prompted. jig proposes a Dockerfile
|
|
67
|
+
and setup and verification commands, then checks them inside the sandbox. Review the
|
|
68
|
+
generated files and commit them:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
git add .sandcastle/Dockerfile .sandcastle/.gitignore jig.config.json
|
|
72
|
+
git commit -m "chore: set up jig"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 2. Describe the change
|
|
76
|
+
|
|
77
|
+
Create a Markdown request with the change you need, why it matters, relevant context,
|
|
78
|
+
constraints, and verifiable acceptance criteria. Linked conversations are not part
|
|
79
|
+
of the agent's input. Save the file outside the target repository, for example as
|
|
80
|
+
`../request.md`, or commit it before running jig. To pipe a request instead, pass `-`
|
|
81
|
+
in place of the file, for example `gh issue view 7 … | jig run -`.
|
|
82
|
+
|
|
83
|
+
To review the plan before implementation, set `"designGate": "checkpoint"` in
|
|
84
|
+
`jig.config.json` and commit the change before starting.
|
|
85
|
+
|
|
86
|
+
### 3. Run and inspect
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
jig run ../request.md --id first-run
|
|
90
|
+
jig status first-run
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
jig plans the work, reviews the design, and implements and reviews each slice.
|
|
94
|
+
At a design checkpoint, read the generated documents and continue with
|
|
95
|
+
`jig run --id first-run`.
|
|
96
|
+
|
|
97
|
+
### 4. Review and merge
|
|
98
|
+
|
|
99
|
+
By default, jig waits for you to merge `jig/run/first-run`. Read
|
|
100
|
+
`.jig/first-run/state/PR_DESCRIPTION.md`, inspect the branch, and merge through your
|
|
101
|
+
normal workflow. jig generates the description but does not open a pull request.
|
|
102
|
+
After merging, run `jig run --id first-run` to record completion.
|
|
103
|
+
|
|
104
|
+
If a run stops early, use [outcomes and recovery](docs/commands.md#outcomes-and-recovery)
|
|
105
|
+
to choose the next action.
|
|
106
|
+
|
|
107
|
+
## Documentation
|
|
108
|
+
|
|
109
|
+
Start with the [documentation index](docs/README.md), or go directly to a task:
|
|
110
|
+
|
|
111
|
+
| I want to… | Guide |
|
|
112
|
+
| --------------------------------------- | ------------------------------------------ |
|
|
113
|
+
| Install jig | [Installation](docs/installation.md) |
|
|
114
|
+
| Start, inspect, or resume a run | [Commands and lifecycle](docs/commands.md) |
|
|
115
|
+
| Set up agent access | [Authentication](docs/authentication.md) |
|
|
116
|
+
| Choose agents and models | [Agent presets](docs/presets.md) |
|
|
117
|
+
| Look up settings and defaults | [Configuration](docs/configuration.md) |
|
|
118
|
+
| Understand container and merge behavior | [Sandbox boundaries](docs/sandbox.md) |
|
|
119
|
+
| Automate runs or inspect artifacts | [Operations](docs/operations.md) |
|
|
120
|
+
| Develop jig | [Contributing](CONTRIBUTING.md) |
|
|
121
|
+
|
|
122
|
+
## Sandbox boundaries
|
|
123
|
+
|
|
124
|
+
Agents run unattended inside a [sandcastle](https://github.com/mattpocock/sandcastle)
|
|
125
|
+
Docker container. They see a private clone with no remote or host repository mounts.
|
|
126
|
+
Only implementation commits are imported back to the host. Credentials enter through
|
|
127
|
+
environment variables, with a private login-cache mount for Codex.
|
|
128
|
+
|
|
129
|
+
Agent review does not replace your review. Automatic merging (`"mergeMode": "auto"`)
|
|
130
|
+
lands agent code without a human checkpoint. Agent commits are unsigned by default;
|
|
131
|
+
`"commitSigning": "repo"` re-signs the run branch during an automatic merge and requires
|
|
132
|
+
a signing setup that works without prompts. See [sandbox boundaries](docs/sandbox.md#merging-and-signing) for details.
|
|
133
|
+
|
|
134
|
+
## License
|
|
135
|
+
|
|
136
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { lstatSync } from 'node:fs';
|
|
3
|
+
import { ConfigInvalid, messageOf } from '../domain/errors.js';
|
|
4
|
+
export function refuseSymlinks(paths) {
|
|
5
|
+
const link = Result.try({
|
|
6
|
+
try: () => findSymlink(paths),
|
|
7
|
+
catch: (cause) => new ConfigInvalid({ message: `Cannot check ${paths.join(', ')}: ${messageOf(cause)}` }),
|
|
8
|
+
});
|
|
9
|
+
if (link.isErr())
|
|
10
|
+
return Result.err(link.error);
|
|
11
|
+
return link.value
|
|
12
|
+
? Result.err(new ConfigInvalid({
|
|
13
|
+
message: `Refusing to write through the symbolic link ${link.value}.`,
|
|
14
|
+
}))
|
|
15
|
+
: Result.ok();
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Git checks out symbolic links, so a path jig writes inside a repository may lead anywhere on
|
|
19
|
+
* this machine. A missing path is no link. Dangling links count: a write would create their target.
|
|
20
|
+
*/
|
|
21
|
+
export function findSymlink(paths) {
|
|
22
|
+
return paths.find((file) => lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink());
|
|
23
|
+
}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { execa } from 'execa';
|
|
3
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { CommitImportRefused, CommitRejected, GitCommandFailed, LocalStateUnwritable, MergeFailed, messageOf, } from '../../domain/errors.js';
|
|
7
|
+
import { runBranchFor } from '../../domain/run-state.js';
|
|
8
|
+
import { isBranchMergedInto, mergeBranchInto } from '../../git/merge.js';
|
|
9
|
+
import { gitCommand, isWorkingTreeClean, openRepo, openRepoWithoutHooks, } from '../../git/repository.js';
|
|
10
|
+
export class GitWorkspace {
|
|
11
|
+
options;
|
|
12
|
+
runBranch;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.options = options;
|
|
15
|
+
this.runBranch = runBranchFor(options.runId);
|
|
16
|
+
}
|
|
17
|
+
saveWork(message, { approved }) {
|
|
18
|
+
return Result.gen(async function* () {
|
|
19
|
+
yield* Result.await(this.commitInSandbox(message));
|
|
20
|
+
yield* Result.await(this.importCommits(approved));
|
|
21
|
+
return Result.ok();
|
|
22
|
+
}, this);
|
|
23
|
+
}
|
|
24
|
+
async commitInSandbox(message) {
|
|
25
|
+
const status = await this.sandboxGit(['status', '--porcelain']);
|
|
26
|
+
if (status.isErr() || status.value === '')
|
|
27
|
+
return status.map(() => undefined);
|
|
28
|
+
const added = await this.sandboxGit(['add', '-A']);
|
|
29
|
+
if (added.isErr())
|
|
30
|
+
return added.map(() => undefined);
|
|
31
|
+
const committed = await this.options.sandbox.execGit(['commit', '-q', '-m', message]);
|
|
32
|
+
if (committed.isErr())
|
|
33
|
+
return Result.err(committed.error);
|
|
34
|
+
const { exitCode, output } = committed.value;
|
|
35
|
+
return exitCode === 0
|
|
36
|
+
? Result.ok()
|
|
37
|
+
: Result.err(new CommitRejected({
|
|
38
|
+
message: `The repository's commit hooks rejected the commit: ${output.trim()}`,
|
|
39
|
+
output: output.trim(),
|
|
40
|
+
}));
|
|
41
|
+
}
|
|
42
|
+
async sandboxGit(args) {
|
|
43
|
+
const ran = await this.options.sandbox.execGit(args);
|
|
44
|
+
if (ran.isErr())
|
|
45
|
+
return Result.err(ran.error);
|
|
46
|
+
const { exitCode, output } = ran.value;
|
|
47
|
+
return exitCode === 0
|
|
48
|
+
? Result.ok(output.trim())
|
|
49
|
+
: Result.err(new GitCommandFailed({
|
|
50
|
+
message: `git ${args[0]} failed in the sandbox: ${output.trim()}`,
|
|
51
|
+
command: `git ${args.join(' ')}`,
|
|
52
|
+
output,
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Commits cross as a bundle, read as data: the host never opens the sandbox's repository, and
|
|
57
|
+
* believes nothing it reports until the fetched commits bear it out.
|
|
58
|
+
*/
|
|
59
|
+
importCommits(approved) {
|
|
60
|
+
return Result.gen(async function* () {
|
|
61
|
+
const head = yield* Result.await(this.sandboxGit(['rev-parse', 'HEAD']));
|
|
62
|
+
if (head === (yield* Result.await(this.headCommit())))
|
|
63
|
+
return Result.ok();
|
|
64
|
+
if (head === approved)
|
|
65
|
+
return this.moveRunBranchTo(approved);
|
|
66
|
+
const fetched = yield* Result.await(this.fetchFromSandbox(approved));
|
|
67
|
+
if (fetched !== head) {
|
|
68
|
+
return Result.err(new CommitImportRefused({
|
|
69
|
+
message: `The sandbox reported ${head} as its head, but its bundle holds ${fetched}.`,
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
if (!(await this.descendsFrom(fetched, approved))) {
|
|
73
|
+
return Result.err(new CommitImportRefused({
|
|
74
|
+
message: `The sandbox rewrote approved commit ${approved}, so its work was not taken.`,
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
return this.moveRunBranchTo(fetched);
|
|
78
|
+
}, this);
|
|
79
|
+
}
|
|
80
|
+
moveRunBranchTo(commit) {
|
|
81
|
+
return gitCommand('reset', async () => {
|
|
82
|
+
await openRepoWithoutHooks(this.options.worktreePath).raw(['reset', '-q', '--hard', commit]);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
fetchFromSandbox(approved) {
|
|
86
|
+
return Result.gen(async function* () {
|
|
87
|
+
const directory = yield* Result.await(makeImportDirectory());
|
|
88
|
+
try {
|
|
89
|
+
const hostBundle = path.join(directory, 'out.bundle');
|
|
90
|
+
yield* Result.await(this.sandboxGit([
|
|
91
|
+
'bundle',
|
|
92
|
+
'create',
|
|
93
|
+
'-q',
|
|
94
|
+
OUTGOING_BUNDLE,
|
|
95
|
+
this.runBranch,
|
|
96
|
+
`^${approved}`,
|
|
97
|
+
]));
|
|
98
|
+
yield* Result.await(this.options.sandbox.copyOut(OUTGOING_BUNDLE, hostBundle));
|
|
99
|
+
return gitCommand('fetch', async () => {
|
|
100
|
+
const git = openRepoWithoutHooks(this.options.worktreePath);
|
|
101
|
+
await git.raw([
|
|
102
|
+
'-c',
|
|
103
|
+
'fetch.fsckObjects=true',
|
|
104
|
+
'fetch',
|
|
105
|
+
'-q',
|
|
106
|
+
hostBundle,
|
|
107
|
+
this.runBranch,
|
|
108
|
+
]);
|
|
109
|
+
return (await git.revparse(['FETCH_HEAD'])).trim();
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
await removeImportDirectory(directory);
|
|
114
|
+
}
|
|
115
|
+
}, this);
|
|
116
|
+
}
|
|
117
|
+
async descendsFrom(commit, ancestor) {
|
|
118
|
+
const { exitCode } = await execa('git', ['merge-base', '--is-ancestor', ancestor, commit], {
|
|
119
|
+
cwd: this.options.repoRoot,
|
|
120
|
+
reject: false,
|
|
121
|
+
});
|
|
122
|
+
return exitCode === 0;
|
|
123
|
+
}
|
|
124
|
+
headCommit() {
|
|
125
|
+
return gitCommand('rev-parse', async () => (await openRepo(this.options.repoRoot).revparse([this.runBranch])).trim());
|
|
126
|
+
}
|
|
127
|
+
forkPoint() {
|
|
128
|
+
return gitCommand('merge-base', async () => {
|
|
129
|
+
const forkPoint = await openRepo(this.options.repoRoot).raw([
|
|
130
|
+
'merge-base',
|
|
131
|
+
this.options.baseBranch,
|
|
132
|
+
this.runBranch,
|
|
133
|
+
]);
|
|
134
|
+
return forkPoint.trim();
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
summariseCommitsSince(since) {
|
|
138
|
+
return Result.gen(async function* () {
|
|
139
|
+
const sha = yield* Result.await(this.headCommit());
|
|
140
|
+
const diff = yield* Result.await(gitCommand('diff', () => openRepo(this.options.repoRoot).diffSummary([since, sha])));
|
|
141
|
+
return Result.ok({
|
|
142
|
+
sha,
|
|
143
|
+
filesChanged: diff.changed,
|
|
144
|
+
insertions: diff.insertions,
|
|
145
|
+
deletions: diff.deletions,
|
|
146
|
+
});
|
|
147
|
+
}, this);
|
|
148
|
+
}
|
|
149
|
+
changedFilesSince(start) {
|
|
150
|
+
return Result.gen(async function* () {
|
|
151
|
+
const head = yield* Result.await(this.headCommit());
|
|
152
|
+
return gitCommand('diff', async () => parseChangedFiles(await openRepoWithoutHooks(this.options.worktreePath).raw([
|
|
153
|
+
'diff',
|
|
154
|
+
'--name-status',
|
|
155
|
+
'-M',
|
|
156
|
+
'-z',
|
|
157
|
+
start,
|
|
158
|
+
head,
|
|
159
|
+
])));
|
|
160
|
+
}, this);
|
|
161
|
+
}
|
|
162
|
+
async readRepoFile(relativePath) {
|
|
163
|
+
try {
|
|
164
|
+
return await readFile(path.join(this.options.repoRoot, relativePath), 'utf-8');
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
collectFacts() {
|
|
171
|
+
return Result.gen(async function* () {
|
|
172
|
+
return Result.ok({
|
|
173
|
+
host: yield* Result.await(this.hostFacts()),
|
|
174
|
+
sandbox: yield* Result.await(this.sandboxFacts()),
|
|
175
|
+
});
|
|
176
|
+
}, this);
|
|
177
|
+
}
|
|
178
|
+
/** The run branch as the host holds it: its tip, the content that tip holds, and whether its worktree is clean. */
|
|
179
|
+
hostFacts() {
|
|
180
|
+
return Result.gen(async function* () {
|
|
181
|
+
const commit = yield* Result.await(gitCommand('rev-parse', () => openRepo(this.options.repoRoot).revparse([this.runBranch])));
|
|
182
|
+
const tree = yield* Result.await(gitCommand('rev-parse', () => openRepo(this.options.repoRoot).revparse([`${this.runBranch}^{tree}`])));
|
|
183
|
+
const clean = yield* Result.await(isWorkingTreeClean(this.options.worktreePath));
|
|
184
|
+
return Result.ok({ commit: commit.trim(), tree: tree.trim(), clean });
|
|
185
|
+
}, this);
|
|
186
|
+
}
|
|
187
|
+
/** The sandbox clone as it stands: its head, the content that head holds, and whether it is clean. */
|
|
188
|
+
sandboxFacts() {
|
|
189
|
+
return Result.gen(async function* () {
|
|
190
|
+
const commit = yield* Result.await(this.sandboxGit(['rev-parse', 'HEAD']));
|
|
191
|
+
const tree = yield* Result.await(this.sandboxGit(['rev-parse', 'HEAD^{tree}']));
|
|
192
|
+
const status = yield* Result.await(this.sandboxGit(['status', '--porcelain']));
|
|
193
|
+
return Result.ok({ commit, tree, clean: status === '' });
|
|
194
|
+
}, this);
|
|
195
|
+
}
|
|
196
|
+
async mergeRunBranch({ approved, }) {
|
|
197
|
+
const { repoRoot, baseBranch, signing } = this.options;
|
|
198
|
+
const tip = await this.refuseUnapprovedTip(approved);
|
|
199
|
+
if (tip.isErr())
|
|
200
|
+
return tip;
|
|
201
|
+
if (signing === 'repo') {
|
|
202
|
+
const signed = await this.signRunBranch();
|
|
203
|
+
if (signed.isErr())
|
|
204
|
+
return signed;
|
|
205
|
+
}
|
|
206
|
+
const merged = await mergeBranchInto(repoRoot, this.runBranch, baseBranch, {
|
|
207
|
+
sign: signing === 'repo',
|
|
208
|
+
});
|
|
209
|
+
if (merged.isOk())
|
|
210
|
+
return Result.ok();
|
|
211
|
+
await abortMergeInProgress(repoRoot);
|
|
212
|
+
return Result.err(new MergeFailed({
|
|
213
|
+
message: `Merging "${this.runBranch}" into "${baseBranch}" failed: ${merged.error.message}`,
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
/** By content, not SHA: signing rewrites the commits, and a merge may be tried again after it. */
|
|
217
|
+
async refuseUnapprovedTip(approved) {
|
|
218
|
+
const trees = await gitCommand('rev-parse', async () => {
|
|
219
|
+
const git = openRepo(this.options.repoRoot);
|
|
220
|
+
return [
|
|
221
|
+
await git.revparse([`${this.runBranch}^{tree}`]),
|
|
222
|
+
approved && (await git.revparse([`${approved}^{tree}`])),
|
|
223
|
+
];
|
|
224
|
+
});
|
|
225
|
+
if (trees.isErr())
|
|
226
|
+
return Result.err(new MergeFailed({ message: trees.error.message }));
|
|
227
|
+
return trees.value[0] === trees.value[1]
|
|
228
|
+
? Result.ok()
|
|
229
|
+
: Result.err(new MergeFailed({
|
|
230
|
+
message: `Refusing to merge "${this.runBranch}": its tip is not the last approved commit.`,
|
|
231
|
+
}));
|
|
232
|
+
}
|
|
233
|
+
/** Runs only when the operator asked, and only now, so SHAs stay stable for the whole run. */
|
|
234
|
+
async signRunBranch() {
|
|
235
|
+
const forkPoint = await this.forkPoint();
|
|
236
|
+
if (forkPoint.isErr())
|
|
237
|
+
return Result.err(new MergeFailed({ message: forkPoint.error.message }));
|
|
238
|
+
const git = openRepoWithoutHooks(this.options.worktreePath);
|
|
239
|
+
const signed = await gitCommand('rebase', () => git.raw(['rebase', '-q', '--force-rebase', '--gpg-sign', forkPoint.value]));
|
|
240
|
+
if (signed.isOk())
|
|
241
|
+
return Result.ok();
|
|
242
|
+
await git.raw(['rebase', '--abort']).catch(() => undefined);
|
|
243
|
+
return Result.err(new MergeFailed({ message: `Could not sign "${this.runBranch}": ${signed.error.message}` }));
|
|
244
|
+
}
|
|
245
|
+
isRunBranchMerged() {
|
|
246
|
+
return isBranchMergedInto(this.options.repoRoot, this.runBranch, this.options.baseBranch);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function makeImportDirectory() {
|
|
250
|
+
const prefix = path.join(tmpdir(), 'jig-import-');
|
|
251
|
+
return Result.tryPromise({
|
|
252
|
+
try: () => mkdtemp(prefix),
|
|
253
|
+
catch: (cause) => new LocalStateUnwritable({
|
|
254
|
+
message: `Cannot make a directory for the sandbox's commits: ${messageOf(cause)}`,
|
|
255
|
+
path: prefix,
|
|
256
|
+
}),
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
/** Inside the clone's `.git`, so a bundle can never be committed by `git add -A`. */
|
|
260
|
+
const OUTGOING_BUNDLE = '.git/jig-out.bundle';
|
|
261
|
+
/** The bundle in it is already fetched; a leftover in the temp directory harms nothing. */
|
|
262
|
+
async function removeImportDirectory(directory) {
|
|
263
|
+
await rm(directory, { recursive: true, force: true }).catch(() => undefined);
|
|
264
|
+
}
|
|
265
|
+
/** Reads `git diff --name-status -z` output: a status, then a path — and the new path after the old when the status renames or copies. */
|
|
266
|
+
function parseChangedFiles(raw) {
|
|
267
|
+
const changes = [];
|
|
268
|
+
const fields = raw.split('\0');
|
|
269
|
+
for (let at = 0; at < fields.length;) {
|
|
270
|
+
const status = fields[at++];
|
|
271
|
+
if (!status)
|
|
272
|
+
break;
|
|
273
|
+
const letter = status.charAt(0);
|
|
274
|
+
const path = fields[at++];
|
|
275
|
+
const newPath = TWO_PATH_STATUS_LETTERS.includes(letter) ? fields[at++] : path;
|
|
276
|
+
if (!path || !newPath)
|
|
277
|
+
break;
|
|
278
|
+
changes.push({ path: newPath, kind: KIND_OF_STATUS[letter] ?? 'modified' });
|
|
279
|
+
}
|
|
280
|
+
return changes;
|
|
281
|
+
}
|
|
282
|
+
/** The statuses git reports as `S<score>`, carrying the new path after the old one. */
|
|
283
|
+
const TWO_PATH_STATUS_LETTERS = ['R', 'C'];
|
|
284
|
+
const KIND_OF_STATUS = {
|
|
285
|
+
A: 'added',
|
|
286
|
+
C: 'added',
|
|
287
|
+
D: 'deleted',
|
|
288
|
+
M: 'modified',
|
|
289
|
+
R: 'renamed',
|
|
290
|
+
T: 'modified',
|
|
291
|
+
};
|
|
292
|
+
/** Leaves the operator's repository as it was; there is nothing to abort when git never started merging. */
|
|
293
|
+
async function abortMergeInProgress(repoRoot) {
|
|
294
|
+
await openRepo(repoRoot)
|
|
295
|
+
.raw(['merge', '--abort'])
|
|
296
|
+
.catch(() => undefined);
|
|
297
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { parseEnv } from 'node:util';
|
|
6
|
+
import { simpleGit } from 'simple-git';
|
|
7
|
+
import writeFileAtomic from 'write-file-atomic';
|
|
8
|
+
import { ConfigInvalid, messageOf } from '../../domain/errors.js';
|
|
9
|
+
import { refuseSymlinks } from '../find-symlink.js';
|
|
10
|
+
import { onLocalState } from './local-state.js';
|
|
11
|
+
import { ignoreJigDirectory, JIG_DIR } from './run-paths.js';
|
|
12
|
+
export function readCredentialsFile(repoRoot) {
|
|
13
|
+
const file = path.join(repoRoot, CREDENTIALS_FILE);
|
|
14
|
+
const refused = refuseSymlinks([path.join(repoRoot, JIG_DIR), file]);
|
|
15
|
+
if (refused.isErr())
|
|
16
|
+
return Result.err(refused.error);
|
|
17
|
+
if (!existsSync(file))
|
|
18
|
+
return Result.ok({});
|
|
19
|
+
return Result.try({
|
|
20
|
+
try: () => parseEnv(readFileSync(file, 'utf-8')),
|
|
21
|
+
catch: (cause) => new ConfigInvalid({ message: `Cannot read ${CREDENTIALS_FILE}: ${messageOf(cause)}` }),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** Credentials the operator keeps for this repository, relative to its root. */
|
|
25
|
+
export const CREDENTIALS_FILE = `${JIG_DIR}/.env`;
|
|
26
|
+
/** Sets one credential, keeping the rest of the file, readable only by the operator. */
|
|
27
|
+
export async function saveCredential(repoRoot, name, value) {
|
|
28
|
+
const directory = path.join(repoRoot, JIG_DIR);
|
|
29
|
+
const file = path.join(repoRoot, CREDENTIALS_FILE);
|
|
30
|
+
const gitignore = path.join(directory, '.gitignore');
|
|
31
|
+
const refused = refuseSymlinks([directory, gitignore, file]);
|
|
32
|
+
if (refused.isErr())
|
|
33
|
+
return Result.err(refused.error);
|
|
34
|
+
const ignored = await onLocalState(file, async () => {
|
|
35
|
+
await ignoreJigDirectory(repoRoot);
|
|
36
|
+
return simpleGit({ baseDir: repoRoot }).checkIgnore(CREDENTIALS_FILE);
|
|
37
|
+
});
|
|
38
|
+
if (ignored.isErr())
|
|
39
|
+
return Result.err(ignored.error);
|
|
40
|
+
if (ignored.value.length === 0) {
|
|
41
|
+
return Result.err(new ConfigInvalid({
|
|
42
|
+
message: `Not saving a credential to ${CREDENTIALS_FILE}: git tracks that file or does not ignore it.`,
|
|
43
|
+
}));
|
|
44
|
+
}
|
|
45
|
+
return onLocalState(file, async () => {
|
|
46
|
+
const current = existsSync(file) ? await readFile(file, 'utf-8') : '';
|
|
47
|
+
const others = current.split('\n').filter((line) => line && !line.startsWith(`${name}=`));
|
|
48
|
+
const lines = [...others, `${name}="${value}"`];
|
|
49
|
+
await writeFileAtomic(file, `${lines.join('\n')}\n`, { mode: 0o600 });
|
|
50
|
+
});
|
|
51
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { mkdir, readFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import writeFileAtomic from 'write-file-atomic';
|
|
6
|
+
import { ConfigInvalid, messageOf } from '../../domain/errors.js';
|
|
7
|
+
import { runStateSchema } from '../../domain/run-state.js';
|
|
8
|
+
import { onLocalState } from './local-state.js';
|
|
9
|
+
import { makeRunDirectory, stateDirectory } from './run-paths.js';
|
|
10
|
+
/**
|
|
11
|
+
* Keeps each run in `.jig/<runId>/state/run.json`. The file is replaced atomically, so a crash
|
|
12
|
+
* mid-save leaves the previous checkpoint intact.
|
|
13
|
+
*/
|
|
14
|
+
export class LocalRunStore {
|
|
15
|
+
repoRoot;
|
|
16
|
+
constructor(repoRoot) {
|
|
17
|
+
this.repoRoot = repoRoot;
|
|
18
|
+
}
|
|
19
|
+
async load(runId) {
|
|
20
|
+
const file = path.join(stateDirectory(this.repoRoot, runId), STATE_FILE);
|
|
21
|
+
if (!existsSync(file))
|
|
22
|
+
return Result.ok(undefined);
|
|
23
|
+
const contents = await onLocalState(file, () => readFile(file, 'utf-8'));
|
|
24
|
+
return contents.isErr() ? Result.err(contents.error) : parseRun(file, contents.value);
|
|
25
|
+
}
|
|
26
|
+
peek(runId) {
|
|
27
|
+
return this.load(runId);
|
|
28
|
+
}
|
|
29
|
+
async save(state) {
|
|
30
|
+
const directory = stateDirectory(this.repoRoot, state.runId);
|
|
31
|
+
const file = path.join(directory, STATE_FILE);
|
|
32
|
+
return onLocalState(file, async () => {
|
|
33
|
+
await makeRunDirectory(this.repoRoot, state.runId);
|
|
34
|
+
await mkdir(directory, { recursive: true });
|
|
35
|
+
await writeFileAtomic(file, `${JSON.stringify(state, null, 2)}\n`);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const STATE_FILE = 'run.json';
|
|
40
|
+
function parseRun(file, contents) {
|
|
41
|
+
return Result.try({
|
|
42
|
+
try: () => runStateSchema.parse(JSON.parse(contents)),
|
|
43
|
+
catch: (cause) => new ConfigInvalid({ message: `The saved run in ${file} is not valid: ${messageOf(cause)}` }),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { LocalStateUnwritable, messageOf } from '../../domain/errors.js';
|
|
3
|
+
/** Runs a read or write under `.jig/`, naming the path and the cause when the disk refuses. */
|
|
4
|
+
export function onLocalState(file, operation) {
|
|
5
|
+
return Result.tryPromise({
|
|
6
|
+
try: operation,
|
|
7
|
+
catch: (cause) => new LocalStateUnwritable({
|
|
8
|
+
message: `Cannot read or write ${file}: ${messageOf(cause)}`,
|
|
9
|
+
path: file,
|
|
10
|
+
}),
|
|
11
|
+
});
|
|
12
|
+
}
|