@popovych.co/witness 0.28.3 → 0.30.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.
- package/README.md +15 -3
- package/dist/act.d.ts +2 -1
- package/dist/act.js +9 -0
- package/dist/arbiter.d.ts +1 -0
- package/dist/arbiter.js +20 -3
- package/dist/autonomy.js +8 -0
- package/dist/busy.d.ts +38 -0
- package/dist/busy.js +274 -0
- package/dist/caps.d.ts +3 -2
- package/dist/caps.js +24 -3
- package/dist/carry.d.ts +74 -0
- package/dist/carry.js +687 -0
- package/dist/clash.d.ts +23 -0
- package/dist/clash.js +225 -0
- package/dist/cli.js +1 -1
- package/dist/content-sha.d.ts +3 -0
- package/dist/content-sha.js +44 -0
- package/dist/decide-view.d.ts +15 -0
- package/dist/decide-view.js +67 -24
- package/dist/drift.js +5 -3
- package/dist/drive-presence.d.ts +3 -0
- package/dist/drive-presence.js +18 -6
- package/dist/drive.d.ts +23 -5
- package/dist/drive.js +353 -95
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.js +327 -29
- package/dist/gate.d.ts +2 -0
- package/dist/gate.js +262 -43
- package/dist/gates/decompose.js +3 -2
- package/dist/gates/design.js +3 -5
- package/dist/gates/implement.js +15 -11
- package/dist/gates/plan.js +3 -4
- package/dist/gates/ship.js +14 -12
- package/dist/gitio.d.ts +6 -0
- package/dist/gitio.js +32 -2
- package/dist/harness.d.ts +1 -0
- package/dist/harness.js +3 -1
- package/dist/journal.d.ts +10 -1
- package/dist/live.d.ts +6 -1
- package/dist/live.js +15 -3
- package/dist/needs-you.d.ts +18 -2
- package/dist/needs-you.js +55 -17
- package/dist/progress.js +5 -0
- package/dist/recommend.d.ts +3 -0
- package/dist/recommend.js +148 -23
- package/dist/reviewed.d.ts +4 -0
- package/dist/reviewed.js +9 -0
- package/dist/reviewer.d.ts +3 -3
- package/dist/reviewer.js +117 -55
- package/dist/rounds.d.ts +47 -4
- package/dist/rounds.js +448 -61
- package/dist/session-end.d.ts +14 -0
- package/dist/session-end.js +89 -0
- package/dist/settle.d.ts +26 -2
- package/dist/settle.js +140 -15
- package/dist/ship-outcome.d.ts +24 -0
- package/dist/ship-outcome.js +76 -0
- package/dist/ship.d.ts +25 -2
- package/dist/ship.js +716 -127
- package/dist/slice.js +4 -2
- package/dist/stamp.d.ts +6 -0
- package/dist/stamp.js +28 -7
- package/dist/steps.d.ts +1 -0
- package/dist/steps.js +31 -7
- package/dist/verbs/check.js +57 -6
- package/dist/verbs/dashboard.js +24 -17
- package/dist/verbs/decide.d.ts +12 -0
- package/dist/verbs/decide.js +158 -82
- package/dist/verbs/evidence.js +52 -4
- package/dist/verbs/gate.js +5 -2
- package/dist/verbs/log.js +25 -9
- package/dist/verbs/next.d.ts +30 -4
- package/dist/verbs/next.js +628 -131
- package/dist/verbs/turn.js +13 -0
- package/dist/verbs/wait.js +30 -5
- package/dist/worker-stream.d.ts +7 -0
- package/dist/worker-stream.js +150 -5
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/commands/witness.md +21 -3
- package/plugin/hooks/session-dashboard.sh +1 -1
- package/plugin/skills/witness-brainstorm/SKILL.md +2 -2
- package/plugin/skills/witness-decompose/SKILL.md +3 -3
- package/plugin/skills/witness-design/SKILL.md +3 -3
- package/plugin/skills/witness-implement/SKILL.md +7 -7
- package/plugin/skills/witness-plan/SKILL.md +4 -4
- package/plugin/skills/witness-ship/SKILL.md +40 -22
package/dist/carry.js
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { cliAct } from './act.js';
|
|
5
|
+
import { ok, refuse, v } from './refusal.js';
|
|
6
|
+
import { spawnSync } from './spawn.js';
|
|
7
|
+
import { logSafe, shellLine, shellWord, withheldOn } from './toon.js';
|
|
8
|
+
import { branchName } from './worktree.js';
|
|
9
|
+
// Row 243 (design §4.1.1). The carry: when the base moves, witness moves the plan's uncommitted
|
|
10
|
+
// work itself, where `git rebase --autostash` used to, so a clash re-applying it stays in the files
|
|
11
|
+
// and never lands on git's shared stash list. This module holds the git primitives the move is made
|
|
12
|
+
// of. Nothing here touches `refs/stash`: the work is captured with `git stash create` and put back
|
|
13
|
+
// with `git stash apply <sha>`, and it is kept between the two under witness's own refs.
|
|
14
|
+
// Witness's own rebase writes this as its reflog action, so step 0 tells it from a session's.
|
|
15
|
+
export const CARRY_ACTION = 'witness-carry';
|
|
16
|
+
// Sized like gitio.ts's runner: a diff or a stash apply's report can be large.
|
|
17
|
+
const GIT_MAX_BUFFER = 256 * 1024 * 1024;
|
|
18
|
+
// git as the carry runs it: under the C locale, so the words read below (`CONFLICT`, "conflicts in
|
|
19
|
+
// index", a held lock) are git's untranslated ones, and with witness's reflog action. Both streams
|
|
20
|
+
// are kept: a clash's `CONFLICT` goes to stdout, "conflicts in index" to stderr. A git that could
|
|
21
|
+
// not start reads as `code: null`, with the reason on stderr. `GIT_MERGE_VERBOSITY=2`, git's
|
|
22
|
+
// default, outranks a user's `merge.verbosity` and any inherited value (S1-B): at 0 a clashing
|
|
23
|
+
// apply prints no `CONFLICT` line, and step 7 would read its clash as a refused apply.
|
|
24
|
+
export function carryGit(wt, ...args) {
|
|
25
|
+
return carryGitWith(wt, {}, ...args);
|
|
26
|
+
}
|
|
27
|
+
// The same, with `env` added: step 0's backup builds its tree through a scratch `GIT_INDEX_FILE`.
|
|
28
|
+
function carryGitWith(wt, env, ...args) {
|
|
29
|
+
const r = spawnSync('git', args, {
|
|
30
|
+
cwd: wt,
|
|
31
|
+
encoding: 'utf8',
|
|
32
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
33
|
+
maxBuffer: GIT_MAX_BUFFER,
|
|
34
|
+
env: { ...process.env, ...env, LC_ALL: 'C', GIT_REFLOG_ACTION: CARRY_ACTION, GIT_MERGE_VERBOSITY: '2' },
|
|
35
|
+
});
|
|
36
|
+
const failed = r.error !== undefined ? r.error.message : '';
|
|
37
|
+
return { code: r.status, stdout: r.stdout ?? '', stderr: `${r.stderr ?? ''}${failed}` };
|
|
38
|
+
}
|
|
39
|
+
// The carry ref holds the captured work while the move is under way (step 4 to step 7): present
|
|
40
|
+
// means a move was interrupted and the work may not be in the tree.
|
|
41
|
+
export function carryRef(planId) {
|
|
42
|
+
return `refs/witness/carry/${planId}`;
|
|
43
|
+
}
|
|
44
|
+
// A clash's backup: the carry moved here, numbered and never overwritten (step 7).
|
|
45
|
+
export function keptPrefix(planId) {
|
|
46
|
+
return `refs/witness/kept/${planId}/`;
|
|
47
|
+
}
|
|
48
|
+
const OPERATIONS = ['rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD'];
|
|
49
|
+
export function operationInProgress(wt) {
|
|
50
|
+
return OPERATIONS.find((op) => {
|
|
51
|
+
const r = carryGit(wt, 'rev-parse', '--git-path', op);
|
|
52
|
+
return r.code === 0 && existsSync(resolve(wt, r.stdout.replace(/\n$/, '')));
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
// Signal (a) of the guard (§4.1.2). Read NUL-separated, so a name is exactly the file's and never
|
|
56
|
+
// git's C-quoted spelling of it (P51).
|
|
57
|
+
export function unmergedPaths(wt) {
|
|
58
|
+
const r = carryGit(wt, 'ls-files', '-u', '-z');
|
|
59
|
+
if (r.code !== 0)
|
|
60
|
+
return [];
|
|
61
|
+
const byPath = new Map();
|
|
62
|
+
for (const record of r.stdout.split('\0')) {
|
|
63
|
+
const m = /^\d+ ([0-9a-f]+) ([123])\t([^]*)$/.exec(record);
|
|
64
|
+
if (m === null)
|
|
65
|
+
continue;
|
|
66
|
+
const path = m[3];
|
|
67
|
+
const entry = byPath.get(path) ?? { path, stages: {} };
|
|
68
|
+
entry.stages[Number(m[2])] = m[1];
|
|
69
|
+
byPath.set(path, entry);
|
|
70
|
+
}
|
|
71
|
+
return [...byPath.values()];
|
|
72
|
+
}
|
|
73
|
+
// The plan's kept refs, numbered ones in numeric order. A ref a human renamed inside the prefix is
|
|
74
|
+
// still the plan's backup and still listed, after them: only moving it out of `refs/witness/kept/`
|
|
75
|
+
// releases its files (§4.1.2 "The escape").
|
|
76
|
+
function keptNames(wt, planId) {
|
|
77
|
+
const prefix = keptPrefix(planId);
|
|
78
|
+
const r = carryGit(wt, 'for-each-ref', '--format=%(objectname) %(refname)', prefix);
|
|
79
|
+
if (r.code !== 0)
|
|
80
|
+
return [];
|
|
81
|
+
const refs = r.stdout.split('\n').flatMap((line) => {
|
|
82
|
+
const m = /^([0-9a-f]+) (.+)$/.exec(line);
|
|
83
|
+
if (m === null || !m[2].startsWith(prefix))
|
|
84
|
+
return [];
|
|
85
|
+
const rest = m[2].slice(prefix.length);
|
|
86
|
+
return [{ ref: m[2], sha: m[1], ...(/^\d+$/.test(rest) ? { n: Number(rest) } : {}) }];
|
|
87
|
+
});
|
|
88
|
+
return refs.sort((a, b) => a.n !== undefined && b.n !== undefined ? a.n - b.n : a.n !== undefined ? -1 : b.n !== undefined ? 1 : a.ref < b.ref ? -1 : 1);
|
|
89
|
+
}
|
|
90
|
+
// The files a kept ref's message lists (`keepCarry`), read from the raw commit so no configured
|
|
91
|
+
// output encoding re-spells a name. A ref witness did not write lists none.
|
|
92
|
+
function keptFiles(wt, sha) {
|
|
93
|
+
const r = carryGit(wt, 'cat-file', 'commit', sha);
|
|
94
|
+
if (r.code !== 0)
|
|
95
|
+
return [];
|
|
96
|
+
const start = r.stdout.indexOf('\n\n');
|
|
97
|
+
if (start < 0)
|
|
98
|
+
return [];
|
|
99
|
+
const line = r.stdout.slice(start + 2).split('\n').find((l) => l.startsWith('files: '));
|
|
100
|
+
if (line === undefined)
|
|
101
|
+
return [];
|
|
102
|
+
try {
|
|
103
|
+
const files = JSON.parse(line.slice('files: '.length));
|
|
104
|
+
return Array.isArray(files) && files.every((f) => typeof f === 'string') ? files : [];
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
export function keptRefs(wt, planId) {
|
|
111
|
+
return keptNames(wt, planId).map(({ ref, sha }) => ({ ref, sha, files: keptFiles(wt, sha) }));
|
|
112
|
+
}
|
|
113
|
+
// Step 7's clash backup. The carry moves to the plan's next kept ref as a stash-shaped commit with
|
|
114
|
+
// the carry's own tree and parents, so `git stash apply --index <kept>` and `git stash show -p
|
|
115
|
+
// <kept>` read it as they read the carry. Its message lists the clashing files as JSON, each name as
|
|
116
|
+
// `ls-files -u -z` gave it. The ref is made create-only (`''` as the old value), so a backup is never
|
|
117
|
+
// overwritten. Only then is the carry ref deleted, and only while it still names this carry: a
|
|
118
|
+
// carry ref that moved is never dropped. Any failed step refuses `carry-pending`, naming the carry
|
|
119
|
+
// ref, which is kept.
|
|
120
|
+
export function keepCarry(wt, planId, carry, files) {
|
|
121
|
+
const ref = carryRef(planId);
|
|
122
|
+
const pending = (step, out) => refuse([carryPending(planId, `${step} failed: ${gitWords(out)}`)]);
|
|
123
|
+
const resolved = carryGit(wt, 'rev-parse', '--verify', '--quiet', `${carry}^{commit}`);
|
|
124
|
+
const sha = resolved.stdout.trim();
|
|
125
|
+
if (resolved.code !== 0 || sha === '')
|
|
126
|
+
return pending(`reading the carry ${carry}`, resolved.stderr);
|
|
127
|
+
const made = carryGit(wt, 'commit-tree', `${sha}^{tree}`, '-p', `${sha}^1`, '-p', `${sha}^2`, '-m', keptMessage(planId, files));
|
|
128
|
+
const keptSha = made.stdout.trim();
|
|
129
|
+
if (made.code !== 0 || keptSha === '')
|
|
130
|
+
return pending('writing the kept commit', made.stderr);
|
|
131
|
+
const kept = nextKept(wt, planId);
|
|
132
|
+
const created = carryGit(wt, 'update-ref', kept, keptSha, '');
|
|
133
|
+
if (created.code !== 0)
|
|
134
|
+
return pending(`creating ${kept}`, created.stderr);
|
|
135
|
+
const dropped = carryGit(wt, 'update-ref', '-d', ref, sha);
|
|
136
|
+
if (dropped.code !== 0)
|
|
137
|
+
return pending(`deleting ${ref} after ${kept} was made`, dropped.stderr);
|
|
138
|
+
return ok(kept);
|
|
139
|
+
}
|
|
140
|
+
// A kept ref's commit message: the files as JSON, each name exactly as git gave it, on the line
|
|
141
|
+
// `keptFiles` reads; `note` (ending in a blank line) says what the backup is when it is no carry.
|
|
142
|
+
function keptMessage(planId, files, note = '') {
|
|
143
|
+
return `witness kept ${planId}\n\n${note}files: ${JSON.stringify(files)}`;
|
|
144
|
+
}
|
|
145
|
+
// The plan's next kept ref: one past the highest number, so a backup is never overwritten (the ref
|
|
146
|
+
// is then made create-only).
|
|
147
|
+
function nextKept(wt, planId) {
|
|
148
|
+
const n = Math.max(0, ...keptNames(wt, planId).flatMap((k) => (k.n !== undefined ? [k.n] : []))) + 1;
|
|
149
|
+
return `${keptPrefix(planId)}${n}`;
|
|
150
|
+
}
|
|
151
|
+
// git's own words in a refusal's cell: cut, and spelled out where they hold a control character.
|
|
152
|
+
function gitWords(out) {
|
|
153
|
+
return logSafe(out.trim().slice(0, 200)) || 'git printed nothing';
|
|
154
|
+
}
|
|
155
|
+
// `carry-pending` (exit 2): the move is unfinished and the carry ref holds the plan's work, kept. It
|
|
156
|
+
// shows the ref both ways — the worktree versions, and the staged ones beside them — and names
|
|
157
|
+
// `witness ship`, whose step 0 finishes the move.
|
|
158
|
+
export function carryPending(planId, got) {
|
|
159
|
+
const ref = carryRef(planId);
|
|
160
|
+
return v(ref, 'carry-pending', got, `${ref} holds the plan's uncommitted work and is kept — ${seeWork(ref)}; ${cliAct('ship', planId).line} finishes the move`);
|
|
161
|
+
}
|
|
162
|
+
// The carry ref shown both ways: the worktree versions, and the staged ones `git stash show -p`
|
|
163
|
+
// leaves out (P43). Any stash-shaped commit reads so: check shows a leftover autostash entry, a carry
|
|
164
|
+
// ref and a clash's backup with it (§4.1.4).
|
|
165
|
+
export function seeWork(ref) {
|
|
166
|
+
return `see it with ${shellLine(['git', 'stash', 'show', '-p', ref])} beside ${shellLine(['git', 'diff', `${ref}^1`, `${ref}^2`])} (the staged versions)`;
|
|
167
|
+
}
|
|
168
|
+
// Step 0.1. The plan's worktree is gone (an abandoned plan): no tree is left for the move to finish
|
|
169
|
+
// in, so the ref is shown and kept, and where the work goes is a human's call (D168).
|
|
170
|
+
export function carryGone(planId, wt) {
|
|
171
|
+
const ref = carryRef(planId);
|
|
172
|
+
return v(ref, 'carry-pending', `the plan's worktree ${shellWord(wt)} is gone, and ${ref} still holds its uncommitted work`, `${ref} is kept and never deleted for you — ${seeWork(ref)}, from the repository; with no worktree to finish the move in, a human decides where the work goes`);
|
|
173
|
+
}
|
|
174
|
+
// Step 0.3. HEAD detached or on another branch: the work goes back only onto the plan's branch, so
|
|
175
|
+
// nothing is compared, applied or moved until the worktree is back on it.
|
|
176
|
+
export function offBranchPending(planId, head) {
|
|
177
|
+
const ref = carryRef(planId);
|
|
178
|
+
const branch = branchName(planId);
|
|
179
|
+
const where = head === '' ? 'HEAD is detached' : `HEAD is on ${shellWord(head.replace(/^refs\/heads\//, ''))}`;
|
|
180
|
+
return v(ref, 'carry-pending', `${where}, not on the plan's branch ${branch}, so the plan's work was not put back`, `the worktree back on the plan's branch with ${shellLine(['git', 'switch', branch])}, then ${cliAct('ship', planId).line}, which finishes the move — `
|
|
181
|
+
+ `${ref} keeps the plan's work meanwhile; ${seeWork(ref)}`);
|
|
182
|
+
}
|
|
183
|
+
// Step 0.4 (P43, P52). Unmerged entries the carry did not leave — a session's own clash, its own
|
|
184
|
+
// `git stash pop` say: each named with its way out once the session has resolved it, then the carry
|
|
185
|
+
// ref, kept. Witness resolves none of them (n2).
|
|
186
|
+
export function sessionUnmerged(planId, files) {
|
|
187
|
+
return [
|
|
188
|
+
...files.map((f) => v(shellWord(f.path), 'carry-pending', 'unmerged — not the carry\'s own clash (its stages are not the carry\'s blobs): a session\'s, from its own git stash pop say', `the session's own clash resolved by the session, then ${remedyLine(['git', 'add', '--', f.path])}`)),
|
|
189
|
+
carryPending(planId, 'the worktree holds unmerged entries of a session\'s making, so the plan\'s work was not put back into it'),
|
|
190
|
+
];
|
|
191
|
+
}
|
|
192
|
+
// Step 0.7. Anything else: neither the work already back nor a clean tracked tree. The tree is left
|
|
193
|
+
// as it stands, never reset; the row shows the carry both ways and the steps to put it back by hand
|
|
194
|
+
// (P43: on a clean tracked tree an `--index` apply, or a plain one where git refuses the staged half),
|
|
195
|
+
// and, in words, that a tree already holding the work keeps the ref as a backup rather than deleting it.
|
|
196
|
+
export function restorePending(planId, got) {
|
|
197
|
+
return v(carryRef(planId), 'carry-pending', got, restoreSteps(planId));
|
|
198
|
+
}
|
|
199
|
+
function restoreSteps(planId) {
|
|
200
|
+
const ref = carryRef(planId);
|
|
201
|
+
return `${ref} holds the plan's uncommitted work and is kept, and the tree is left as it stands — ${seeWork(ref)}. To put it back by hand, `
|
|
202
|
+
+ `on a clean tracked tree: ${shellLine(['git', 'stash', 'apply', '--index', ref])}, or ${shellLine(['git', 'stash', 'apply', ref])} where git answers `
|
|
203
|
+
+ `conflicts in index. If the tree already holds the work, move ${ref} to an unused number under ${keptPrefix(planId)} rather than `
|
|
204
|
+
+ `deleting it, so the backup is kept; then ${cliAct('ship', planId).line}`;
|
|
205
|
+
}
|
|
206
|
+
// Step 0.2, fix round 1. Witness's own crashed rebase, touched since it stopped (a session partway
|
|
207
|
+
// through resolving it, say), is never aborted: finishing or dropping it is the human's choice, given
|
|
208
|
+
// in prose and never as a runnable row, beside the restore steps.
|
|
209
|
+
export function touchedRebasePending(planId, why) {
|
|
210
|
+
return v(carryRef(planId), 'carry-pending', `witness's own rebase from the interrupted move was touched since it stopped — ${why} — so it was not aborted`, `the rebase is a human's to finish: ${shellLine(['git', 'rebase', '--continue'])} once every file is resolved and staged, or `
|
|
211
|
+
+ `${shellLine(['git', 'rebase', '--abort'])}, which drops what was resolved in it — then ${cliAct('ship', planId).line}, which finishes the move. `
|
|
212
|
+
+ restoreSteps(planId));
|
|
213
|
+
}
|
|
214
|
+
// §4.1.5 (S1-3). A lock another git process holds, read first from git's own words (C locale), then
|
|
215
|
+
// from the lock files themselves: Apple's git words a held index lock at `stash create` and `stash
|
|
216
|
+
// apply` only as "could not write index". `locks` names them as `git rev-parse --git-path` resolves
|
|
217
|
+
// them, so a linked worktree's index lock and the shared carry ref's are each found where git keeps
|
|
218
|
+
// them. The path, or nothing.
|
|
219
|
+
const LOCK_WORDS = /Unable to create '([^'\n]+\.lock)': File exists/;
|
|
220
|
+
export function heldLock(wt, out, locks = ['index.lock']) {
|
|
221
|
+
const said = LOCK_WORDS.exec(out);
|
|
222
|
+
if (said !== null)
|
|
223
|
+
return said[1];
|
|
224
|
+
for (const name of locks) {
|
|
225
|
+
const r = carryGit(wt, 'rev-parse', '--git-path', name);
|
|
226
|
+
if (r.code !== 0)
|
|
227
|
+
continue;
|
|
228
|
+
const path = resolve(wt, r.stdout.replace(/\n$/, ''));
|
|
229
|
+
if (existsSync(path))
|
|
230
|
+
return path;
|
|
231
|
+
}
|
|
232
|
+
return undefined;
|
|
233
|
+
}
|
|
234
|
+
// `index-locked` (exit 3, transient): a held lock, the index's or the carry ref's. The lock's path is
|
|
235
|
+
// `got`. Its want says what removing it takes, whether the work waits in the carry ref, and — when
|
|
236
|
+
// witness's own failed rebase could not be undone (`unfinished`) — that it may still be in progress.
|
|
237
|
+
// "Nothing moved" is said only when it is true.
|
|
238
|
+
export function lockedRow(planId, lock, carried, unfinished = false) {
|
|
239
|
+
const ship = cliAct('ship', planId).line;
|
|
240
|
+
const held = `${shellWord(lock)} released — remove it if no git process is running`;
|
|
241
|
+
const work = carried ? `${carryRef(planId)} keeps the plan's work meanwhile, and ${ship} finishes the move` : `then ${ship}`;
|
|
242
|
+
if (unfinished) {
|
|
243
|
+
return v('lock', 'index-locked', lock, `${held}; witness's own rebase did not finish and was not undone — `
|
|
244
|
+
+ `${shellLine(['git', 'rebase', '--abort'])} ends it if one is still in progress; ${work}`);
|
|
245
|
+
}
|
|
246
|
+
return v('lock', 'index-locked', lock, carried ? `${held}; ${work}` : `${held}, ${work}; nothing moved`);
|
|
247
|
+
}
|
|
248
|
+
// HEAD's reflog subjects in this worktree, newest first. Where HEAD keeps no reflog of its own, git
|
|
249
|
+
// reads the branch's in its place while HEAD is attached, and none while it is detached; neither
|
|
250
|
+
// ever holds witness's `(start)`, which only HEAD's own log records — so no proof is read from it.
|
|
251
|
+
export function headReflog(wt) {
|
|
252
|
+
const r = carryGit(wt, 'reflog', 'show', '--format=%gs', 'HEAD');
|
|
253
|
+
return r.code === 0 ? r.stdout.split('\n').filter((s) => s !== '') : [];
|
|
254
|
+
}
|
|
255
|
+
const ownEntry = (s) => s.startsWith(`${CARRY_ACTION} `);
|
|
256
|
+
// The reading both steps share. `entries` newest first, walked back to witness's own `(start)`:
|
|
257
|
+
// every entry on the way carries witness's action, else a session's entry stands after it (or the
|
|
258
|
+
// newest `(start)` is the session's own). No `(start)` reached is silence.
|
|
259
|
+
function readOwner(entries) {
|
|
260
|
+
for (const s of entries) {
|
|
261
|
+
if (!ownEntry(s))
|
|
262
|
+
return 'session';
|
|
263
|
+
if (s.startsWith(`${CARRY_ACTION} (start)`))
|
|
264
|
+
return 'witness';
|
|
265
|
+
}
|
|
266
|
+
return 'silent';
|
|
267
|
+
}
|
|
268
|
+
// Step 6. After witness's own rebase failed, the operation in progress is read from what HEAD's
|
|
269
|
+
// reflog gained since `before` (read just before the call): every new entry witness's, one of them
|
|
270
|
+
// its `(start)`. An operation that is no rebase, or git's "already a rebase-… directory", is a
|
|
271
|
+
// session's. No new entry at all (no HEAD reflog, or a session's rebase that has written nothing yet,
|
|
272
|
+
// an editor open on its todo) is silence.
|
|
273
|
+
export function rebaseOwnerSince(wt, op, out, before) {
|
|
274
|
+
if (op !== 'rebase-merge' && op !== 'rebase-apply')
|
|
275
|
+
return 'session';
|
|
276
|
+
if (/already a rebase-(?:merge|apply) directory/.test(out))
|
|
277
|
+
return 'session';
|
|
278
|
+
const after = headReflog(wt);
|
|
279
|
+
const fresh = after.slice(0, Math.max(0, after.length - before.length));
|
|
280
|
+
return fresh.some((s) => !ownEntry(s)) ? 'session' : readOwner(fresh);
|
|
281
|
+
}
|
|
282
|
+
// Step 0.2 (P40, P53). A crashed move's rebase is witness's own only when HEAD's latest `(start)`
|
|
283
|
+
// reflog entry carries witness's action, every HEAD entry after it does too, and its orig-head is
|
|
284
|
+
// `<carry>^1`, where witness's rebase began. A session that continued witness's rebase has written
|
|
285
|
+
// `rebase (continue)` entries of its own, so its resolved commits are never dropped; a session's own
|
|
286
|
+
// rebase from the same HEAD writes its own `(start)`. With no HEAD reflog file, git would read the
|
|
287
|
+
// branch's log in HEAD's place, so silence is read from the file's absence. An orig-head that is not
|
|
288
|
+
// `<carry>^1` is positively not this move's rebase.
|
|
289
|
+
export function witnessOwnRebase(wt, carry) {
|
|
290
|
+
const op = operationInProgress(wt);
|
|
291
|
+
if (op !== 'rebase-merge' && op !== 'rebase-apply')
|
|
292
|
+
return 'session';
|
|
293
|
+
const reading = gitPathExists(wt, 'logs/HEAD') ? readOwner(headReflog(wt)) : 'silent';
|
|
294
|
+
if (reading === 'session')
|
|
295
|
+
return 'session';
|
|
296
|
+
const origHead = readGitPath(wt, `${op}/orig-head`);
|
|
297
|
+
const base = carryGit(wt, 'rev-parse', '--verify', '--quiet', `${carry}^1`).stdout.trim();
|
|
298
|
+
return origHead !== undefined && base !== '' && origHead === base ? reading : 'session';
|
|
299
|
+
}
|
|
300
|
+
function gitPath(wt, name) {
|
|
301
|
+
const r = carryGit(wt, 'rev-parse', '--git-path', name);
|
|
302
|
+
return r.code === 0 ? resolve(wt, r.stdout.replace(/\n$/, '')) : undefined;
|
|
303
|
+
}
|
|
304
|
+
function gitPathExists(wt, name) {
|
|
305
|
+
const path = gitPath(wt, name);
|
|
306
|
+
return path !== undefined && existsSync(path);
|
|
307
|
+
}
|
|
308
|
+
function readGitPath(wt, name) {
|
|
309
|
+
const path = gitPath(wt, name);
|
|
310
|
+
if (path === undefined)
|
|
311
|
+
return undefined;
|
|
312
|
+
try {
|
|
313
|
+
return readFileSync(path, 'utf8').trim();
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
export function freshStop(wt) {
|
|
320
|
+
const unmerged = unmergedPaths(wt);
|
|
321
|
+
if (unmerged.length === 0)
|
|
322
|
+
return { fresh: false, why: 'nothing is unmerged any more: its conflicts were resolved and staged' };
|
|
323
|
+
const conflicted = new Set(unmerged.map((p) => p.path));
|
|
324
|
+
const outside = (out) => [...new Set(out.split('\0'))].filter((p) => p !== '' && !conflicted.has(p));
|
|
325
|
+
const named = (paths) => paths.map((p) => shellWord(p)).join(', ');
|
|
326
|
+
const worktree = carryGit(wt, 'diff', '--name-only', '-z', '--no-renames', '--no-relative');
|
|
327
|
+
if (worktree.code !== 0)
|
|
328
|
+
return { fresh: false, why: `git could not list the worktree's changes: ${gitWords(worktree.stderr)}` };
|
|
329
|
+
const edited = outside(worktree.stdout);
|
|
330
|
+
if (edited.length > 0)
|
|
331
|
+
return { fresh: false, why: `files changed in the worktree beyond the conflicted ones: ${named(edited)}` };
|
|
332
|
+
const pick = carryGit(wt, 'rev-parse', '--verify', '--quiet', 'REBASE_HEAD^{commit}').stdout.trim();
|
|
333
|
+
if (pick === '')
|
|
334
|
+
return { fresh: false, why: 'the commit the rebase stopped on (REBASE_HEAD) cannot be read' };
|
|
335
|
+
const replay = carryGit(wt, 'merge-tree', '--write-tree', `--merge-base=${pick}^`, 'HEAD', pick);
|
|
336
|
+
const tree = replay.stdout.split('\n')[0].trim();
|
|
337
|
+
if ((replay.code !== 0 && replay.code !== 1) || !/^[0-9a-f]+$/.test(tree)) {
|
|
338
|
+
return { fresh: false, why: `git could not replay the stopped commit to compare the index (git merge-tree --merge-base, git 2.40 and later): ${gitWords(replay.stderr)}` };
|
|
339
|
+
}
|
|
340
|
+
const index = carryGit(wt, 'diff', '--cached', '--name-only', '-z', '--no-renames', '--no-relative', tree);
|
|
341
|
+
if (index.code !== 0)
|
|
342
|
+
return { fresh: false, why: `git could not compare the index: ${gitWords(index.stderr)}` };
|
|
343
|
+
const restaged = outside(index.stdout);
|
|
344
|
+
if (restaged.length > 0)
|
|
345
|
+
return { fresh: false, why: `staged changes the rebase's stop did not make: ${named(restaged)}` };
|
|
346
|
+
return { fresh: true, unmerged };
|
|
347
|
+
}
|
|
348
|
+
// Step 0.2, fix round 1. Before witness aborts its own stopped rebase, the conflicted files' worktree
|
|
349
|
+
// bytes are kept in the plan's next kept ref, so an edit inside a still-unmerged file that was never
|
|
350
|
+
// staged survives the abort. The tree is built in a scratch index (`GIT_INDEX_FILE`, seeded from
|
|
351
|
+
// HEAD, the files added from the worktree, a deleted one removed): the real index is untouched and
|
|
352
|
+
// nothing lands on the stash list. The commit's parent is the stop's HEAD, so `git show <ref>` shows
|
|
353
|
+
// the files against it. Any failed step refuses `carry-pending`, and nothing is aborted. A retry at
|
|
354
|
+
// the same stop (its abort met a held lock, or the run was killed after the backup) finds the backup
|
|
355
|
+
// the last try wrote and reuses it, never writing an identical one (the final review's M6).
|
|
356
|
+
export function keepStopped(wt, planId, files) {
|
|
357
|
+
const pending = (step, out) => refuse([carryPending(planId, `${step} failed, so witness's own stopped rebase was not aborted: ${gitWords(out)}`)]);
|
|
358
|
+
const dir = mkdtempSync(join(tmpdir(), 'witness-kept-'));
|
|
359
|
+
try {
|
|
360
|
+
const scratch = { GIT_INDEX_FILE: join(dir, 'index') };
|
|
361
|
+
const seeded = carryGitWith(wt, scratch, 'read-tree', 'HEAD');
|
|
362
|
+
if (seeded.code !== 0)
|
|
363
|
+
return pending('seeding a scratch index from HEAD', seeded.stderr);
|
|
364
|
+
const added = carryGitWith(wt, scratch, 'update-index', '--add', '--remove', '--', ...files);
|
|
365
|
+
if (added.code !== 0)
|
|
366
|
+
return pending('adding the conflicted files to the scratch index', added.stderr);
|
|
367
|
+
const written = carryGitWith(wt, scratch, 'write-tree');
|
|
368
|
+
const tree = written.stdout.trim();
|
|
369
|
+
if (written.code !== 0 || tree === '')
|
|
370
|
+
return pending('writing the scratch tree', written.stderr);
|
|
371
|
+
const stopped = carryGit(wt, 'rev-parse', '--verify', '--quiet', 'HEAD^{commit}');
|
|
372
|
+
const head = stopped.stdout.trim();
|
|
373
|
+
if (stopped.code !== 0 || head === '')
|
|
374
|
+
return pending('reading the stop\'s HEAD', stopped.stderr);
|
|
375
|
+
const same = keptAlike(wt, planId, tree, head, files);
|
|
376
|
+
if (same !== undefined)
|
|
377
|
+
return ok(same);
|
|
378
|
+
const note = 'the conflicted files of witness\'s stopped rebase as the worktree held them, kept before step 0 aborted it\n\n';
|
|
379
|
+
const made = carryGit(wt, 'commit-tree', tree, '-p', head, '-m', keptMessage(planId, files, note));
|
|
380
|
+
const sha = made.stdout.trim();
|
|
381
|
+
if (made.code !== 0 || sha === '')
|
|
382
|
+
return pending('writing the kept commit', made.stderr);
|
|
383
|
+
const kept = nextKept(wt, planId);
|
|
384
|
+
const created = carryGit(wt, 'update-ref', kept, sha, '');
|
|
385
|
+
if (created.code !== 0)
|
|
386
|
+
return pending(`creating ${kept}`, created.stderr);
|
|
387
|
+
return ok(kept);
|
|
388
|
+
}
|
|
389
|
+
finally {
|
|
390
|
+
rmSync(dir, { recursive: true, force: true });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
// M6. A kept ref under the plan's prefix that already holds this backup: the same tree, the stop's
|
|
394
|
+
// HEAD as its one parent, and the same files listed. Anything git cannot answer is no match.
|
|
395
|
+
function keptAlike(wt, planId, tree, parent, files) {
|
|
396
|
+
const listed = JSON.stringify(files);
|
|
397
|
+
for (const k of keptRefs(wt, planId)) {
|
|
398
|
+
if (JSON.stringify(k.files) !== listed)
|
|
399
|
+
continue;
|
|
400
|
+
const r = carryGit(wt, 'rev-parse', `${k.sha}^{tree}`, `${k.sha}^@`);
|
|
401
|
+
if (r.code === 0 && r.stdout.trim().split('\n').join(' ') === `${tree} ${parent}`)
|
|
402
|
+
return k.ref;
|
|
403
|
+
}
|
|
404
|
+
return undefined;
|
|
405
|
+
}
|
|
406
|
+
// c5. `git merge-tree --write-tree --merge-base` arrived in git 2.40. Read from `git --version`'s
|
|
407
|
+
// line, a Windows build's suffix included; a line that names no version reads as old, which only
|
|
408
|
+
// skips the comparison (step 0.5).
|
|
409
|
+
export function gitAtLeast(versionLine, major, minor) {
|
|
410
|
+
const m = /\bgit version (\d+)\.(\d+)/.exec(versionLine);
|
|
411
|
+
if (m === null)
|
|
412
|
+
return false;
|
|
413
|
+
const [a, b] = [Number(m[1]), Number(m[2])];
|
|
414
|
+
return a > major || (a === major && b >= minor);
|
|
415
|
+
}
|
|
416
|
+
// The blob a commit holds at a path, or nothing where it holds none (step 0.4 compares a stage with
|
|
417
|
+
// it). `<rev>:<path>` reads the path as written: no pathspec magic.
|
|
418
|
+
export function blobAt(wt, rev, path) {
|
|
419
|
+
const r = carryGit(wt, 'rev-parse', '--verify', '--quiet', `${rev}:${path}`);
|
|
420
|
+
const sha = r.stdout.trim();
|
|
421
|
+
return r.code === 0 && /^[0-9a-f]+$/.test(sha) ? sha : undefined;
|
|
422
|
+
}
|
|
423
|
+
// Step 0.5 (P35, P43). Whether the plan's work is already back: the tree compared, both halves, with
|
|
424
|
+
// the carry replayed onto HEAD (`git merge-tree --write-tree --merge-base=<carry>^1 HEAD <side>`, git
|
|
425
|
+
// 2.40 and later). The worktree side is held against the tracked tree a fresh `git stash create`
|
|
426
|
+
// records (untracked files are never in it), the index side against that capture's index; a capture
|
|
427
|
+
// that prints nothing leaves both halves HEAD's tree. A replay that conflicts (exit 1) is never
|
|
428
|
+
// equal. `lock`: the fresh capture met a held index lock (S1-3).
|
|
429
|
+
export function workAlreadyBack(wt, carry) {
|
|
430
|
+
const replayed = (side) => {
|
|
431
|
+
const r = carryGit(wt, 'merge-tree', '--write-tree', `--merge-base=${carry}^1`, 'HEAD', side);
|
|
432
|
+
const tree = r.stdout.split('\n')[0].trim();
|
|
433
|
+
return r.code === 0 && /^[0-9a-f]+$/.test(tree) ? tree : undefined;
|
|
434
|
+
};
|
|
435
|
+
const worktree = replayed(carry);
|
|
436
|
+
const index = replayed(`${carry}^2`);
|
|
437
|
+
if (worktree === undefined || index === undefined)
|
|
438
|
+
return { back: false };
|
|
439
|
+
const fresh = carryGit(wt, 'stash', 'create');
|
|
440
|
+
if (fresh.code !== 0) {
|
|
441
|
+
const lock = heldLock(wt, `${fresh.stdout}${fresh.stderr}`);
|
|
442
|
+
return lock === undefined ? { back: false } : { back: false, lock };
|
|
443
|
+
}
|
|
444
|
+
const sha = fresh.stdout.trim();
|
|
445
|
+
const tree = (rev) => {
|
|
446
|
+
const r = carryGit(wt, 'rev-parse', '--verify', '--quiet', `${rev}^{tree}`);
|
|
447
|
+
return r.code === 0 && r.stdout.trim() !== '' ? r.stdout.trim() : undefined;
|
|
448
|
+
};
|
|
449
|
+
const now = sha === '' ? { worktree: tree('HEAD'), index: tree('HEAD') } : { worktree: tree(sha), index: tree(`${sha}^2`) };
|
|
450
|
+
return { back: now.worktree !== undefined && now.worktree === worktree && now.index === index };
|
|
451
|
+
}
|
|
452
|
+
// Step 2 (P19). An operation a session started is its own to finish: witness never aborts it, nor
|
|
453
|
+
// applies into it. The row names its `--continue` and `--abort`. A `rebase-apply` holding `applying`
|
|
454
|
+
// is `git am`'s.
|
|
455
|
+
const OP_VERB = {
|
|
456
|
+
'rebase-merge': 'rebase', 'rebase-apply': 'rebase', MERGE_HEAD: 'merge', CHERRY_PICK_HEAD: 'cherry-pick', REVERT_HEAD: 'revert',
|
|
457
|
+
};
|
|
458
|
+
// `silent`: a rebase whose reflog cannot tell whose it is (`RebaseOwner`), so it may be witness's own:
|
|
459
|
+
// the want then adds the design's sentence for a human who knows witness started it. A rebase the
|
|
460
|
+
// reflog shows to be a session's never gets it.
|
|
461
|
+
export function operationRefusal(wt, planId, op, silent = false) {
|
|
462
|
+
const applying = op === 'rebase-apply' && carryGit(wt, 'rev-parse', '--git-path', 'rebase-apply/applying');
|
|
463
|
+
const verb = applying && applying.code === 0 && existsSync(resolve(wt, applying.stdout.replace(/\n$/, ''))) ? 'am' : OP_VERB[op];
|
|
464
|
+
const ship = cliAct('ship', planId).line;
|
|
465
|
+
const abort = shellLine(['git', verb, '--abort']);
|
|
466
|
+
const own = silent && verb === 'rebase' ? `; if the rebase is witness's own (its reflog cannot tell), run ${abort}, then re-run ${ship}` : '';
|
|
467
|
+
return v(op, 'operation-in-progress', `a git ${verb} is in progress in the worktree`, `it finished with ${shellLine(['git', verb, '--continue'])}, or ended with ${abort} — `
|
|
468
|
+
+ `an operation a session started is the session's to end, never witness's — then ${ship}${own}`);
|
|
469
|
+
}
|
|
470
|
+
// The files an intent-to-add entry (`git add -N`) holds: the worktree side of `git diff` lists them as
|
|
471
|
+
// added, and nothing else is added on that side.
|
|
472
|
+
function intentToAdd(wt) {
|
|
473
|
+
const r = carryGit(wt, 'diff', '--name-only', '-z', '--no-renames', '--no-relative', '--diff-filter=A');
|
|
474
|
+
return r.code === 0 ? r.stdout.split('\0').filter((f) => f !== '') : [];
|
|
475
|
+
}
|
|
476
|
+
// Step 4. The plan's uncommitted work captured with `git stash create`, which writes a stash-shaped
|
|
477
|
+
// commit and never touches `refs/stash`, the list every worktree shares (P2). The commit goes to the
|
|
478
|
+
// carry ref, create-only. `undefined`: nothing to carry, only when git also lists no tracked change.
|
|
479
|
+
// Every refusal comes before anything moves.
|
|
480
|
+
export function captureCarry(wt, planId) {
|
|
481
|
+
const ship = cliAct('ship', planId).line;
|
|
482
|
+
const made = carryGit(wt, 'stash', 'create');
|
|
483
|
+
if (made.code !== 0) {
|
|
484
|
+
const out = `${made.stdout}${made.stderr}`;
|
|
485
|
+
const lock = heldLock(wt, out);
|
|
486
|
+
if (lock !== undefined)
|
|
487
|
+
return refuse([lockedRow(planId, lock, false)]);
|
|
488
|
+
const ita = intentToAdd(wt);
|
|
489
|
+
// P14 (S1-7): git cannot capture an intent-to-add entry; each is named with both ways out.
|
|
490
|
+
if (ita.length > 0) {
|
|
491
|
+
return refuse(ita.map((f) => v(shellWord(f), 'carry-refused', 'an intent-to-add entry (git add -N), which git stash create cannot capture', `${remedyLine(['git', 'add', '--', f])} stages it whole, or ${remedyLine(['git', 'reset', '--', f])} drops the intent and leaves `
|
|
492
|
+
+ `the file untracked — nothing moved; then ${ship}`)));
|
|
493
|
+
}
|
|
494
|
+
return refuse([v('stash', 'carry-refused', `git stash create failed: ${gitWords(out)}`, `a worktree whose changes git stash create can capture — nothing moved; fix what git names, then ${ship}`)]);
|
|
495
|
+
}
|
|
496
|
+
const sha = made.stdout.trim();
|
|
497
|
+
if (sha === '') {
|
|
498
|
+
const status = carryGit(wt, 'status', '--porcelain', '--untracked-files=no');
|
|
499
|
+
if (status.code === 0 && status.stdout === '')
|
|
500
|
+
return ok(undefined);
|
|
501
|
+
return refuse([v('stash', 'carry-refused', status.code === 0
|
|
502
|
+
? `git stash create captured nothing, yet git status lists tracked changes: ${gitWords(status.stdout)}`
|
|
503
|
+
: `git stash create captured nothing, and git status failed: ${gitWords(status.stderr)}`, `a worktree whose changes git stash create can capture — nothing moved; then ${ship}`)]);
|
|
504
|
+
}
|
|
505
|
+
const ref = carryRef(planId);
|
|
506
|
+
const written = carryGit(wt, 'update-ref', ref, sha, '');
|
|
507
|
+
if (written.code !== 0) {
|
|
508
|
+
const out = `${written.stdout}${written.stderr}`;
|
|
509
|
+
const lock = heldLock(wt, out, [`${ref}.lock`]);
|
|
510
|
+
if (lock !== undefined)
|
|
511
|
+
return refuse([lockedRow(planId, lock, false)]);
|
|
512
|
+
return refuse([v(ref, 'carry-refused', `writing ${ref} failed: ${gitWords(out)}`, `a writable ${ref} — nothing moved; then ${ship}`)]);
|
|
513
|
+
}
|
|
514
|
+
return ok(sha);
|
|
515
|
+
}
|
|
516
|
+
// Step 5. `git reset --hard`, then the tracked tree verified clean. `git checkout -- .` would leave
|
|
517
|
+
// staged work behind (P13), and with a user's `rebase.autoStash=true` that work brings #86 straight
|
|
518
|
+
// back (P15). A reset that fails or leaves the tree dirty (a file held open on Windows) refuses
|
|
519
|
+
// `carry-pending`: the carry ref is kept, and step 0 finishes the move.
|
|
520
|
+
export function cleanTree(wt, planId) {
|
|
521
|
+
const reset = carryGit(wt, 'reset', '--hard', '--quiet');
|
|
522
|
+
if (reset.code !== 0) {
|
|
523
|
+
const out = `${reset.stdout}${reset.stderr}`;
|
|
524
|
+
const lock = heldLock(wt, out);
|
|
525
|
+
if (lock !== undefined)
|
|
526
|
+
return refuse([lockedRow(planId, lock, true)]);
|
|
527
|
+
return refuse([carryPending(planId, `git reset --hard failed: ${gitWords(out)}`)]);
|
|
528
|
+
}
|
|
529
|
+
const status = carryGit(wt, 'status', '--porcelain', '--untracked-files=no');
|
|
530
|
+
if (status.code !== 0)
|
|
531
|
+
return refuse([carryPending(planId, `git status failed after git reset --hard: ${gitWords(status.stderr)}`)]);
|
|
532
|
+
if (status.stdout !== '')
|
|
533
|
+
return refuse([carryPending(planId, `the tracked tree is still not clean after git reset --hard: ${gitWords(status.stdout)}`)]);
|
|
534
|
+
return ok(undefined);
|
|
535
|
+
}
|
|
536
|
+
// Every path the carry writes: its worktree side and its index side, against its base.
|
|
537
|
+
function carryPaths(wt, carry) {
|
|
538
|
+
const paths = new Set();
|
|
539
|
+
for (const side of [carry, `${carry}^2`]) {
|
|
540
|
+
const r = carryGit(wt, 'diff-tree', '-r', '--name-only', '-z', '--no-renames', `${carry}^1`, side);
|
|
541
|
+
if (r.code !== 0)
|
|
542
|
+
return undefined;
|
|
543
|
+
for (const p of r.stdout.split('\0'))
|
|
544
|
+
if (p !== '')
|
|
545
|
+
paths.add(p);
|
|
546
|
+
}
|
|
547
|
+
return [...paths];
|
|
548
|
+
}
|
|
549
|
+
const CONFLICT = /^CONFLICT \(/m;
|
|
550
|
+
// Step 7. `git stash apply --index <carry>`, so the staged versions go back staged. Before anything
|
|
551
|
+
// is written, an untracked file where the carry or its index writes one refuses (S1-1): in a witness
|
|
552
|
+
// worktree's sparse checkout the apply would replace it silently. The outcomes:
|
|
553
|
+
// - clean: the carry ref is dropped, checked (S1-6) — a failed drop is a held lock or a refusal,
|
|
554
|
+
// never a carry ref left standing behind a reported success;
|
|
555
|
+
// - clash: no unmerged entries before, git printed `CONFLICT`, unmerged entries after — the carry
|
|
556
|
+
// moves to the plan's next kept ref, listing the files (`keepCarry`);
|
|
557
|
+
// - "conflicts in index" (P25): a plain apply instead, and the carry is kept like a clash backup,
|
|
558
|
+
// listing its staged files, since a staged-only version survives only there;
|
|
559
|
+
// - anything else: refused, or a held lock — the carry ref kept either way.
|
|
560
|
+
// git's words are read only as the carry's runner gives them: in the C locale.
|
|
561
|
+
export function reapply(wt, planId, carry) {
|
|
562
|
+
const writes = carryPaths(wt, carry);
|
|
563
|
+
if (writes === undefined)
|
|
564
|
+
return { kind: 'refused', out: `git could not read which files the carry ${carry} writes` };
|
|
565
|
+
const inTheWay = untrackedInTheWay(wt, writes);
|
|
566
|
+
if (inTheWay === undefined)
|
|
567
|
+
return { kind: 'refused', out: 'git could not list the untracked files, so the plan\'s work was not put back over them' };
|
|
568
|
+
if (inTheWay.length > 0) {
|
|
569
|
+
return { kind: 'refused', out: `untracked files sit where the plan's work goes back — ${inTheWay.map((f) => shellWord(f)).join(', ')} — `
|
|
570
|
+
+ 'moved aside, the work goes back; nothing was written over them' };
|
|
571
|
+
}
|
|
572
|
+
if (unmergedPaths(wt).length > 0)
|
|
573
|
+
return { kind: 'refused', out: 'the index already holds unmerged entries, so the plan\'s work was not put back into it' };
|
|
574
|
+
const applied = carryGit(wt, 'stash', 'apply', '--index', carry);
|
|
575
|
+
if (applied.code === 0)
|
|
576
|
+
return dropCarry(wt, planId, carry);
|
|
577
|
+
const out = `${applied.stdout}${applied.stderr}`;
|
|
578
|
+
const clashed = settleApply(wt, planId, carry, out);
|
|
579
|
+
if (clashed !== undefined)
|
|
580
|
+
return clashed;
|
|
581
|
+
if (/conflicts in index/.test(out)) {
|
|
582
|
+
const plain = carryGit(wt, 'stash', 'apply', carry);
|
|
583
|
+
if (plain.code === 0) {
|
|
584
|
+
const index = carryGit(wt, 'diff-tree', '-r', '--name-only', '-z', '--no-renames', `${carry}^1`, `${carry}^2`);
|
|
585
|
+
const files = index.code === 0 ? index.stdout.split('\0').filter((f) => f !== '') : [];
|
|
586
|
+
const k = keep(wt, planId, carry, files, 'the plan\'s work went back without its staged versions');
|
|
587
|
+
return k.kind === 'kept' ? { kind: 'clean', kept: k.ref } : k;
|
|
588
|
+
}
|
|
589
|
+
const plainOut = `${plain.stdout}${plain.stderr}`;
|
|
590
|
+
return settleApply(wt, planId, carry, plainOut) ?? unapplied(wt, plainOut);
|
|
591
|
+
}
|
|
592
|
+
return unapplied(wt, out);
|
|
593
|
+
}
|
|
594
|
+
// An apply that clashed, as step 7 reads one; anything else is no clash (`undefined`).
|
|
595
|
+
function settleApply(wt, planId, carry, out) {
|
|
596
|
+
if (!CONFLICT.test(out))
|
|
597
|
+
return undefined;
|
|
598
|
+
const files = unmergedPaths(wt);
|
|
599
|
+
if (files.length === 0)
|
|
600
|
+
return undefined;
|
|
601
|
+
const k = keep(wt, planId, carry, files.map((f) => f.path), `the plan's work clashed going back, in ${files.map((f) => shellWord(f.path)).join(', ')}`);
|
|
602
|
+
return k.kind === 'kept' ? { kind: 'clash', kept: k.ref, files } : k;
|
|
603
|
+
}
|
|
604
|
+
function keep(wt, planId, carry, files, what) {
|
|
605
|
+
const kept = keepCarry(wt, planId, carry, files);
|
|
606
|
+
if (kept.ok)
|
|
607
|
+
return { kind: 'kept', ref: kept.value };
|
|
608
|
+
const lock = heldLock(wt, '', [`${carryRef(planId)}.lock`]);
|
|
609
|
+
if (lock !== undefined)
|
|
610
|
+
return { kind: 'locked', lock };
|
|
611
|
+
return { kind: 'refused', out: `${what}, and keeping the carry failed: ${kept.violations[0]?.got ?? ''}` };
|
|
612
|
+
}
|
|
613
|
+
function unapplied(wt, out) {
|
|
614
|
+
const lock = heldLock(wt, out);
|
|
615
|
+
if (lock !== undefined)
|
|
616
|
+
return { kind: 'locked', lock };
|
|
617
|
+
return { kind: 'refused', out: `git stash apply refused the plan's work: ${gitWords(out)}` };
|
|
618
|
+
}
|
|
619
|
+
// After a clean apply the carry ref goes, checked against the carry itself (S1-6). Step 0.5 drops it
|
|
620
|
+
// the same way once the work is found already back.
|
|
621
|
+
export function dropCarry(wt, planId, carry) {
|
|
622
|
+
const ref = carryRef(planId);
|
|
623
|
+
const dropped = carryGit(wt, 'update-ref', '-d', ref, carry);
|
|
624
|
+
if (dropped.code === 0)
|
|
625
|
+
return { kind: 'clean' };
|
|
626
|
+
const out = `${dropped.stdout}${dropped.stderr}`;
|
|
627
|
+
const lock = heldLock(wt, out, [`${ref}.lock`]);
|
|
628
|
+
if (lock !== undefined)
|
|
629
|
+
return { kind: 'locked', lock };
|
|
630
|
+
return { kind: 'refused', out: `the plan's work is back in the tree, but deleting ${ref} failed: ${gitWords(out)}` };
|
|
631
|
+
}
|
|
632
|
+
// §4.1.5 (the first build's finding). In a witness worktree's sparse checkout, `git rebase` silently
|
|
633
|
+
// replaces an untracked file at a path the base holds with the base's bytes and exits 0, where a
|
|
634
|
+
// plain checkout refuses. So before anything moves, every non-ignored untracked file at a path the
|
|
635
|
+
// moved base holds — or in a directory/file clash with one — refuses `rebase-refused`, named.
|
|
636
|
+
export function baseInTheWay(wt, planId, base) {
|
|
637
|
+
const ship = cliAct('ship', planId).line;
|
|
638
|
+
const tree = carryGit(wt, 'ls-tree', '-r', '--full-tree', '--name-only', '-z', base);
|
|
639
|
+
if (tree.code !== 0) {
|
|
640
|
+
return refuse([v('rebase', 'rebase-refused', `git could not list ${base}'s files: ${gitWords(tree.stderr)}`, `a readable ${base} — nothing moved; then ${ship}`)]);
|
|
641
|
+
}
|
|
642
|
+
const found = untrackedInTheWay(wt, tree.stdout.split('\0').filter((p) => p !== ''));
|
|
643
|
+
if (found === undefined) {
|
|
644
|
+
return refuse([v('rebase', 'rebase-refused', 'git could not list the untracked files the rebase would meet', `a worktree git can list — nothing moved; then ${ship}`)]);
|
|
645
|
+
}
|
|
646
|
+
if (found.length === 0)
|
|
647
|
+
return ok(undefined);
|
|
648
|
+
return refuse(found.map((f) => v(shellWord(f), 'rebase-refused', `untracked here, where ${base} holds a file — the rebase would replace it with ${base}'s bytes`, `it moved aside, or staged as the plan's work with ${remedyLine(['git', 'add', '--', f])} — nothing moved; then ${ship}`)));
|
|
649
|
+
}
|
|
650
|
+
// S1-1, S1-2. The untracked files that sit where a move would write one of `paths`: at the path
|
|
651
|
+
// itself, under it (the path is a file and they need its directory), or above it (one of them is a
|
|
652
|
+
// file where the path needs a directory). In a witness worktree's sparse checkout `git rebase` and
|
|
653
|
+
// `git stash apply` silently replace such a file, where a plain checkout refuses, so the carry asks
|
|
654
|
+
// first: Task 3's rebase and every apply. Ignored files are git's own to replace, as everywhere. On
|
|
655
|
+
// a filesystem git was told is case-insensitive (`core.ignorecase`), `NOTES.md` is in the way of
|
|
656
|
+
// `notes.md`, so names are compared without case there. `undefined`: git could not list them, and
|
|
657
|
+
// the caller refuses rather than guess.
|
|
658
|
+
export function untrackedInTheWay(wt, paths) {
|
|
659
|
+
if (paths.length === 0)
|
|
660
|
+
return [];
|
|
661
|
+
const listed = carryGit(wt, 'ls-files', '-z', '--others', '--exclude-standard');
|
|
662
|
+
if (listed.code !== 0)
|
|
663
|
+
return undefined;
|
|
664
|
+
const ignoreCase = carryGit(wt, 'config', '--type=bool', '--get', 'core.ignorecase').stdout.trim() === 'true';
|
|
665
|
+
const fold = (p) => (ignoreCase ? p.normalize('NFC').toLowerCase() : p);
|
|
666
|
+
const wanted = paths.map(fold);
|
|
667
|
+
return listed.stdout.split('\0').filter((u) => u !== '').filter((u) => {
|
|
668
|
+
const f = fold(u);
|
|
669
|
+
return wanted.some((p) => f === p || f.startsWith(`${p}/`) || p.startsWith(`${f}/`));
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
// §4.1.5 (S1-4, S1-7). Every git command a clash, carry or guard row names, as one line. A file name
|
|
673
|
+
// git would read as pathspec magic (`:x.md`) or a glob (`[x].md`, `*`, `?`, a backslash) runs with
|
|
674
|
+
// `--literal-pathspecs`, so the line names that file and no other: `git add -- :x.md` stages x.md.
|
|
675
|
+
// A line holding a name a terminal cannot show, or one Windows' shells read as more than text, is
|
|
676
|
+
// shown with why and never offered (`withheldOn`): pasted, its spelled-out name names another file.
|
|
677
|
+
const PATHSPEC_SPECIAL = /^:|[*?[\\]/;
|
|
678
|
+
export function remedyLine(argv, platform = process.platform) {
|
|
679
|
+
const dash = argv.indexOf('--');
|
|
680
|
+
const names = dash < 0 ? [] : argv.slice(dash + 1);
|
|
681
|
+
const words = argv[0] === 'git' && names.some((n) => PATHSPEC_SPECIAL.test(n))
|
|
682
|
+
? ['git', '--literal-pathspecs', ...argv.slice(1)]
|
|
683
|
+
: [...argv];
|
|
684
|
+
const withheld = withheldOn(words, platform);
|
|
685
|
+
const line = shellLine(words, platform);
|
|
686
|
+
return withheld === undefined ? line : `${line} (${withheld})`;
|
|
687
|
+
}
|