@phyzess/kitto 0.2.1 → 0.3.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/CHANGELOG.md +31 -0
- package/README.md +36 -4
- package/bin/kitto.mjs +176 -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 +475 -59
- 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 +35 -13
- package/lib/scopes.mjs +45 -10
- package/lib/setup-wizard.mjs +38 -13
- package/lib/versions.mjs +8 -2
- package/lib/worktree-audit.mjs +189 -0
- package/lib/worktree-lifecycle.mjs +451 -0
- package/package.json +3 -3
- package/sync.sh +94 -25
package/lib/versions.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { readFile, readdir } from 'node:fs/promises';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { dependencyPlan, executable, npmSpec, npxPackage, optionalJson, piServers, query } from './dependencies.mjs';
|
|
5
|
+
import { isDesktopProfile } from './dsh-profile.mjs';
|
|
5
6
|
import { hostSkillRoots } from './host-config.mjs';
|
|
6
7
|
|
|
7
8
|
const version = output => output?.match(/\d+\.\d+\.\d+(?:-[\w.-]+)?/)?.[0] || null;
|
|
@@ -108,11 +109,16 @@ export async function versionReport(state, hosts, pnpmVersion, online, hashTree)
|
|
|
108
109
|
for (const name of state.agents) {
|
|
109
110
|
rows.push({ kind: 'npm', owner: name, name: hosts[name].package, installed: version(query(name, ['--version'])), tested: hosts[name].version });
|
|
110
111
|
}
|
|
111
|
-
if (state.agents.includes('dsh')) rows.push({ kind: 'npm', owner: 'dsh', name: 'pnpm', installed: version(query('pnpm', ['--version'])), tested: pnpmVersion });
|
|
112
|
+
if (state.agents.includes('dsh') && !isDesktopProfile(state.dshProfile)) rows.push({ kind: 'npm', owner: 'dsh', name: 'pnpm', installed: version(query('pnpm', ['--version'])), tested: pnpmVersion });
|
|
112
113
|
const revision = query('git', ['-C', state.source, 'rev-parse', 'HEAD']);
|
|
113
114
|
if (state.agents.includes('pi')) rows.push(...await piVersions(state, revision));
|
|
114
115
|
if (state.agents.includes('codex')) rows.push(...await codexVersions(state));
|
|
115
|
-
if (state.agents.includes('dsh'))
|
|
116
|
+
if (state.agents.includes('dsh')) {
|
|
117
|
+
if (isDesktopProfile(state.dshProfile)) {
|
|
118
|
+
rows.push({ kind: 'inventory', owner: 'dsh', profile: state.dshProfile,
|
|
119
|
+
note: 'DSH desktop profile is app-managed; Kitto does not manage its bundles, patch or pnpm.' });
|
|
120
|
+
} else rows.push(...await dshVersions(state));
|
|
121
|
+
}
|
|
116
122
|
for (const { name, source } of [{ name: 'shared', source: join(state.source, 'skills') }, ...hostSkillRoots(state)]) {
|
|
117
123
|
rows.push(...(await resources(source, revision, hashTree)).map(row => ({ ...row, owner: name })));
|
|
118
124
|
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const usage = 'kitto worktree audit [--workspace PATH] [--json]';
|
|
6
|
+
const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
7
|
+
// Do not inherit repository selection, trace destinations or injected Git config.
|
|
8
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
|
|
9
|
+
Object.assign(env, { LC_ALL: 'C', GIT_ALLOW_PROTOCOL: '', GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0',
|
|
10
|
+
GIT_TRACE2: '0', GIT_TRACE2_PERF: '0', GIT_TRACE2_EVENT: '0' });
|
|
11
|
+
if (process.env.GIT_CONFIG_NOSYSTEM === '1') env.GIT_CONFIG_NOSYSTEM = '1';
|
|
12
|
+
|
|
13
|
+
export function git(cwd, ...args) {
|
|
14
|
+
return spawnSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false',
|
|
15
|
+
'-c', 'core.hooksPath=/dev/null', '-c', 'gc.auto=0', '-C', cwd, ...args],
|
|
16
|
+
{ env, timeout: 30000, maxBuffer: 16 * 1024 * 1024 });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function cleanExit(result, status = 0) {
|
|
20
|
+
// A probe can emit partial results and warn on stderr even with the expected exit code.
|
|
21
|
+
return !result.error && result.status === status && result.stderr?.length === 0;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function output(path, ...args) {
|
|
25
|
+
const result = git(path, ...args);
|
|
26
|
+
if (result.error) throw result.error;
|
|
27
|
+
if (!cleanExit(result)) throw new Error(`Cannot read Git ${args[0]} at ${JSON.stringify(path)}.`);
|
|
28
|
+
return text.decode(result.stdout).replace(/\n$/, ''); // Preserve whitespace in paths.
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function commonDir(path) {
|
|
32
|
+
return realpath(output(path, 'rev-parse', '--path-format=absolute', '--git-common-dir'));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function registrations(repo) {
|
|
36
|
+
return output(repo, 'worktree', 'list', '--porcelain', '-z').split('\0\0').filter(Boolean).map(record =>
|
|
37
|
+
Object.fromEntries(record.split('\0').map(line => {
|
|
38
|
+
const i = line.indexOf(' ');
|
|
39
|
+
return i < 0 ? [line, true] : [line.slice(0, i), line.slice(i + 1)];
|
|
40
|
+
})));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function diskBytes(path) {
|
|
44
|
+
// Both BSD and GNU du support -k, -s and -x. Ignore partial totals on error.
|
|
45
|
+
const result = spawnSync('du', ['-skx', path], { env, timeout: 60000 });
|
|
46
|
+
if (!cleanExit(result)) return null;
|
|
47
|
+
const match = /^(\d+)\t/.exec(result.stdout.toString());
|
|
48
|
+
const bytes = match ? Number(match[1]) * 1024 : NaN;
|
|
49
|
+
return Number.isSafeInteger(bytes) ? bytes : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function changes(path) {
|
|
53
|
+
// A configured clean/process filter can run arbitrary programs during status.
|
|
54
|
+
// Don't invoke it, even indirectly through nested submodule status.
|
|
55
|
+
if (!cleanExit(git(path, 'config', '--get-regexp', '^filter\\..*\\.(clean|process)$'), 1)) return null;
|
|
56
|
+
const result = git(path, 'status', '--porcelain=v1', '-z', '--no-renames', '--ignored=matching',
|
|
57
|
+
'--untracked-files=normal', '--ignore-submodules=all');
|
|
58
|
+
if (!cleanExit(result)) return null;
|
|
59
|
+
const lines = result.stdout.toString('latin1').split('\0').filter(Boolean);
|
|
60
|
+
return { tracked: lines.some(line => !['!!', '??'].includes(line.slice(0, 2))),
|
|
61
|
+
untracked: lines.some(line => line.startsWith('??')), ignored: lines.some(line => line.startsWith('!!')) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function checkoutGitDir(path, common, primary, bare) {
|
|
65
|
+
const gitDir = await realpath(output(path, 'rev-parse', '--absolute-git-dir'));
|
|
66
|
+
if (await commonDir(path) !== common || (!bare && output(path, 'rev-parse', '--show-toplevel') !== path)) {
|
|
67
|
+
throw new Error('Worktree checkout mismatch');
|
|
68
|
+
}
|
|
69
|
+
if (primary) {
|
|
70
|
+
if (gitDir !== common) throw new Error('Primary Git directory mismatch');
|
|
71
|
+
} else {
|
|
72
|
+
const marker = join(path, '.git');
|
|
73
|
+
if (dirname(gitDir) !== join(common, 'worktrees') ||
|
|
74
|
+
await realpath(output(path, 'rev-parse', '--resolve-git-dir', marker)) !== gitDir) {
|
|
75
|
+
throw new Error('Linked Git directory mismatch');
|
|
76
|
+
}
|
|
77
|
+
// A gitfile can select a different linked checkout in the same repository.
|
|
78
|
+
// Require its administrative directory to point back to this checkout's gitfile.
|
|
79
|
+
const reverse = join(gitDir, 'gitdir');
|
|
80
|
+
if (!(await lstat(reverse)).isFile()) throw new Error('Invalid worktree backlink');
|
|
81
|
+
const backlink = text.decode(await readFile(reverse)).replace(/\n$/, '');
|
|
82
|
+
if (!backlink || resolve(gitDir, backlink) !== marker) throw new Error('Worktree backlink mismatch');
|
|
83
|
+
}
|
|
84
|
+
return gitDir;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function inspect(repo, common, entry, primary, base, unique) {
|
|
88
|
+
const path = entry.worktree;
|
|
89
|
+
const row = { path, commonDir: common, gitDir: null, primary, bare: !!entry.bare,
|
|
90
|
+
branch: entry.branch ?? null, head: entry.HEAD ?? null, detached: !!entry.detached,
|
|
91
|
+
locked: !!entry.locked, prunable: !!entry.prunable, estimatedBytes: null,
|
|
92
|
+
changes: null, upstream: null, localBaseHead: base, mergedIntoLocalBase: null,
|
|
93
|
+
ownership: 'unmanaged', occupancy: 'unknown', blockers: ['unmanaged', 'occupancy-unknown'] };
|
|
94
|
+
for (const fact of ['primary', 'bare', 'detached', 'locked', 'prunable']) if (row[fact]) row.blockers.push(fact);
|
|
95
|
+
try {
|
|
96
|
+
if (!unique || await realpath(path) !== path) throw new Error('Worktree registration mismatch');
|
|
97
|
+
row.gitDir = await checkoutGitDir(path, common, primary, row.bare);
|
|
98
|
+
} catch {
|
|
99
|
+
row.blockers.push('identity-unknown');
|
|
100
|
+
return row;
|
|
101
|
+
}
|
|
102
|
+
row.estimatedBytes = diskBytes(path);
|
|
103
|
+
if (row.estimatedBytes === null) row.blockers.push('size-unknown');
|
|
104
|
+
if (row.bare) return row;
|
|
105
|
+
if (row.branch) {
|
|
106
|
+
try { row.upstream = output(repo, 'for-each-ref', '--format=%(upstream)', row.branch) || null; }
|
|
107
|
+
catch { row.blockers.push('upstream-unknown'); }
|
|
108
|
+
}
|
|
109
|
+
if (base && row.head) {
|
|
110
|
+
const result = git(repo, 'merge-base', '--is-ancestor', row.head, base);
|
|
111
|
+
if (cleanExit(result)) row.mergedIntoLocalBase = true;
|
|
112
|
+
else if (cleanExit(result, 1)) row.mergedIntoLocalBase = false;
|
|
113
|
+
}
|
|
114
|
+
if (row.mergedIntoLocalBase !== true) row.blockers.push(row.mergedIntoLocalBase === false ? 'not-in-local-base' : 'ancestry-unknown');
|
|
115
|
+
// Even --no-optional-locks does not stop Git freshening sharedindex.* mtimes.
|
|
116
|
+
// Without reading the index, conservatively skip probes if shared indexes exist.
|
|
117
|
+
const metadata = await readdir(row.gitDir).catch(() => null);
|
|
118
|
+
if (!metadata || metadata.some(name => name.startsWith('sharedindex.'))) {
|
|
119
|
+
row.blockers.push('index-probe-skipped', 'changes-unknown');
|
|
120
|
+
return row;
|
|
121
|
+
}
|
|
122
|
+
row.changes = changes(path);
|
|
123
|
+
if (!row.changes) row.blockers.push('changes-unknown');
|
|
124
|
+
else for (const [key, present] of Object.entries(row.changes)) if (present) row.blockers.push(key);
|
|
125
|
+
const files = git(path, 'ls-files', '-v', '--stage', '-z');
|
|
126
|
+
if (!cleanExit(files)) row.blockers.push('index-flags-unknown');
|
|
127
|
+
else {
|
|
128
|
+
const records = files.stdout.toString('latin1').split('\0');
|
|
129
|
+
if (records.some(record => /^[a-zS] /.test(record))) row.blockers.push('masked-index-entries');
|
|
130
|
+
if (records.some(record => /^. 160000 /.test(record))) row.blockers.push('submodules-unknown');
|
|
131
|
+
}
|
|
132
|
+
for (const marker of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'BISECT_START', 'rebase-merge', 'rebase-apply', 'sequencer']) {
|
|
133
|
+
try { await lstat(join(row.gitDir, marker)); row.blockers.push(`git-operation:${marker}`); }
|
|
134
|
+
catch (error) { if (error.code !== 'ENOENT') row.blockers.push('git-operation-unknown'); }
|
|
135
|
+
}
|
|
136
|
+
return row;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function candidates(workspace) {
|
|
140
|
+
if (!workspace) return [process.cwd()];
|
|
141
|
+
const root = await realpath(workspace);
|
|
142
|
+
const dirs = await readdir(root, { withFileTypes: true });
|
|
143
|
+
if (dirs.some(entry => entry.name === '.git')) return [root];
|
|
144
|
+
const repos = [];
|
|
145
|
+
for (const entry of dirs) {
|
|
146
|
+
if (!entry.isDirectory()) continue;
|
|
147
|
+
const dir = join(root, entry.name);
|
|
148
|
+
try { await lstat(join(dir, '.git')); repos.push(dir); }
|
|
149
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
150
|
+
}
|
|
151
|
+
return repos;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Inventory local Git registrations without creating state or inferring ownership. */
|
|
155
|
+
export async function auditWorktrees(workspace) {
|
|
156
|
+
const rows = [], seen = new Set();
|
|
157
|
+
for (const repo of await candidates(workspace)) {
|
|
158
|
+
const common = await commonDir(repo);
|
|
159
|
+
if (seen.has(common)) continue;
|
|
160
|
+
seen.add(common);
|
|
161
|
+
const entries = registrations(repo);
|
|
162
|
+
const base = entries[0]?.HEAD ?? null;
|
|
163
|
+
const counts = new Map();
|
|
164
|
+
for (const { worktree } of entries) counts.set(worktree, (counts.get(worktree) ?? 0) + 1);
|
|
165
|
+
for (const [index, entry] of entries.entries()) {
|
|
166
|
+
rows.push(await inspect(repo, common, entry, index === 0, base, counts.get(entry.worktree) === 1));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return rows.sort((a, b) => (b.estimatedBytes ?? -1) - (a.estimatedBytes ?? -1) || a.path.localeCompare(b.path));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function worktreeCommand([command, ...args]) {
|
|
173
|
+
if (!command || ['--help', '-h'].includes(command) || (command === 'audit' && args.length === 1 && ['--help', '-h'].includes(args[0]))) {
|
|
174
|
+
console.log(usage); return;
|
|
175
|
+
}
|
|
176
|
+
if (command !== 'audit') throw new Error(`Usage: ${usage}`);
|
|
177
|
+
let workspace, json = false;
|
|
178
|
+
for (let i = 0; i < args.length; i++) {
|
|
179
|
+
if (args[i] === '--json' && !json) json = true;
|
|
180
|
+
else if (args[i] === '--workspace' && !workspace && args[i + 1] && !args[i + 1].startsWith('-')) workspace = resolve(args[++i]);
|
|
181
|
+
else throw new Error(`Usage: ${usage}`);
|
|
182
|
+
}
|
|
183
|
+
const rows = await auditWorktrees(workspace);
|
|
184
|
+
if (json) console.log(JSON.stringify(rows, null, 2));
|
|
185
|
+
else {
|
|
186
|
+
console.log('Estimated bytes | Worktree | Branch / HEAD | Blockers (not a removal decision)');
|
|
187
|
+
for (const row of rows) console.log(`${row.estimatedBytes ?? 'unknown'} | ${JSON.stringify(row.path)} | ${JSON.stringify(row.branch ?? row.head)} | ${row.blockers.join(', ')}`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
@@ -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
|
+
}
|