@phyzess/kitto 0.2.0 → 0.3.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/CHANGELOG.md +32 -0
- package/README.md +36 -4
- package/bin/kitto.mjs +173 -2
- package/integration/dsh-archive-review.mjs +55 -0
- package/integration/dsh.mjs +3 -1
- package/integration/plugin.json +1 -1
- package/integration/scoped-dsh/native.mjs +33 -1
- package/integration/skills/kitto/SKILL.md +5 -4
- package/lib/codegraph.mjs +135 -0
- package/lib/codex-mcp.mjs +738 -0
- package/lib/dsh-profile.mjs +111 -0
- package/lib/environment-setup.mjs +19 -3
- package/lib/host-config.mjs +29 -4
- package/lib/hosts.mjs +288 -0
- package/lib/kitto.mjs +420 -55
- package/lib/mcp-credentials.mjs +289 -0
- package/lib/mcp-sync.mjs +500 -0
- package/lib/parity.mjs +64 -0
- package/lib/pi_config.py +218 -9
- package/lib/scope-dsh.mjs +10 -31
- package/lib/scope-setup.mjs +34 -12
- package/lib/scopes.mjs +45 -10
- package/lib/setup-prompts.mjs +68 -0
- package/lib/setup-wizard.mjs +61 -87
- package/lib/versions.mjs +8 -2
- package/lib/worktree-audit.mjs +189 -0
- package/lib/worktree-lifecycle.mjs +451 -0
- package/package.json +4 -3
- package/sync.sh +94 -25
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, readFile, readdir, readlink, realpath, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir, hostname } from 'node:os';
|
|
5
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { readScopeRegistry } from './scopes.mjs';
|
|
7
|
+
import { checkoutGitDir, cleanExit, commonDir, git, inspect, output, registrations } from './worktree-audit.mjs';
|
|
8
|
+
|
|
9
|
+
export const lifecycleUsage = `kitto worktree start --repo PATH --task ID --session ID [--confirm TOKEN]
|
|
10
|
+
kitto worktree finish --repo PATH --task ID --session ID --quiescent (--release | --delivered SHA)
|
|
11
|
+
kitto worktree apply --repo PATH --task ID --session ID --quiescent (--release | --delivered SHA) --confirm TOKEN`;
|
|
12
|
+
const id = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
|
|
13
|
+
const sha = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
|
|
14
|
+
const hex = /^[0-9a-f]{64}$/;
|
|
15
|
+
const stringMatches = (value, pattern) => typeof value === 'string' && pattern.test(value);
|
|
16
|
+
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
17
|
+
const uid = process.getuid?.();
|
|
18
|
+
|
|
19
|
+
function requireFact(condition, message) {
|
|
20
|
+
if (!condition) throw new Error(message);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function within(root, path) {
|
|
24
|
+
const rel = relative(root, path);
|
|
25
|
+
return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function stat(path) {
|
|
29
|
+
try { return await lstat(path, { bigint: true }); }
|
|
30
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function nodeIdentity(path) {
|
|
34
|
+
const node = await stat(path);
|
|
35
|
+
requireFact(node?.isDirectory() && await realpath(path) === path, 'Directory identity is unknown.');
|
|
36
|
+
return `${node.dev}:${node.ino}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function privatePath(path, directory, create = false) {
|
|
40
|
+
if (create) await mkdir(path, { recursive: true, mode: 0o700 });
|
|
41
|
+
const node = await stat(path);
|
|
42
|
+
if (!node) return false;
|
|
43
|
+
requireFact((directory ? node.isDirectory() : node.isFile()) && node.uid === BigInt(uid) &&
|
|
44
|
+
(node.mode & 0o077n) === 0n && await realpath(path) === path, 'Worktree state must be private and must not use path aliases.');
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function underLock(root, run) {
|
|
49
|
+
await privatePath(root, true, true);
|
|
50
|
+
const lock = join(root, 'lock');
|
|
51
|
+
try { await mkdir(lock, { mode: 0o700 }); }
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code === 'EEXIST') throw new Error('Worktree state is locked; wait for its writer or inspect a stale lock manually.');
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
try { return await run(); }
|
|
57
|
+
finally { await rmdir(lock); }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function load(file, key) {
|
|
61
|
+
if (!await privatePath(file, false)) return null;
|
|
62
|
+
const row = JSON.parse(await readFile(file, 'utf8'));
|
|
63
|
+
requireFact(row?.version === 1 && row.key === key && typeof row.revision === 'string' &&
|
|
64
|
+
['creating', 'ready', 'removing', 'removed'].includes(row.phase) && Array.isArray(row.sessions) &&
|
|
65
|
+
row.sessions.every(session => stringMatches(session, id)) && new Set(row.sessions).size === row.sessions.length &&
|
|
66
|
+
(row.phase === 'creating' || (typeof row.identity === 'string' && hex.test(row.identity))), 'Invalid worktree ledger; refusing to proceed.');
|
|
67
|
+
return row;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function save(file, row) {
|
|
71
|
+
const temporary = join(dirname(file), `${randomUUID()}.tmp`);
|
|
72
|
+
await writeFile(temporary, JSON.stringify(row) + '\n', { flag: 'wx', mode: 0o600 });
|
|
73
|
+
try { await rename(temporary, file); }
|
|
74
|
+
finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function options(command, args) {
|
|
78
|
+
const result = {};
|
|
79
|
+
for (let i = 0; i < args.length; i++) {
|
|
80
|
+
const flag = args[i];
|
|
81
|
+
const key = flag.slice(2);
|
|
82
|
+
requireFact(/^--(?:repo|task|session|confirm|quiescent|release|delivered)$/.test(flag) && !(key in result), lifecycleUsage);
|
|
83
|
+
result[key] = ['quiescent', 'release'].includes(key) ? true : args[++i];
|
|
84
|
+
requireFact(result[key] && (result[key] === true || !result[key].startsWith('--')), lifecycleUsage);
|
|
85
|
+
}
|
|
86
|
+
requireFact(result.repo && stringMatches(result.task, id) && stringMatches(result.session, id) &&
|
|
87
|
+
(!result.confirm || stringMatches(result.confirm, hex)), lifecycleUsage);
|
|
88
|
+
if (command === 'start') requireFact(!result.quiescent && !result.release && !result.delivered, lifecycleUsage);
|
|
89
|
+
else requireFact(result.quiescent && (result.release ? !result.delivered : stringMatches(result.delivered, sha)) &&
|
|
90
|
+
(command === 'apply' ? result.confirm : !result.confirm), lifecycleUsage);
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function repository(args, root) {
|
|
95
|
+
const repo = await realpath(resolve(args.repo));
|
|
96
|
+
const registry = await readScopeRegistry();
|
|
97
|
+
const scope = registry.workspaces.includes(repo) ? ['workspace', repo] :
|
|
98
|
+
(registry.workspaceParents ?? []).includes(dirname(repo)) ? ['workspace-parent', dirname(repo)] : null;
|
|
99
|
+
requireFact(scope, 'The primary checkout needs an explicit workspace or direct workspace-parent scope.');
|
|
100
|
+
const common = await commonDir(repo);
|
|
101
|
+
const entries = registrations(repo);
|
|
102
|
+
const primary = entries[0];
|
|
103
|
+
requireFact(primary?.worktree === repo && !primary.bare && !primary.detached && !primary.prunable &&
|
|
104
|
+
!primary.locked && typeof primary.branch === 'string' && stringMatches(primary.HEAD, sha) &&
|
|
105
|
+
entries.filter(entry => entry.worktree === repo).length === 1, 'Choose the canonical primary checkout with an attached local branch.');
|
|
106
|
+
await checkoutGitDir(repo, common, true, false);
|
|
107
|
+
requireFact(!within(repo, root) && !within(common, root), 'Worktree state must be outside the source checkout and Git directory.');
|
|
108
|
+
const repoId = digest([hostname(), repo, await nodeIdentity(repo), common, await nodeIdentity(common)]);
|
|
109
|
+
const key = digest([repoId, args.task]);
|
|
110
|
+
const bucket = join(root, repoId);
|
|
111
|
+
const path = join(bucket, key);
|
|
112
|
+
const branch = `kitto/task-${key}`;
|
|
113
|
+
return { repo, common, entries, primary, scope, key, bucket, path, branch, file: join(bucket, `${key}.json`) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function ownRegistration(ctx) {
|
|
117
|
+
return ctx.entries.filter(entry => entry.worktree === ctx.path || entry.branch === `refs/heads/${ctx.branch}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function emptyDestination(ctx) {
|
|
121
|
+
const refs = output(ctx.repo, 'for-each-ref', '--format=%(refname)', `refs/heads/${ctx.branch}`);
|
|
122
|
+
return !ownRegistration(ctx).length && !await stat(ctx.path) && !refs;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const ownershipMarker = 'kitto-owner';
|
|
126
|
+
|
|
127
|
+
async function binding(ctx, create = false) {
|
|
128
|
+
const entries = ownRegistration(ctx);
|
|
129
|
+
const [entry] = entries;
|
|
130
|
+
requireFact(entries.length === 1 && entry.worktree === ctx.path && entry.branch === `refs/heads/${ctx.branch}` &&
|
|
131
|
+
!entry.bare && !entry.detached && !entry.prunable && stringMatches(entry.HEAD, sha), 'Managed checkout registration is missing or has changed.');
|
|
132
|
+
const gitDir = await checkoutGitDir(ctx.path, ctx.common, false, false);
|
|
133
|
+
const nodes = [ctx.path, await nodeIdentity(ctx.path), gitDir, await nodeIdentity(gitDir)];
|
|
134
|
+
const marker = join(gitDir, ownershipMarker);
|
|
135
|
+
if (create) await writeFile(marker, digest(randomUUID()), { flag: 'wx', mode: 0o600 });
|
|
136
|
+
requireFact(await privatePath(marker, false), 'Managed checkout ownership marker is missing.');
|
|
137
|
+
const owner = await readFile(marker, 'utf8');
|
|
138
|
+
requireFact(hex.test(owner), 'Invalid checkout ownership marker.');
|
|
139
|
+
return { identity: digest([...nodes, owner]), entry, gitDir };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function currentRow(ctx, old, phase, fields = {}) {
|
|
143
|
+
return { version: 1, key: ctx.key, revision: randomUUID(), identity: old?.identity ?? null,
|
|
144
|
+
phase, sessions: old?.sessions ?? [], ...fields };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function plan(ctx, args, row, action, facts, blockers = []) {
|
|
148
|
+
const info = { action, task: args.task, session: args.session, repo: ctx.repo, path: ctx.path,
|
|
149
|
+
branch: ctx.branch, baseBranch: ctx.primary.branch, baseHead: ctx.primary.HEAD, scope: ctx.scope, ...facts, blockers };
|
|
150
|
+
return { ...info, confirm: blockers.length ? null : digest([1, ctx.key, row?.revision ?? null, info]) };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function confirm(args, preview) {
|
|
154
|
+
requireFact(preview.confirm && args.confirm === preview.confirm, 'Confirmation is missing, blocked, or stale; request a fresh preview.');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function noCheckoutFilters(path) {
|
|
158
|
+
return cleanExit(git(path, 'config', '--get-regexp', '^filter\\..*\\.(clean|smudge|process)$'), 1);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Advisory only: no host event proves that a session claim can be released.
|
|
162
|
+
// Use only the current repository's private ledger; do not probe other checkouts
|
|
163
|
+
// or include their paths, task identifiers, or session identifiers in the hint.
|
|
164
|
+
async function handoffHints(ctx) {
|
|
165
|
+
const result = { otherClaimed: 0, otherUnclaimed: 0, otherInterrupted: 0, incomplete: false };
|
|
166
|
+
try {
|
|
167
|
+
if (!await privatePath(ctx.bucket, true)) return result;
|
|
168
|
+
for (const name of await readdir(ctx.bucket)) {
|
|
169
|
+
if (!/^[0-9a-f]{64}\.json$/.test(name)) continue;
|
|
170
|
+
const key = name.slice(0, -5);
|
|
171
|
+
if (key === ctx.key) continue;
|
|
172
|
+
try {
|
|
173
|
+
const row = await load(join(ctx.bucket, name), key);
|
|
174
|
+
if (!row) result.incomplete = true;
|
|
175
|
+
else if (row.phase === 'ready') result[row.sessions.length ? 'otherClaimed' : 'otherUnclaimed']++;
|
|
176
|
+
else if (row.phase !== 'removed') result.otherInterrupted++;
|
|
177
|
+
} catch {
|
|
178
|
+
result.incomplete = true;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
} catch {
|
|
182
|
+
result.incomplete = true;
|
|
183
|
+
}
|
|
184
|
+
return result;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function start(ctx, args, row) {
|
|
188
|
+
let preview;
|
|
189
|
+
if (row?.phase === 'ready') {
|
|
190
|
+
const { identity, entry } = await binding(ctx);
|
|
191
|
+
requireFact(row.identity === identity && !entry.locked, 'Managed checkout identity has changed or Git has locked it.');
|
|
192
|
+
preview = plan(ctx, args, row, 'reuse', { head: entry.HEAD, sessions: row.sessions });
|
|
193
|
+
} else {
|
|
194
|
+
requireFact(!row || row.phase === 'creating', 'This task is being removed or has already been retired; use a new task ID.');
|
|
195
|
+
requireFact(await emptyDestination(ctx), 'Destination or branch already exists; Kitto does not adopt existing worktrees.');
|
|
196
|
+
requireFact(noCheckoutFilters(ctx.repo), 'Configured or unknown Git filters prevent unattended checkout.');
|
|
197
|
+
preview = plan(ctx, args, row, 'create', { sessions: [] });
|
|
198
|
+
}
|
|
199
|
+
if (!args.confirm) return { ...preview, handoffHints: await handoffHints(ctx) };
|
|
200
|
+
confirm(args, preview);
|
|
201
|
+
const sessions = [...new Set([...preview.sessions, args.session])].sort();
|
|
202
|
+
if (preview.action === 'create') {
|
|
203
|
+
await privatePath(ctx.bucket, true, true);
|
|
204
|
+
await save(ctx.file, currentRow(ctx, row, 'creating'));
|
|
205
|
+
// A clean result is required, but worktree add writes progress to stderr even on success.
|
|
206
|
+
const result = git(ctx.repo, 'worktree', 'add', '--quiet', '--no-checkout', '-b', ctx.branch, '--', ctx.path, ctx.primary.HEAD);
|
|
207
|
+
requireFact(cleanExit(result), 'Git could not create the worktree safely. Creation intent retained; inspect artifacts manually.');
|
|
208
|
+
ctx.entries = registrations(ctx.repo);
|
|
209
|
+
const { identity, entry } = await binding(ctx, true);
|
|
210
|
+
requireFact(entry.HEAD === ctx.primary.HEAD && !entry.locked, 'Created checkout differs from the approved plan.');
|
|
211
|
+
// Conditional config may select filters only for the linked checkout.
|
|
212
|
+
requireFact(noCheckoutFilters(ctx.path), 'Configured or unknown filters in the new checkout; creation intent retained.');
|
|
213
|
+
requireFact(cleanExit(git(ctx.path, 'read-tree', entry.HEAD)) && cleanExit(git(ctx.path, 'checkout-index', '--all')),
|
|
214
|
+
'Git could not populate the new checkout safely. Creation intent retained; inspect artifacts manually.');
|
|
215
|
+
await save(ctx.file, currentRow(ctx, row, 'ready', { identity, sessions }));
|
|
216
|
+
} else {
|
|
217
|
+
await save(ctx.file, currentRow(ctx, row, 'ready', { sessions }));
|
|
218
|
+
}
|
|
219
|
+
return { ...preview, confirm: null, sessions, applied: true };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const conversionAttrs = new Set(['filter', 'working-tree-encoding', 'text', 'eol', 'crlf', 'ident']);
|
|
223
|
+
|
|
224
|
+
function verifyConversionPolicy(path, names) {
|
|
225
|
+
requireFact(noCheckoutFilters(path), 'Configured or unknown checkout filters.');
|
|
226
|
+
const autocrlf = git(path, 'config', '--type=bool', '--get', 'core.autocrlf');
|
|
227
|
+
requireFact(cleanExit(autocrlf, 1) || (cleanExit(autocrlf) && autocrlf.stdout.toString() === 'false\n'),
|
|
228
|
+
'Configured or unknown line-ending conversion.');
|
|
229
|
+
let batch = [], bytes = 0;
|
|
230
|
+
function checkBatch() {
|
|
231
|
+
const fields = output(path, 'check-attr', '--all', '-z', '--', ...batch).split('\0');
|
|
232
|
+
requireFact(fields.pop() === '' && fields.length % 3 === 0, 'Invalid Git attribute output.');
|
|
233
|
+
for (let i = 1; i < fields.length; i += 3) {
|
|
234
|
+
requireFact(!conversionAttrs.has(fields[i]), 'Checkout conversion attributes are not supported for removal.');
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
for (const name of names) {
|
|
238
|
+
const size = Buffer.byteLength(name) + 1;
|
|
239
|
+
if (batch.length && bytes + size > 32768) {
|
|
240
|
+
checkBatch();
|
|
241
|
+
batch = [];
|
|
242
|
+
bytes = 0;
|
|
243
|
+
}
|
|
244
|
+
batch.push(name);
|
|
245
|
+
bytes += size;
|
|
246
|
+
}
|
|
247
|
+
if (batch.length) checkBatch();
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const observation = node => [node.dev, node.ino, node.mode, node.size, node.mtimeNs, node.ctimeNs].map(String);
|
|
251
|
+
function sameObservation(left, right) {
|
|
252
|
+
if (!right) return false;
|
|
253
|
+
const values = observation(right);
|
|
254
|
+
return observation(left).every((value, i) => value === values[i]);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function rawBlobId(path, node, algorithm) {
|
|
258
|
+
const blob = createHash(algorithm);
|
|
259
|
+
if (node.isSymbolicLink()) {
|
|
260
|
+
const target = await readlink(path, { encoding: 'buffer' });
|
|
261
|
+
blob.update(`blob ${target.length}\0`).update(target);
|
|
262
|
+
} else {
|
|
263
|
+
requireFact(constants.O_NOFOLLOW && constants.O_NONBLOCK, 'Safe regular file access is unavailable.');
|
|
264
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
265
|
+
try {
|
|
266
|
+
requireFact(sameObservation(node, await file.stat({ bigint: true })), 'Checkout file changed before reading.');
|
|
267
|
+
blob.update(`blob ${node.size}\0`);
|
|
268
|
+
let size = 0n;
|
|
269
|
+
for await (const chunk of file.createReadStream({ autoClose: false })) {
|
|
270
|
+
size += BigInt(chunk.length);
|
|
271
|
+
requireFact(size <= node.size, 'Checkout file grew during reading.');
|
|
272
|
+
blob.update(chunk);
|
|
273
|
+
}
|
|
274
|
+
requireFact(size === node.size && sameObservation(node, await file.stat({ bigint: true })), 'Checkout file changed during reading.');
|
|
275
|
+
} finally { await file.close(); }
|
|
276
|
+
}
|
|
277
|
+
requireFact(sameObservation(node, await stat(path)), 'Checkout entry changed during reading.');
|
|
278
|
+
return blob.digest('hex');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Verify the disk against the index and the committed tree independently of Git's
|
|
282
|
+
// stat cache. Only raw byte equality is accepted; no clean/smudge conversion runs.
|
|
283
|
+
async function checkoutSnapshot(ctx, head) {
|
|
284
|
+
if (process.platform === 'linux') {
|
|
285
|
+
// Device numbers alone do not detect same-device bind mounts.
|
|
286
|
+
const mounts = await readFile('/proc/self/mountinfo', 'utf8');
|
|
287
|
+
for (const line of mounts.trimEnd().split('\n')) {
|
|
288
|
+
const encoded = line.split(' ')[4];
|
|
289
|
+
requireFact(encoded, 'Mount table is unreadable.');
|
|
290
|
+
const mount = encoded.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
|
|
291
|
+
requireFact(!within(ctx.path, mount), 'Mounted checkout entry.');
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const algorithm = output(ctx.path, 'rev-parse', '--show-object-format');
|
|
295
|
+
requireFact(['sha1', 'sha256'].includes(algorithm), 'Unknown Git object format.');
|
|
296
|
+
const indexed = new Map(), directories = new Set();
|
|
297
|
+
for (const record of output(ctx.path, 'ls-files', '--stage', '-z').split('\0').filter(Boolean)) {
|
|
298
|
+
const match = /^(100644|100755|120000) ([0-9a-f]+) 0\t([\s\S]+)$/.exec(record);
|
|
299
|
+
requireFact(match && match[2].length === (algorithm === 'sha1' ? 40 : 64), 'Unsupported index entry.');
|
|
300
|
+
const [, mode, oid, name] = match;
|
|
301
|
+
const parts = name.split('/');
|
|
302
|
+
requireFact(!indexed.has(name) && parts.every(part => part && !['.', '..', '.git'].includes(part)), 'Unknown tracked path.');
|
|
303
|
+
indexed.set(name, { mode, oid });
|
|
304
|
+
for (let i = 1; i < parts.length; i++) directories.add(parts.slice(0, i).join('/'));
|
|
305
|
+
}
|
|
306
|
+
const committed = new Set();
|
|
307
|
+
for (const record of output(ctx.path, 'ls-tree', '-r', '-z', '--full-tree', head).split('\0').filter(Boolean)) {
|
|
308
|
+
const match = /^(100644|100755|120000) blob ([0-9a-f]+)\t([\s\S]+)$/.exec(record);
|
|
309
|
+
requireFact(match, 'Unsupported committed tree entry.');
|
|
310
|
+
const [, mode, oid, name] = match;
|
|
311
|
+
const indexEntry = indexed.get(name);
|
|
312
|
+
requireFact(indexEntry?.mode === mode && indexEntry.oid === oid && !committed.has(name), 'Index differs from the committed tree.');
|
|
313
|
+
committed.add(name);
|
|
314
|
+
}
|
|
315
|
+
requireFact(committed.size === indexed.size, 'Some indexed paths are not committed.');
|
|
316
|
+
verifyConversionPolicy(ctx.path, indexed.keys());
|
|
317
|
+
const root = await stat(ctx.path);
|
|
318
|
+
const hash = createHash('sha256');
|
|
319
|
+
function record(name, node) {
|
|
320
|
+
hash.update(JSON.stringify([name, ...observation(node)]));
|
|
321
|
+
}
|
|
322
|
+
async function walk(path, parent) {
|
|
323
|
+
for (const name of (await readdir(path)).sort()) {
|
|
324
|
+
const child = join(path, name), rel = parent ? `${parent}/${name}` : name;
|
|
325
|
+
const node = await stat(child);
|
|
326
|
+
requireFact(node && node.dev === root.dev, 'Unknown checkout entry or filesystem boundary.');
|
|
327
|
+
record(rel, node);
|
|
328
|
+
if (rel === '.git') requireFact(node.isFile(), 'Unknown Git file.');
|
|
329
|
+
else if (node.isDirectory()) {
|
|
330
|
+
requireFact(directories.has(rel), 'Untracked directory.');
|
|
331
|
+
directories.delete(rel);
|
|
332
|
+
await walk(child, rel);
|
|
333
|
+
} else {
|
|
334
|
+
const entry = indexed.get(rel);
|
|
335
|
+
const executable = (node.mode & 0o100n) !== 0n;
|
|
336
|
+
requireFact(entry && (entry.mode === '120000' ? node.isSymbolicLink() : node.isFile() && executable === (entry.mode === '100755')),
|
|
337
|
+
'Untracked, changed, or unsupported filesystem entry.');
|
|
338
|
+
const oid = await rawBlobId(child, node, algorithm);
|
|
339
|
+
requireFact(oid === entry.oid, 'Checkout content differs from its committed blob.');
|
|
340
|
+
hash.update(oid);
|
|
341
|
+
indexed.delete(rel);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
requireFact(root?.isDirectory(), 'Unknown checkout root.');
|
|
346
|
+
record('', root);
|
|
347
|
+
await walk(ctx.path, '');
|
|
348
|
+
requireFact(!indexed.size && !directories.size, 'Some indexed paths are unavailable.');
|
|
349
|
+
return hash.digest('hex');
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async function finish(ctx, args, row) {
|
|
353
|
+
requireFact(row && ['ready', 'removing'].includes(row.phase), 'No owned, active worktree for this task.');
|
|
354
|
+
requireFact(row.sessions.includes(args.session), 'This session has no claim on the task.');
|
|
355
|
+
let preview;
|
|
356
|
+
if (args.release) {
|
|
357
|
+
requireFact(row.phase === 'ready', 'Interrupted removal must be reviewed before releasing the session.');
|
|
358
|
+
preview = plan(ctx, args, row, 'release', { sessions: row.sessions });
|
|
359
|
+
} else {
|
|
360
|
+
const blockers = [];
|
|
361
|
+
if (row.sessions.length !== 1) blockers.push('other-sessions-active');
|
|
362
|
+
if (args.delivered !== ctx.primary.HEAD) blockers.push('delivery-head-mismatch');
|
|
363
|
+
if (within(ctx.path, await realpath(process.cwd()))) blockers.push('caller-in-target');
|
|
364
|
+
const entries = ownRegistration(ctx);
|
|
365
|
+
if (row.phase === 'removing' && !entries.length && !await stat(ctx.path)) {
|
|
366
|
+
const head = output(ctx.repo, 'rev-parse', '--verify', `refs/heads/${ctx.branch}`);
|
|
367
|
+
requireFact(head === row.removalHead, 'Interrupted removal no longer matches the retained branch.');
|
|
368
|
+
preview = plan(ctx, args, row, 'record-removed', { delivered: args.delivered, head, sessions: row.sessions }, blockers);
|
|
369
|
+
} else {
|
|
370
|
+
const { identity, entry, gitDir } = await binding(ctx);
|
|
371
|
+
requireFact(identity === row.identity, 'Managed checkout identity has changed.');
|
|
372
|
+
const audit = await inspect(ctx.repo, ctx.common, entry, false, ctx.primary.HEAD, true);
|
|
373
|
+
for (const blocker of audit.blockers) {
|
|
374
|
+
if (!['unmanaged', 'occupancy-unknown'].includes(blocker)) blockers.push(blocker);
|
|
375
|
+
}
|
|
376
|
+
if (!audit.changes && !blockers.includes('changes-unknown')) blockers.push('changes-unknown');
|
|
377
|
+
for (const lock of ['index.lock', 'HEAD.lock', 'config.worktree.lock']) {
|
|
378
|
+
if (await stat(join(gitDir, lock))) blockers.push('git-write-in-progress');
|
|
379
|
+
}
|
|
380
|
+
if (await stat(join(ctx.common, 'info/grafts')) || output(ctx.repo, 'for-each-ref', '--format=%(refname)', 'refs/replace/')) {
|
|
381
|
+
blockers.push('modified-ancestry');
|
|
382
|
+
}
|
|
383
|
+
let snapshot = null;
|
|
384
|
+
if (!blockers.length) {
|
|
385
|
+
try { snapshot = await checkoutSnapshot(ctx, entry.HEAD); }
|
|
386
|
+
catch { blockers.push('filesystem-unverified'); }
|
|
387
|
+
}
|
|
388
|
+
preview = plan(ctx, args, row, 'remove', { delivered: args.delivered, head: entry.HEAD,
|
|
389
|
+
sessions: row.sessions, snapshot }, [...new Set(blockers)]);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (!args.confirm) return preview;
|
|
393
|
+
confirm(args, preview);
|
|
394
|
+
if (preview.action === 'release') {
|
|
395
|
+
await save(ctx.file, currentRow(ctx, row, 'ready', { sessions: row.sessions.filter(session => session !== args.session) }));
|
|
396
|
+
} else {
|
|
397
|
+
if (preview.action === 'remove') {
|
|
398
|
+
await save(ctx.file, currentRow(ctx, row, 'removing', { removalHead: preview.head }));
|
|
399
|
+
const result = git(ctx.repo, 'worktree', 'remove', '--', ctx.path);
|
|
400
|
+
requireFact(cleanExit(result), 'Git declined or could not verify removal. Inspect the interrupted operation before retrying.');
|
|
401
|
+
ctx.entries = registrations(ctx.repo);
|
|
402
|
+
requireFact(!ownRegistration(ctx).length && !await stat(ctx.path) &&
|
|
403
|
+
output(ctx.repo, 'rev-parse', '--verify', `refs/heads/${ctx.branch}`) === preview.head,
|
|
404
|
+
'Git removal could not be verified; removal intent retained.');
|
|
405
|
+
}
|
|
406
|
+
await save(ctx.file, currentRow(ctx, row, 'removed', { sessions: [] }));
|
|
407
|
+
}
|
|
408
|
+
return { ...preview, confirm: null, applied: true };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function stateRoot() {
|
|
412
|
+
requireFact(uid !== undefined, 'The worktree lifecycle requires a POSIX user.');
|
|
413
|
+
const state = process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state');
|
|
414
|
+
requireFact(isAbsolute(state), 'XDG_STATE_HOME must be an absolute device-local path.');
|
|
415
|
+
return resolve(state, 'kitto-worktrees');
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Match a persisted host session to an explicitly named, still-owned local claim. */
|
|
419
|
+
export async function matchesArchiveClaim({ repo, task, session }, header) {
|
|
420
|
+
if (typeof repo !== 'string' || !isAbsolute(repo) || !stringMatches(task, id) ||
|
|
421
|
+
!stringMatches(session, id) || header?.id !== session || typeof header.cwd !== 'string' ||
|
|
422
|
+
!isAbsolute(header.cwd)) return false;
|
|
423
|
+
try {
|
|
424
|
+
const root = stateRoot();
|
|
425
|
+
if (!await privatePath(root, true)) return false;
|
|
426
|
+
const ctx = await repository({ repo, task }, root);
|
|
427
|
+
if (header.cwd !== ctx.path || !await privatePath(ctx.bucket, true)) return false;
|
|
428
|
+
const row = await load(ctx.file, ctx.key);
|
|
429
|
+
if (row?.phase !== 'ready' || !row.sessions.includes(session)) return false;
|
|
430
|
+
const { identity } = await binding(ctx);
|
|
431
|
+
return row.identity === identity && (await load(ctx.file, ctx.key))?.revision === row.revision;
|
|
432
|
+
} catch { return false; }
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
export async function lifecycleCommand(command, argv) {
|
|
436
|
+
if (argv.length === 1 && ['--help', '-h'].includes(argv[0])) return console.log(lifecycleUsage);
|
|
437
|
+
const args = options(command, argv);
|
|
438
|
+
const root = stateRoot();
|
|
439
|
+
const modifying = command === 'apply' || !!args.confirm;
|
|
440
|
+
const run = async () => {
|
|
441
|
+
const ctx = await repository(args, root);
|
|
442
|
+
await privatePath(root, true);
|
|
443
|
+
await privatePath(ctx.bucket, true);
|
|
444
|
+
const row = await load(ctx.file, ctx.key);
|
|
445
|
+
return command === 'start' ? start(ctx, args, row) : finish(ctx, args, row);
|
|
446
|
+
};
|
|
447
|
+
// Validate scope before any state changes, and re-resolve it under the lock.
|
|
448
|
+
if (modifying) await repository(args, root);
|
|
449
|
+
const result = modifying ? await underLock(root, run) : await run();
|
|
450
|
+
console.log(JSON.stringify(result, null, 2));
|
|
451
|
+
}
|
package/package.json
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phyzess/kitto",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Portable personal configuration for Pi, Codex and DeepSeek Harness",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": { "kitto": "bin/kitto.mjs" },
|
|
7
|
-
"engines": { "node": ">=22.0.0", "dsh": ">=0.2.2-rc.
|
|
7
|
+
"engines": { "node": ">=22.0.0", "dsh": ">=0.2.2-rc.2 <0.3.0" },
|
|
8
8
|
"publishConfig": { "access": "public" },
|
|
9
9
|
"repository": { "type": "git", "url": "git+https://github.com/phyzess/kitto.git" },
|
|
10
10
|
"files": ["bin/*.mjs", "lib/*.mjs", "lib/*.py", "integration/", "sync.sh", "CHANGELOG.md"],
|
|
11
|
+
"dependencies": { "@clack/prompts": "1.9.0" },
|
|
11
12
|
"scripts": {
|
|
12
|
-
"test": "node --test tests/kitto.test.mjs tests/scope*.test.mjs tests/setup-wizard.test.mjs",
|
|
13
|
+
"test": "node --test tests/kitto.test.mjs tests/worktree-*.test.mjs tests/codegraph.test.mjs tests/parity.test.mjs tests/codex-mcp.test.mjs tests/mcp-sync.test.mjs tests/scope*.test.mjs tests/setup-wizard.test.mjs",
|
|
13
14
|
"prepublishOnly": "npm test && python3 -m unittest discover -s tests -v",
|
|
14
15
|
"release": "node scripts/release.mjs"
|
|
15
16
|
},
|