@anhlp/alp-daemon 0.0.1-beta.3 → 0.0.1-beta.5
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 +4 -0
- package/dist/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/alpd.js +29928 -14898
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +34 -1
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +154 -2
- package/dist/files.js +392 -68
- package/dist/git.d.ts +93 -0
- package/dist/git.js +1192 -0
- package/dist/gitignore.d.ts +5 -0
- package/dist/gitignore.js +7 -1
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +21 -1
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/main.js +43 -11
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +198 -0
- package/dist/operations.d.ts +8 -2
- package/dist/operations.js +20 -10
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +296 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +14 -2
- package/dist/server.js +836 -90
- package/dist/store.d.ts +72 -2
- package/dist/store.js +111 -4
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +193 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +29 -0
- package/dist/windows-terminal.js +122 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +70 -7
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +528 -82
- package/src/git.ts +1140 -0
- package/src/gitignore.ts +10 -0
- package/src/history.ts +118 -0
- package/src/index.ts +7 -0
- package/src/lifecycle.ts +283 -0
- package/src/main.ts +37 -12
- package/src/native-terminal.ts +122 -0
- package/src/operations.ts +27 -11
- package/src/registry.ts +238 -0
- package/src/scheduler.ts +432 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +948 -102
- package/src/store.ts +117 -4
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +641 -0
- package/src/windows-terminal.ts +123 -0
- package/src/worktrees.ts +382 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/** Identity-bound native PTY owner; shipped helper only, never runtime compilation. */
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
8
|
+
export type CleanupResult = { observed: number; live: number; uncertain: number; coverage?: 'root-only'; outputOpen?: boolean };
|
|
9
|
+
type Exit = { exitCode: number | null; signal?: number };
|
|
10
|
+
type Listener<T> = (event: T) => void;
|
|
11
|
+
const sha = (value: Buffer) => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
function binary() {
|
|
13
|
+
const libc = process.platform === 'linux' ? (process.report?.getReport() as { header?: { glibcVersionRuntime?: string } })?.header?.glibcVersionRuntime ? 'glibc' : 'musl' : undefined;
|
|
14
|
+
const slot = [process.platform, process.arch, libc].filter(Boolean).join('-');
|
|
15
|
+
// The ALP executable (t-1e02) extracts its helper; registerPackaged in @anhlp/alp-core/packaged publishes assetDir here.
|
|
16
|
+
// Read through globalThis so this shipped adapter stays free of package imports.
|
|
17
|
+
const assets = (globalThis as { [key: symbol]: { assetDir?: () => string | undefined } | undefined })[Symbol.for('alp.packaged')]?.assetDir?.();
|
|
18
|
+
const adjacent = assets ? path.join(assets, 'terminal-native') : path.join(path.dirname(fileURLToPath(import.meta.url)), 'terminal-native');
|
|
19
|
+
const dir = assets || existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../native');
|
|
20
|
+
const file = path.join(dir, 'prebuilt', slot, 'terminal-owner');
|
|
21
|
+
const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), 'manifest.json'), 'utf8'));
|
|
22
|
+
if (!statSync(file).isFile() || manifest.protocol !== 1 || manifest.slot !== slot || manifest.source !== sha(readFileSync(path.join(dir, 'terminal-owner.c'))) || manifest.sha256 !== sha(readFileSync(file))) throw new Error('Native helper manifest mismatch');
|
|
23
|
+
return file;
|
|
24
|
+
}
|
|
25
|
+
/** Only an authenticated helper's exact capability record can select compatibility. */
|
|
26
|
+
export function nativeCapabilityOf(probe: { status: number | null; stdout: string }, platform: NodeJS.Platform): { available: boolean; protection?: 'root-only'; reason?: string } {
|
|
27
|
+
if (probe.status === 0 && probe.stdout.trim() === 'alp-terminal-owner:1') return { available: true };
|
|
28
|
+
if (platform === 'linux' && probe.status === 0 && probe.stdout.trim() === 'alp-terminal-owner:1:root-only') return { available: true, protection: 'root-only', reason: 'bound_signal_unavailable' };
|
|
29
|
+
return { available: false, reason: 'native_capability_unavailable' };
|
|
30
|
+
}
|
|
31
|
+
export function nativeTerminalCapability(): ReturnType<typeof nativeCapabilityOf> {
|
|
32
|
+
try {
|
|
33
|
+
const probe = spawnSync(binary(), ['--capability'], { encoding: 'utf8', timeout: 2_000, maxBuffer: 4096 });
|
|
34
|
+
return nativeCapabilityOf(probe, process.platform);
|
|
35
|
+
} catch { return { available: false, reason: 'native_prebuilt_unavailable' }; }
|
|
36
|
+
}
|
|
37
|
+
export async function nativePtySpawn(file: string, args: string[], options: { name: string; cols: number; rows: number; cwd: string; env: Record<string, string>; killGraceMs?: number; signal?: AbortSignal; protection?: 'root-only' | 'none' }) {
|
|
38
|
+
if (options.signal?.aborted) throw new Error('Native terminal startup cancelled');
|
|
39
|
+
const child = spawn(binary(), [...(options.protection === 'root-only' ? ['--root-only'] : []), String(options.cols), String(options.rows), String(options.killGraceMs ?? 1000), options.cwd, file, ...args], { env: options.env, stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe'] });
|
|
40
|
+
const control = child.stdio[4] as import('node:stream').Writable;
|
|
41
|
+
const events = child.stdio[3] as import('node:stream').Readable;
|
|
42
|
+
const data = new Set<Listener<string>>(), exits = new Set<Listener<Exit>>();
|
|
43
|
+
const decoder = new StringDecoder('utf8'); let buffered = '', protocol = '', exit: Exit | undefined, pid = 0;
|
|
44
|
+
let readyResolve!: () => void, readyReject!: (error: Error) => void, finish!: (result: CleanupResult) => void;
|
|
45
|
+
const ready = new Promise<void>((resolve, reject) => { readyResolve = resolve; readyReject = reject; });
|
|
46
|
+
const finished = new Promise<CleanupResult>(resolve => { finish = resolve; });
|
|
47
|
+
let result: CleanupResult | undefined, completed = false, closing = false, adapterFailed = false;
|
|
48
|
+
let controlBlocked = false, pendingResize: string | undefined;
|
|
49
|
+
const resizeCommand = (command: string) => {
|
|
50
|
+
if (closing || result) return;
|
|
51
|
+
if (controlBlocked) { pendingResize = command; return; }
|
|
52
|
+
controlBlocked = !control.write(command);
|
|
53
|
+
};
|
|
54
|
+
control.on('drain', () => {
|
|
55
|
+
controlBlocked = false;
|
|
56
|
+
const next = pendingResize; pendingResize = undefined;
|
|
57
|
+
if (next) resizeCommand(next);
|
|
58
|
+
});
|
|
59
|
+
const closeOwner = () => {
|
|
60
|
+
if (closing || result) return;
|
|
61
|
+
closing = true; pendingResize = undefined;
|
|
62
|
+
// No queue of resizes can stand ahead of cleanup: closing fd4 wakes native POLLHUP.
|
|
63
|
+
control.destroy(); child.stdin?.end();
|
|
64
|
+
};
|
|
65
|
+
const fail = (reason: string) => {
|
|
66
|
+
adapterFailed = true;
|
|
67
|
+
readyReject(new Error(reason));
|
|
68
|
+
// No bare child PID signaling. Closing owner input/control asks native bound cleanup.
|
|
69
|
+
closeOwner();
|
|
70
|
+
};
|
|
71
|
+
const timer = setTimeout(() => fail('Native terminal startup timed out'), 5000);
|
|
72
|
+
const complete = (value: CleanupResult) => { if (!completed) { completed = true; result = adapterFailed ? { ...value, uncertain: Math.max(1, value.uncertain) } : value; finish(result); } };
|
|
73
|
+
child.on('error', error => { fail(error.message); complete({ observed: 0, live: 0, uncertain: 1 }); });
|
|
74
|
+
child.on('close', () => {
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
if (!pid) readyReject(new Error('Native terminal refused startup'));
|
|
77
|
+
// close follows every stdio end: service exit disposal cannot discard trailing PTY output.
|
|
78
|
+
exit ??= { exitCode: null };
|
|
79
|
+
for (const listener of exits) listener(exit);
|
|
80
|
+
complete(result ?? { observed: 0, live: 0, uncertain: 1 });
|
|
81
|
+
});
|
|
82
|
+
child.stderr?.resume();
|
|
83
|
+
// Pipes may fail after native exit. Native protocol/close supplies the authoritative outcome.
|
|
84
|
+
child.stdin?.on('error', () => {}); control.on('error', () => {});
|
|
85
|
+
child.stdout?.on('data', (chunk: Buffer) => {
|
|
86
|
+
const text = decoder.write(chunk);
|
|
87
|
+
if (data.size) for (const listener of data) listener(text);
|
|
88
|
+
else if (Buffer.byteLength(buffered) + Buffer.byteLength(text) <= 1024*1024) buffered += text;
|
|
89
|
+
else fail('Native terminal output limit exceeded');
|
|
90
|
+
});
|
|
91
|
+
events.on('data', (chunk: Buffer) => {
|
|
92
|
+
protocol += chunk.toString('utf8');
|
|
93
|
+
if (protocol.length > 8192) { fail('Invalid native protocol'); return; }
|
|
94
|
+
let newline;
|
|
95
|
+
while ((newline = protocol.indexOf('\n')) >= 0) {
|
|
96
|
+
const line = protocol.slice(0, newline); protocol = protocol.slice(newline + 1);
|
|
97
|
+
try {
|
|
98
|
+
const value = JSON.parse(line);
|
|
99
|
+
if (value.ready && value.protocol === 1 && Number.isSafeInteger(value.ready) && value.ready > 1) { pid = value.ready; clearTimeout(timer); readyResolve(); }
|
|
100
|
+
else if ('exitCode' in value) { exit = { exitCode: value.exitCode, signal: value.signal }; }
|
|
101
|
+
else if (value.cleanup === true && ['observed', 'live', 'uncertain'].every(key => Number.isSafeInteger(value[key]) && value[key] >= 0)) result = value;
|
|
102
|
+
else if (value.refused === 'terminal_protection_ack_required' || value.refused === 'terminal_unsupported') { readyReject(Object.assign(new Error('Native terminal capability changed before startup'), { terminalReason: value.refused })); }
|
|
103
|
+
else if (value.error) fail(String(value.error));
|
|
104
|
+
else fail('Invalid native event');
|
|
105
|
+
} catch { fail('Invalid native JSON'); }
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
const abort = () => fail('Native terminal startup cancelled');
|
|
109
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
110
|
+
if (options.signal?.aborted) abort();
|
|
111
|
+
try { await ready; } catch (error) { const cleanupResult = await finished; throw Object.assign(error instanceof Error ? error : new Error(String(error)), { cleanupResult }); }
|
|
112
|
+
finally { options.signal?.removeEventListener('abort', abort); }
|
|
113
|
+
return {
|
|
114
|
+
pid,
|
|
115
|
+
write(value: string) { if (closing || result) return; if ((child.stdin?.writableLength ?? 0) + Buffer.byteLength(value) > 1024*1024) { fail('Native input limit exceeded'); return; } child.stdin?.write(value); },
|
|
116
|
+
resize(cols: number, rows: number) { if (Number.isInteger(cols) && Number.isInteger(rows) && cols > 0 && cols <= 1000 && rows > 0 && rows <= 1000) resizeCommand(`R ${cols} ${rows}\n`); },
|
|
117
|
+
kill() { closeOwner(); },
|
|
118
|
+
cleanup() { closeOwner(); return finished; },
|
|
119
|
+
onData(listener: Listener<string>) { data.add(listener); if (buffered) { const value = buffered; buffered = ''; queueMicrotask(() => { if (data.has(listener)) listener(value); }); } return { dispose() { data.delete(listener); } }; },
|
|
120
|
+
onExit(listener: Listener<Exit>) { exits.add(listener); if (exit && completed) { const value = exit; queueMicrotask(() => { if (exits.has(listener)) listener(value); }); } return { dispose() { exits.delete(listener); } }; },
|
|
121
|
+
};
|
|
122
|
+
}
|
package/src/operations.ts
CHANGED
|
@@ -2,11 +2,11 @@ import { createHash, createHmac, randomBytes } from 'node:crypto';
|
|
|
2
2
|
import { lstat, stat } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { CAPABILITY, ERROR, RPC_ERROR } from '@anhlp/alp-protocol';
|
|
5
|
-
import { closeTask, createTask, epicReport, loadTasks, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
|
|
5
|
+
import { closeTask, createTask, epicReport, loadTasks, rejectGate, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
|
|
6
6
|
import { taskRows } from '@anhlp/alp-core/task-rows';
|
|
7
7
|
import { deleteEntry, duplicateEntry, getEntry, listEntries, renameEntry, saveEntry, setGivenSkills } from '@anhlp/alp-core/library-edit';
|
|
8
8
|
import { listTeams } from '@anhlp/alp-core/teams';
|
|
9
|
-
import {
|
|
9
|
+
import { catalogEntries } from '@anhlp/alp-runtime/index';
|
|
10
10
|
import { listProviders } from '@anhlp/alp-core/providers';
|
|
11
11
|
import { languageSetting, setLanguage, LANGUAGE_CHARS } from '@anhlp/alp-core/user-settings';
|
|
12
12
|
import { syncProjectSettings } from '@anhlp/alp-core/init';
|
|
@@ -27,9 +27,13 @@ export type OperationsOptions = {
|
|
|
27
27
|
templates?: Record<string, string>;
|
|
28
28
|
/** Project roots the daemon knows from its session records, for a team save's sync. */
|
|
29
29
|
knownProjects?: () => Iterable<string>;
|
|
30
|
+
/** A gate changed through task.gate.resolve: the runtime syncs the project's gate cards and mail. */
|
|
31
|
+
onGateChange?: (projectRoot: string) => Promise<void> | void;
|
|
30
32
|
};
|
|
31
33
|
|
|
32
|
-
|
|
34
|
+
/** `caller.agent`: the connection said in daemon.hello that an ALP agent started it (t-ca1f). */
|
|
35
|
+
export type Caller = { agent?: boolean };
|
|
36
|
+
type Handler = (params: any, caller?: Caller) => Promise<unknown>;
|
|
33
37
|
|
|
34
38
|
/** How long task.create remembers a requestId (§10): within one alpd process only. */
|
|
35
39
|
const REQUEST_TTL_MS = 10 * 60 * 1000;
|
|
@@ -56,6 +60,7 @@ function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry
|
|
|
56
60
|
case 'TASK_NOT_FOUND': return failure(ERROR.notFound, 'unknown_task', message);
|
|
57
61
|
case 'TASK_CHANGED': case 'REVISION_CONFLICT': return failure(ERROR.conflict, 'revision_conflict', message);
|
|
58
62
|
case 'INVALID_TASK': case 'TASK_CYCLE': case 'TASK_TAKEN': case 'TASK_UNVERIFIED': return failure(ERROR.conflict, 'task_state', message);
|
|
63
|
+
case 'GATE_USER_ONLY': return failure(ERROR.forbidden, 'user_only', message);
|
|
59
64
|
case 'TASKS_LOCKED': return failure(ERROR.unavailable, 'busy', message);
|
|
60
65
|
case 'IN_USE': return failure(ERROR.conflict, 'in_use', message);
|
|
61
66
|
case 'INVALID_SCOPE': return failure(RPC_ERROR.invalidParams, 'invalid_scope', message);
|
|
@@ -119,7 +124,7 @@ function unredact(kind: string, content: Record<string, unknown>, previous: Reco
|
|
|
119
124
|
return next;
|
|
120
125
|
}
|
|
121
126
|
|
|
122
|
-
export function createOperations({ home, templates, knownProjects = () => [] }: OperationsOptions = {}) {
|
|
127
|
+
export function createOperations({ home, templates, knownProjects = () => [], onGateChange }: OperationsOptions = {}) {
|
|
123
128
|
/** Revisions on the wire are keyed per alpd process, so they never carry a hash of secret content. */
|
|
124
129
|
const revisionKey = randomBytes(32);
|
|
125
130
|
const toWire = (revision: string | null | undefined) => revision == null ? null : `r${createHmac('sha256', revisionKey).update(revision).digest('base64url').slice(0, 22)}`;
|
|
@@ -156,8 +161,8 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
|
|
|
156
161
|
catch (error: any) { if (error?.code === 'NOT_FOUND') return undefined; throw error; }
|
|
157
162
|
}
|
|
158
163
|
|
|
159
|
-
const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async params => {
|
|
160
|
-
try { return await handler(params); }
|
|
164
|
+
const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async (params, caller) => {
|
|
165
|
+
try { return await handler(params, caller); }
|
|
161
166
|
catch (error) { throw fromCore(error, context); }
|
|
162
167
|
};
|
|
163
168
|
|
|
@@ -189,22 +194,33 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
|
|
|
189
194
|
return result;
|
|
190
195
|
}),
|
|
191
196
|
|
|
192
|
-
'task.update': guard(async ({ projectRoot, id, action, note, ifRev }) => {
|
|
197
|
+
'task.update': guard(async ({ projectRoot, id, action, note, ifRev }, caller) => {
|
|
193
198
|
const root = await project(projectRoot);
|
|
194
199
|
const options = ifRev !== undefined ? { ifRev } : undefined;
|
|
195
200
|
if (action === 'reopen') {
|
|
196
201
|
const task = await reopenTask(root, id, { ...(note ? { note } : {}) }, 'user', options);
|
|
197
202
|
return { id: task.id, status: task.status, rev: task.rev };
|
|
198
203
|
}
|
|
199
|
-
const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}) }, 'user', options);
|
|
204
|
+
const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}), agent: caller?.agent === true, channel: 'web' }, 'user', options);
|
|
200
205
|
const { tasks } = await loadTasks(root);
|
|
201
206
|
const landed = tasks.some(entry => entry.parent === task.id) ? epicReport(task.id, tasks).text.split('\n')[0] : undefined;
|
|
202
207
|
return { id: task.id, status: task.status, rev: task.rev, ...(landed ? { landed } : {}) };
|
|
203
208
|
}),
|
|
204
209
|
|
|
205
|
-
|
|
210
|
+
// Approves a gate, or with reject records the user's rejection and leaves it open. Either way
|
|
211
|
+
// the runtime is told, so main gets the decision by mail once and the gate's card settles.
|
|
212
|
+
'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = 'web' }, caller) => {
|
|
206
213
|
const root = await project(projectRoot);
|
|
207
|
-
|
|
214
|
+
// Only the user decides a human gate: never a connection an ALP agent opened (t-ca1f).
|
|
215
|
+
if (caller?.agent) {
|
|
216
|
+
const { tasks } = await loadTasks(root);
|
|
217
|
+
if (tasks.find(task => task.id === id)?.gates.find(entry => entry.id === gate)?.kind === 'human') throw failure(ERROR.forbidden, 'user_only', 'Only the user decides a human gate; this connection was opened by an ALP agent');
|
|
218
|
+
}
|
|
219
|
+
const guarded = ifRev !== undefined ? { ifRev } : {};
|
|
220
|
+
const task = reject === true
|
|
221
|
+
? await rejectGate(root, id, gate, { by: 'user', channel, ...(note ? { reason: note } : {}), ...guarded })
|
|
222
|
+
: await resolveGate(root, id, gate, { by: 'user', channel, ...(note ? { note } : {}), ...(choice !== undefined ? { choice } : {}), ...guarded });
|
|
223
|
+
await onGateChange?.(root);
|
|
208
224
|
return { id: task.id, status: task.status, rev: task.rev };
|
|
209
225
|
}),
|
|
210
226
|
};
|
|
@@ -275,7 +291,7 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
|
|
|
275
291
|
'library.skills.set': guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: 'invalid_entry' }),
|
|
276
292
|
|
|
277
293
|
'library.models': guard(async () => {
|
|
278
|
-
const models: Array<{ id: string; label: string; efforts: string[]; effort?: string }> =
|
|
294
|
+
const models: Array<{ id: string; label: string; efforts: string[]; effort?: string }> = catalogEntries.map(model => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} · ${model.label}`, efforts: model.efforts, ...(model.effort ? { effort: model.effort } : {}) }));
|
|
279
295
|
for (const provider of await listProviders(home)) {
|
|
280
296
|
if (provider.enabled === false || provider.kind === 'antigravity') continue;
|
|
281
297
|
models.push({ id: `acp:${provider.id}`, label: `${provider.label} · Provider default`, efforts: [] });
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile, rename, realpath, stat, chmod, unlink } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export type ProjectRecord = { id: string; root: string; canonical?: string; customName?: string | null; addedAt: string; removedAt?: string | null };
|
|
6
|
+
export type WorkspaceRecord = { id: string; projectId: string; directory: string; canonical?: string; title?: string | null; pinnedAt?: string | null; labels: string[]; createdAt: string; archivedAt?: string | null; idempotencyKey?: string; worktree?: ManagedWorktree };
|
|
7
|
+
export type ManagedWorktree = { kind: 'user'; sourceWorkspaceId: string; source: string; commonDir: string; gitDir: string; mappingId: string; principalId: string; grantEpoch: string; requestId?: string; ifRevision?: number; branch: string; head: string; removedAt?: string };
|
|
8
|
+
export type Registry = { version: 1; revision: number; projects: ProjectRecord[]; workspaces: WorkspaceRecord[]; sessions: Record<string, string>; labels: { generation: string; seq: number; catalog: { name: string; color: string }[] }; worktreeJournal?: Record<string, { fingerprint: string; intent: any }>; receipts: Record<string, { fingerprint: string; result: unknown }> };
|
|
9
|
+
export class RegistryError extends Error {
|
|
10
|
+
constructor(readonly code: number, message: string, readonly data: { reason: string }) { super(message); }
|
|
11
|
+
}
|
|
12
|
+
function fail(reason: string, message: string, code = 1004): never { throw new RegistryError(code, message, { reason }); }
|
|
13
|
+
const hex = () => randomBytes(8).toString('hex');
|
|
14
|
+
const now = () => new Date().toISOString();
|
|
15
|
+
const object = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
|
|
16
|
+
const nullable = (v: any) => v === undefined || v === null || typeof v === 'string';
|
|
17
|
+
// Legacy bridge wire palette; domain code does not depend on the Paseo SDK.
|
|
18
|
+
const labelColors = new Set(['violet', 'sky', 'emerald', 'orange', 'pink', 'indigo', 'teal', 'red', 'amber', 'blue']);
|
|
19
|
+
const strings = (v: any) => Array.isArray(v) && v.every((s: any) => typeof s === 'string');
|
|
20
|
+
function validate(value: any): asserts value is Registry {
|
|
21
|
+
if (!object(value) || !Array.isArray(value.projects) || !Array.isArray(value.workspaces) || !object(value.sessions) || !object(value.labels)
|
|
22
|
+
|| typeof value.labels.generation !== 'string' || !Number.isSafeInteger(value.labels.seq) || value.labels.seq < 0 || !Array.isArray(value.labels.catalog)
|
|
23
|
+
|| value.labels.catalog.some((l: any) => !object(l) || typeof l.name !== 'string' || !labelColors.has(l.color))
|
|
24
|
+
|| (value.version !== undefined && value.version !== 1) || (value.revision !== undefined && (!Number.isSafeInteger(value.revision) || value.revision < 0))) fail('corrupt_registry', 'Invalid workspace registry', 1005);
|
|
25
|
+
if (value.version === 1 && (!Number.isSafeInteger(value.revision) || !object(value.receipts))) fail('corrupt_registry', 'Missing versioned registry metadata', 1005);
|
|
26
|
+
if (value.worktreeJournal !== undefined && (!object(value.worktreeJournal) || Object.values(value.worktreeJournal).some((j: any) => !object(j) || typeof j.fingerprint !== 'string' || !object(j.intent)))) fail('corrupt_registry', 'Invalid worktree journal', 1005);
|
|
27
|
+
for (const j of Object.values(value.worktreeJournal ?? {}) as any[]) { const i=j.intent; if (!['create','remove'].includes(i.method) || !/^wks_[0-9a-f]{16}$/.test(i.id) || i.branch !== `alp/workspace/${i.id}` || !['directory','source','commonDir'].every(k=>typeof i[k]==='string' && path.isAbsolute(i[k])) || !/^[0-9a-f]{40,64}$/.test(i.head)) fail('corrupt_registry','Invalid native intent',1005); }
|
|
28
|
+
const projects = new Set<string>(); const workspaces = new Set<string>();
|
|
29
|
+
for (const p of value.projects) {
|
|
30
|
+
if (!object(p) || typeof p.id !== 'string' || !p.id || projects.has(p.id) || typeof p.root !== 'string' || !path.isAbsolute(p.root) || typeof p.addedAt !== 'string' || !nullable(p.customName) || !nullable(p.removedAt) || (p.canonical !== undefined && (typeof p.canonical !== 'string' || !path.isAbsolute(p.canonical)))) fail('corrupt_registry', 'Invalid project record', 1005);
|
|
31
|
+
projects.add(p.id);
|
|
32
|
+
}
|
|
33
|
+
for (const w of value.workspaces) {
|
|
34
|
+
if (!object(w) || typeof w.id !== 'string' || !w.id || workspaces.has(w.id) || !projects.has(w.projectId) || typeof w.directory !== 'string' || !path.isAbsolute(w.directory) || typeof w.createdAt !== 'string' || ((value.version === 1 || w.labels !== undefined) && !strings(w.labels)) || !nullable(w.title) || !nullable(w.pinnedAt) || !nullable(w.archivedAt) || (w.canonical !== undefined && (typeof w.canonical !== 'string' || !path.isAbsolute(w.canonical))) || (w.idempotencyKey !== undefined && typeof w.idempotencyKey !== 'string')) fail('corrupt_registry', 'Invalid workspace record', 1005);
|
|
35
|
+
if (w.worktree !== undefined && (!object(w.worktree) || w.worktree.kind !== 'user' || ['sourceWorkspaceId','source','commonDir','gitDir','mappingId','principalId','grantEpoch','branch','head'].some(k => typeof w.worktree[k] !== 'string'))) fail('corrupt_registry', 'Invalid managed worktree', 1005);
|
|
36
|
+
workspaces.add(w.id);
|
|
37
|
+
}
|
|
38
|
+
if (Object.values(value.sessions).some(id => typeof id !== 'string' || !workspaces.has(id))) fail('corrupt_registry', 'Invalid session placement', 1005);
|
|
39
|
+
if (value.receipts !== undefined && (!object(value.receipts) || Object.values(value.receipts).some((r: any) => !object(r) || typeof r.fingerprint !== 'string' || !Object.hasOwn(r, 'result')))) fail('corrupt_registry', 'Invalid operation receipts', 1005);
|
|
40
|
+
}
|
|
41
|
+
const placementOf = (r: Registry, id: string) => Object.hasOwn(r.sessions, id) ? r.sessions[id] : undefined;
|
|
42
|
+
const place = (r: Registry, id: string, workspaceId: string) => Object.defineProperty(r.sessions, id, { value: workspaceId, writable: true, enumerable: true, configurable: true });
|
|
43
|
+
async function identity(directory: string) {
|
|
44
|
+
if (typeof directory !== 'string' || !path.isAbsolute(directory)) fail('directory_not_found', 'An absolute existing directory is required', -32602);
|
|
45
|
+
const canonical = await realpath(directory);
|
|
46
|
+
if (!(await stat(canonical)).isDirectory()) fail('directory_not_found', 'An existing directory is required', -32602);
|
|
47
|
+
return canonical;
|
|
48
|
+
}
|
|
49
|
+
/** Sole mutable owner. Failed writes never publish the draft or consume a requestId. */
|
|
50
|
+
export function createRegistry(home: string, options: { write?: typeof writeFile } = {}) {
|
|
51
|
+
const file = path.join(home, 'state', 'web-workspaces.json');
|
|
52
|
+
let committed: Registry | undefined;
|
|
53
|
+
let tail: Promise<unknown> = Promise.resolve();
|
|
54
|
+
const serial = <T>(fn: () => Promise<T>): Promise<T> => { const result = tail.then(fn); tail = result.catch(() => {}); return result; };
|
|
55
|
+
const write = options.write ?? writeFile;
|
|
56
|
+
async function persist(value: Registry) {
|
|
57
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
58
|
+
await chmod(path.dirname(file), 0o700);
|
|
59
|
+
const temporary = `${file}.${hex()}.tmp`;
|
|
60
|
+
try { await write(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600, flag: 'wx' }); await rename(temporary, file); }
|
|
61
|
+
finally { await unlink(temporary).catch(() => {}); }
|
|
62
|
+
}
|
|
63
|
+
async function load() {
|
|
64
|
+
if (committed) return;
|
|
65
|
+
let text: string;
|
|
66
|
+
try { text = await readFile(file, 'utf8'); }
|
|
67
|
+
catch (error: any) {
|
|
68
|
+
if (error.code !== 'ENOENT') throw error;
|
|
69
|
+
committed = { version: 1, revision: 0, projects: [], workspaces: [], sessions: {}, labels: { generation: hex(), seq: 0, catalog: [] }, receipts: {} }; return;
|
|
70
|
+
}
|
|
71
|
+
let parsed: any;
|
|
72
|
+
try { parsed = JSON.parse(text); } catch { fail('corrupt_registry', 'Workspace registry is unreadable; original retained', 1005); }
|
|
73
|
+
validate(parsed);
|
|
74
|
+
if (parsed.version === undefined) {
|
|
75
|
+
// Keep the exact original for recovery. Never replace it with a synthesized format.
|
|
76
|
+
await writeFile(`${file}.legacy-v0.json`, text, { mode: 0o600, flag: 'wx' }).catch((e: any) => { if (e.code !== 'EEXIST') throw e; });
|
|
77
|
+
await chmod(`${file}.legacy-v0.json`, 0o600);
|
|
78
|
+
const migrated = { ...parsed, version: 1 as const, revision: 0, receipts: {}, workspaces: parsed.workspaces.map((w: WorkspaceRecord) => ({ ...w, labels: w.labels ?? [] })) };
|
|
79
|
+
for (const p of migrated.projects) p.canonical = await realpath(p.root).catch(() => undefined);
|
|
80
|
+
for (const w of migrated.workspaces) w.canonical = await realpath(w.directory).catch(() => undefined);
|
|
81
|
+
await persist(migrated); committed = migrated;
|
|
82
|
+
} else { await chmod(path.dirname(file), 0o700); await chmod(file, 0o600); committed = parsed; }
|
|
83
|
+
}
|
|
84
|
+
const project = (r: Registry, id: string) => r.projects.find(p => p.id === id) ?? fail('not_found', 'No project', 1001);
|
|
85
|
+
const workspace = (r: Registry, id: string) => r.workspaces.find(w => w.id === id) ?? fail('not_found', 'No workspace', 1001);
|
|
86
|
+
const live = (r: Registry, w: WorkspaceRecord) => !w.archivedAt && !project(r, w.projectId).removedAt;
|
|
87
|
+
function register(r: Registry, directory: string, canonical?: string) {
|
|
88
|
+
let p = r.projects.find(p => !p.removedAt && (p.canonical ?? path.resolve(p.root)) === (canonical ?? path.resolve(directory)));
|
|
89
|
+
if (!p) { p = { id: `prj_${hex()}`, root: directory, ...(canonical === undefined ? {} : { canonical }), addedAt: now() }; r.projects.push(p); }
|
|
90
|
+
return p;
|
|
91
|
+
}
|
|
92
|
+
function makeWorkspace(r: Registry, p: ProjectRecord, directory: string, canonical: string | undefined, fields: Partial<WorkspaceRecord> = {}) {
|
|
93
|
+
const w: WorkspaceRecord = { id: `wks_${hex()}`, projectId: p.id, directory, ...(canonical === undefined ? {} : { canonical }), labels: [], createdAt: now(), ...fields }; r.workspaces.push(w); return w;
|
|
94
|
+
}
|
|
95
|
+
async function action(r: Registry, method: string, a: any): Promise<any> {
|
|
96
|
+
switch (method) {
|
|
97
|
+
case 'project.add': { const canonical = await identity(a.directory); return { project: register(r, a.directory, canonical) }; }
|
|
98
|
+
case 'project.register': {
|
|
99
|
+
const canonical = await identity(a.directory); const p = register(r, a.directory, canonical);
|
|
100
|
+
if (!r.workspaces.some(w => w.projectId === p.id && live(r, w) && (w.canonical ?? w.directory) === canonical)) makeWorkspace(r, p, a.directory, canonical);
|
|
101
|
+
return { project: p };
|
|
102
|
+
}
|
|
103
|
+
case 'project.remove': { const p = project(r, a.projectId); p.removedAt = now(); for (const w of r.workspaces.filter(w => w.projectId === p.id)) { w.archivedAt = now(); w.pinnedAt = null; } return { project: p }; }
|
|
104
|
+
case 'project.rename': { const p = project(r, a.projectId); p.customName = a.customName?.trim() || null; return { project: p }; }
|
|
105
|
+
case 'workspace.create': {
|
|
106
|
+
const canonical = await identity(a.directory);
|
|
107
|
+
const previous = a.idempotencyKey ? r.workspaces.find(w => w.idempotencyKey === a.idempotencyKey) : undefined;
|
|
108
|
+
if (previous) { if ((previous.canonical ?? previous.directory) !== canonical) fail('request_conflict', 'Idempotency key names another directory'); return { workspace: previous }; }
|
|
109
|
+
const p = a.projectId ? project(r, a.projectId) : register(r, a.directory, canonical);
|
|
110
|
+
if (p.removedAt) fail('not_found', 'Project was removed', 1001);
|
|
111
|
+
return { workspace: makeWorkspace(r, p, a.directory, canonical, { ...(a.workspaceId ? { id: a.workspaceId } : {}), title: a.title?.trim() || null, ...(a.idempotencyKey ? { idempotencyKey: a.idempotencyKey } : {}) }) };
|
|
112
|
+
}
|
|
113
|
+
case 'workspace.update': {
|
|
114
|
+
const w = workspace(r, a.workspaceId);
|
|
115
|
+
if (a.title !== undefined) w.title = a.title?.trim() || null;
|
|
116
|
+
if (a.pinned !== undefined) w.pinnedAt = a.pinned ? w.pinnedAt ?? now() : null;
|
|
117
|
+
if (a.archived !== undefined) { w.archivedAt = a.archived ? now() : null; if (a.archived) w.pinnedAt = null; }
|
|
118
|
+
return { workspace: w };
|
|
119
|
+
}
|
|
120
|
+
case 'placement.prepare': {
|
|
121
|
+
for (const s of a.sessions) {
|
|
122
|
+
const mapped = placementOf(r, s.id);
|
|
123
|
+
let w = mapped ? workspace(r, mapped) : undefined;
|
|
124
|
+
const historical = s.archived || s.status === 'closed' || s.status === 'error';
|
|
125
|
+
// Preparation projects saved roots, including history and processes whose cwd
|
|
126
|
+
// was deleted. It does not authorize execution: resolve still checks live identity.
|
|
127
|
+
// A saved mapping must never be rebound through a retargeted directory alias.
|
|
128
|
+
if (w) {
|
|
129
|
+
if (!historical && w.archivedAt) w.archivedAt = null;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (typeof s.projectRoot !== 'string' || !path.isAbsolute(s.projectRoot)) fail('directory_not_found', 'An absolute directory is required', -32602);
|
|
133
|
+
const lexical = path.resolve(s.projectRoot);
|
|
134
|
+
// A lexical fallback is placement metadata, never proof of canonical identity.
|
|
135
|
+
const canonical = await identity(s.projectRoot).catch((error: any) => {
|
|
136
|
+
if (historical || error.code === 'ENOENT' || error.code === 'ENOTDIR') return undefined;
|
|
137
|
+
throw error;
|
|
138
|
+
});
|
|
139
|
+
const here = r.workspaces.filter(w => canonical === undefined ? path.resolve(w.directory) === lexical : (w.canonical ?? w.directory) === canonical).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
140
|
+
w = here.find(w => live(r, w)) ?? (s.archived ? here.at(-1) : undefined) ?? makeWorkspace(r, register(r, s.projectRoot, canonical), s.projectRoot, canonical, s.archived ? { archivedAt: s.updatedAt ?? now() } : {});
|
|
141
|
+
place(r, s.id, w.id);
|
|
142
|
+
}
|
|
143
|
+
return {};
|
|
144
|
+
}
|
|
145
|
+
case 'placement.assign': { workspace(r, a.workspaceId); if (placementOf(r, a.sessionId) && placementOf(r, a.sessionId) !== a.workspaceId) fail('workspace_mismatch', 'Session already has another workspace'); place(r, a.sessionId, a.workspaceId); return {}; }
|
|
146
|
+
case 'placement.remove': { if (placementOf(r, a.sessionId) === a.workspaceId) delete r.sessions[a.sessionId]; return {}; }
|
|
147
|
+
case 'label.assign': {
|
|
148
|
+
const w = workspace(r, a.workspaceId); const name = a.label.name.trim().replace(/\s+/g, ' '); if (!name) fail('invalid_label', 'A label needs a name', -32602);
|
|
149
|
+
let l = r.labels.catalog.find(l => l.name.toLowerCase() === name.toLowerCase());
|
|
150
|
+
if (!l && a.assigned) { l = { name, color: a.label.color }; r.labels.catalog.push(l); r.labels.seq++; }
|
|
151
|
+
w.labels = w.labels.filter(n => n.toLowerCase() !== name.toLowerCase()); if (a.assigned && l) w.labels.push(l.name); return { label: l ?? a.label, workspaceLabels: w.labels };
|
|
152
|
+
}
|
|
153
|
+
case 'label.update': {
|
|
154
|
+
const l = r.labels.catalog.find(l => l.name.toLowerCase() === a.name.toLowerCase()); if (!l) fail('not_found', 'No label', 1001);
|
|
155
|
+
const previousName = l.name; const name = a.newName === undefined ? l.name : a.newName.trim().replace(/\s+/g, ' ');
|
|
156
|
+
if (!name || r.labels.catalog.some(other => other !== l && other.name.toLowerCase() === name.toLowerCase())) fail('label_name_taken', 'Invalid or duplicate label', -32602);
|
|
157
|
+
l.name = name; if (a.color) l.color = a.color;
|
|
158
|
+
let affectedWorkspaceCount = 0;
|
|
159
|
+
for (const w of r.workspaces) { const i = w.labels.findIndex(n => n.toLowerCase() === previousName.toLowerCase()); if (i >= 0) { w.labels[i] = name; affectedWorkspaceCount++; } }
|
|
160
|
+
r.labels.seq++; return { label: l, previousName, affectedWorkspaceCount };
|
|
161
|
+
}
|
|
162
|
+
case 'label.delete': {
|
|
163
|
+
const l = r.labels.catalog.find(l => l.name.toLowerCase() === a.name.toLowerCase()); if (!l) fail('not_found', 'No label', 1001);
|
|
164
|
+
r.labels.catalog = r.labels.catalog.filter(other => other !== l); let affectedWorkspaceCount = 0;
|
|
165
|
+
for (const w of r.workspaces) { const before = w.labels.length; w.labels = w.labels.filter(n => n.toLowerCase() !== l.name.toLowerCase()); if (before !== w.labels.length) affectedWorkspaceCount++; }
|
|
166
|
+
r.labels.seq++; return { affectedWorkspaceCount };
|
|
167
|
+
}
|
|
168
|
+
default: return fail('unknown_operation', 'Unknown registry operation', -32602);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const fingerprintOf = (args: any, revision: number | undefined) => createHash('sha256').update(JSON.stringify({ args, ifRevision: revision }, (_key, value) => object(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value)).digest('hex');
|
|
172
|
+
return {
|
|
173
|
+
/** Native intent and receipt share the sole registry writer and atomic persistence boundary. */
|
|
174
|
+
nativeMutation: (method: string, args: any, context: { actor: string; requestId: string; ifRevision: number }, prepare: (r: Registry) => Promise<any>, apply: (intent: any, draft: Registry) => Promise<any>) => serial(async () => {
|
|
175
|
+
await load();
|
|
176
|
+
if (!context.requestId || typeof context.requestId !== 'string' || context.requestId.length > 200 || !Number.isSafeInteger(context.ifRevision) || context.ifRevision < 0) fail('invalid_request_id', 'requestId and ifRevision are required', -32602);
|
|
177
|
+
const key = createHash('sha256').update(JSON.stringify([context.actor, method, context.requestId])).digest('hex');
|
|
178
|
+
const fingerprint = fingerprintOf(args, context.ifRevision);
|
|
179
|
+
const receipt = committed!.receipts[key];
|
|
180
|
+
if (receipt) { if (receipt.fingerprint !== fingerprint) fail('request_conflict', 'requestId reused'); return structuredClone(receipt.result); }
|
|
181
|
+
const pending = committed!.worktreeJournal?.[key];
|
|
182
|
+
if (pending && pending.fingerprint !== fingerprint) fail('request_conflict', 'requestId reused');
|
|
183
|
+
if (!pending && Object.keys(committed!.worktreeJournal ?? {}).length) fail('reconciliation_required', 'Retry the pending worktree request before another mutation');
|
|
184
|
+
if (!pending && context.ifRevision !== committed!.revision) fail('stale_revision', 'Registry changed; refresh');
|
|
185
|
+
if (!pending) {
|
|
186
|
+
const intent = await prepare(structuredClone(committed!));
|
|
187
|
+
const draft = structuredClone(committed!); (draft.worktreeJournal ??= {})[key] = { fingerprint, intent };
|
|
188
|
+
await persist(draft); committed = draft;
|
|
189
|
+
}
|
|
190
|
+
const draft = structuredClone(committed!);
|
|
191
|
+
const result = await apply(structuredClone(draft.worktreeJournal![key].intent), draft);
|
|
192
|
+
draft.revision++;
|
|
193
|
+
const response = { ...result, revision: draft.revision };
|
|
194
|
+
draft.receipts[key] = { fingerprint, result: structuredClone(response) }; delete draft.worktreeJournal![key];
|
|
195
|
+
validate(draft); await persist(draft); committed = draft; return structuredClone(response);
|
|
196
|
+
}),
|
|
197
|
+
snapshot: () => serial(async () => { await load(); return structuredClone(committed!); }),
|
|
198
|
+
mutate: (method: string, args: any, context: { actor?: string; allowedRoots?: string[]; ifRevision?: number; requestId: string }) => serial(async () => {
|
|
199
|
+
await load();
|
|
200
|
+
if (Object.keys(committed!.worktreeJournal ?? {}).length) fail('reconciliation_required', 'Retry the pending worktree request before changing metadata');
|
|
201
|
+
if (context.allowedRoots) {
|
|
202
|
+
const checked = async (directory: string, canonical?: string) => {
|
|
203
|
+
const actual = await identity(directory);
|
|
204
|
+
if (!context.allowedRoots!.includes(actual) || (canonical !== undefined && canonical !== actual)) fail('outside_workspace', 'Resource is outside the credential grant', 1003);
|
|
205
|
+
};
|
|
206
|
+
if (method === 'project.register') await checked(args.directory);
|
|
207
|
+
else if (method === 'workspace.update') { const w = workspace(committed!, args.workspaceId); await checked(w.directory, w.canonical); }
|
|
208
|
+
else if (method === 'project.remove') {
|
|
209
|
+
const p = project(committed!, args.projectId); await checked(p.root, p.canonical);
|
|
210
|
+
for (const w of committed!.workspaces.filter(w => w.projectId === p.id)) await checked(w.directory, w.canonical);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (!context.requestId || typeof context.requestId !== 'string' || context.requestId.length > 200) fail('invalid_request_id', 'requestId is required', -32602);
|
|
214
|
+
const key = createHash('sha256').update(JSON.stringify([context.actor ?? 'owner', method, context.requestId])).digest('hex');
|
|
215
|
+
const fingerprint = createHash('sha256').update(JSON.stringify({ args, ifRevision: context.ifRevision }, (_key, value) => object(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value)).digest('hex');
|
|
216
|
+
const receipt = committed!.receipts[key];
|
|
217
|
+
if (receipt) { if (receipt.fingerprint !== fingerprint) fail('request_conflict', 'requestId reused with different payload'); return structuredClone(receipt.result); }
|
|
218
|
+
if (context.ifRevision !== undefined && context.ifRevision !== committed!.revision) fail('stale_revision', 'Registry changed; refresh and retry');
|
|
219
|
+
const draft = structuredClone(committed!); const result = await action(draft, method, args);
|
|
220
|
+
if (method === 'placement.prepare' && JSON.stringify(draft) === JSON.stringify(committed)) return { ...result, revision: draft.revision };
|
|
221
|
+
draft.revision++;
|
|
222
|
+
const response = { ...result, revision: draft.revision };
|
|
223
|
+
draft.receipts[key] = { fingerprint, result: structuredClone(response) };
|
|
224
|
+
validate(draft); await persist(draft); committed = draft;
|
|
225
|
+
return structuredClone(response);
|
|
226
|
+
}),
|
|
227
|
+
async resolve(workspaceId: string, cwd?: string, includeArchived = false) {
|
|
228
|
+
const r = await this.snapshot(); const w = workspace(r, workspaceId);
|
|
229
|
+
if (!includeArchived && !live(r, w)) fail('not_found', 'Workspace is archived', 1001);
|
|
230
|
+
if (Object.values(r.worktreeJournal ?? {}).some(j => j.intent.id === workspaceId)) fail('reconciliation_required', 'Workspace mutation requires reconciliation');
|
|
231
|
+
const canonical = await identity(w.directory);
|
|
232
|
+
if (canonical !== (w.canonical ?? w.directory)) fail('identity_changed', 'Workspace directory identity changed', 1003);
|
|
233
|
+
if (cwd !== undefined && await identity(cwd) !== canonical) fail('cwd_mismatch', 'cwd and workspaceId must agree', -32602);
|
|
234
|
+
return canonical;
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
export type RegistryService = ReturnType<typeof createRegistry>;
|