@anhlp/alp-daemon 0.0.0-stage → 0.0.1-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +14 -2
- package/dist/THIRD-PARTY-NOTICES.txt +456 -0
- package/dist/alp-templates.d.ts +5 -0
- package/dist/alpd.js +64050 -0
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +150 -0
- 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 +262 -0
- package/dist/files.js +674 -0
- package/dist/git.d.ts +98 -0
- package/dist/git.js +1246 -0
- package/dist/gitignore.d.ts +62 -0
- package/dist/gitignore.js +254 -0
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +28 -0
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/lock.d.ts +21 -0
- package/dist/lock.js +42 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +363 -0
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +44 -0
- package/dist/native-entry.d.ts +2 -0
- package/dist/native-entry.js +3 -0
- package/dist/native-register.d.ts +1 -0
- package/dist/native-register.js +13 -0
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +201 -0
- package/dist/operations.d.ts +40 -0
- package/dist/operations.js +313 -0
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/rpc-error.d.ts +6 -0
- package/dist/rpc-error.js +11 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +298 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +60 -0
- package/dist/server.js +1958 -0
- package/dist/store.d.ts +178 -0
- package/dist/store.js +386 -0
- 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 +203 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +32 -0
- package/dist/windows-terminal.js +79 -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 +163 -4
- package/src/alp-templates.d.ts +5 -0
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +884 -0
- package/src/git.ts +1220 -0
- package/src/gitignore.ts +277 -0
- package/src/history.ts +118 -0
- package/src/index.ts +12 -0
- package/src/lifecycle.ts +283 -0
- package/src/lock.ts +53 -0
- package/src/main.ts +381 -0
- package/src/model-catalog.ts +36 -0
- package/src/native-entry.ts +5 -0
- package/src/native-register.ts +21 -0
- package/src/native-terminal.ts +127 -0
- package/src/operations.ts +329 -0
- package/src/registry.ts +238 -0
- package/src/rpc-error.ts +4 -0
- package/src/scheduler.ts +438 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +2238 -0
- package/src/store.ts +449 -0
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +653 -0
- package/src/windows-terminal.ts +74 -0
- package/src/worktrees.ts +382 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows terminals (best-effort, like Paseo/Orca): the platform PTY through node-pty (ConPTY).
|
|
3
|
+
* There is no protection helper on Windows: closing a terminal kills its pty (node-pty `kill`),
|
|
4
|
+
* which ends the shell; processes it started may keep running. Terminals report `protection: 'none'`.
|
|
5
|
+
*/
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import type { PtySpawn } from './terminals.js';
|
|
8
|
+
|
|
9
|
+
/** The node-pty surface the win32 owner uses. */
|
|
10
|
+
export type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
|
|
11
|
+
pid: number; write(data: string): void; resize(cols: number, rows: number): void; kill(signal?: string): void;
|
|
12
|
+
onData(listener: (data: string) => void): { dispose(): void }; onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
|
|
13
|
+
} };
|
|
14
|
+
|
|
15
|
+
let loaded: NodePty | null | undefined;
|
|
16
|
+
/** node-pty, or undefined when it cannot load on this host. */
|
|
17
|
+
export function loadNodePty(): NodePty | undefined {
|
|
18
|
+
if (loaded === undefined) {
|
|
19
|
+
try { loaded = createRequire(import.meta.url)('node-pty') as NodePty; } catch { loaded = null; }
|
|
20
|
+
}
|
|
21
|
+
return loaded ?? undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `load` is a test hook (tests/windows-terminal.test.js); production loads the installed node-pty. */
|
|
25
|
+
export function windowsTerminalCapability(load: () => NodePty | undefined = loadNodePty): { available: boolean; protection?: 'none'; reason?: string } {
|
|
26
|
+
return load() ? { available: true, protection: 'none' } : { available: false, reason: 'node_pty_unavailable' };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The shell for a Windows terminal: COMSPEC when absolute, else cmd.exe. */
|
|
30
|
+
export function windowsShell(env: NodeJS.ProcessEnv = process.env): string {
|
|
31
|
+
const candidate = env.ComSpec ?? env.COMSPEC;
|
|
32
|
+
return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : 'cmd.exe';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The win32 owner over `load`'s node-pty; `load` is a test hook, production uses {@link windowsPtySpawn}. */
|
|
36
|
+
export const createWindowsPtySpawn = (load: () => NodePty | undefined = loadNodePty): PtySpawn => (file, args, options) => {
|
|
37
|
+
if (options.signal?.aborted) throw new Error('Terminal startup cancelled');
|
|
38
|
+
const pty = load();
|
|
39
|
+
if (!pty) throw new Error('node-pty is unavailable on this host');
|
|
40
|
+
const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
|
|
41
|
+
let killed = false;
|
|
42
|
+
// Waited for after kill so that a closed terminal no longer holds its working directory (t-bfbd).
|
|
43
|
+
// process.kill(pid, 0) is not that point: libuv reads the exit code, which Windows sets before it
|
|
44
|
+
// closes the shell's handles, the cwd among them (rmdir right after a TerminateProcess: EBUSY).
|
|
45
|
+
// node-pty emits exit when its output socket closes (after kill: ClosePseudoConsole, then the conout
|
|
46
|
+
// drain); the exit code it carries is set only by its native WaitForSingleObject on the shell's process
|
|
47
|
+
// handle, which returns once those handles are closed. A numeric exit code therefore means the
|
|
48
|
+
// directory was released; the order of the two is what node-pty does, not something it promises
|
|
49
|
+
// (every exit after a kill carried a numeric code here, 200 of 200 on Windows 10). Best-effort, like
|
|
50
|
+
// the rest of the Windows owner. Subscribed here, before any service listener.
|
|
51
|
+
let exit = false;
|
|
52
|
+
const exited = new Promise<void>(resolve => { child.onExit(() => { exit = true; resolve(); }); });
|
|
53
|
+
return {
|
|
54
|
+
// node-pty reports the ConPTY shell's pid only once its output worker connects (0 until then), so
|
|
55
|
+
// the pid is read live rather than copied at spawn.
|
|
56
|
+
get pid() { return child.pid; },
|
|
57
|
+
write(data: string) { if (!killed) child.write(data); },
|
|
58
|
+
resize(cols: number, rows: number) { if (!killed) try { child.resize(cols, rows); } catch { /* exited */ } },
|
|
59
|
+
// Best-effort: node-pty ends the ConPTY session and its shell; descendants are not guaranteed.
|
|
60
|
+
kill() { if (killed) return; killed = true; try { child.kill(); } catch { /* already exited */ } },
|
|
61
|
+
// Bounded: node-pty defers a kill until the terminal is ready (its first output) and may never report
|
|
62
|
+
// an exit (a terminal that never becomes ready, a lost callback); that does not hold up close.
|
|
63
|
+
async exited(ms: number) {
|
|
64
|
+
if (exit) return;
|
|
65
|
+
let timer: NodeJS.Timeout | undefined;
|
|
66
|
+
await Promise.race([exited, new Promise<void>(resolve => { timer = setTimeout(resolve, ms); })]);
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
},
|
|
69
|
+
onData: listener => child.onData(listener),
|
|
70
|
+
onExit: listener => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal })),
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export const windowsPtySpawn: PtySpawn = createWindowsPtySpawn();
|
package/src/worktrees.ts
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, readFile, realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { user_worktree } from '@anhlp/alp-core';
|
|
6
|
+
import { RegistryError, type RegistryService, type Registry, type WorkspaceRecord } from './registry.js';
|
|
7
|
+
|
|
8
|
+
type Mapping = { id: string; source: string; commonDir: string; parent: string };
|
|
9
|
+
type Context = { principalId?: string; principalEpoch?: string; mappingIds?: string[]; authorizedRoots?: string[] };
|
|
10
|
+
/** What the owner confirms before a legacy managed worktree is adopted (t-c1ba), each proven from Git and the filesystem. */
|
|
11
|
+
export type AdoptionFacts = { workspaceId: string; directory: string; source: string; commonDir: string; gitDir: string; branch: string; head: string };
|
|
12
|
+
const fail = (reason: string, message: string, code = 1004): never => {
|
|
13
|
+
throw new RegistryError(code, message, { reason });
|
|
14
|
+
};
|
|
15
|
+
const git = user_worktree.userWorktreeGit;
|
|
16
|
+
/** Owner-only file; neither an RPC parameter nor repository configuration can approve a destination. */
|
|
17
|
+
export async function worktreeMappings(home: string): Promise<Mapping[]> {
|
|
18
|
+
const file = path.join(home, 'worktree-destinations.json');
|
|
19
|
+
const info = await lstat(file).catch((e: any) => {
|
|
20
|
+
if (e.code === 'ENOENT') return undefined;
|
|
21
|
+
throw e;
|
|
22
|
+
});
|
|
23
|
+
if (!info) return [];
|
|
24
|
+
if (!info.isFile() || (process.platform !== 'win32' && (info.uid !== process.getuid?.() || info.mode & 0o077)))
|
|
25
|
+
fail('mapping_invalid', 'Worktree destination configuration must be private', 1005);
|
|
26
|
+
const value = JSON.parse(await readFile(file, 'utf8'));
|
|
27
|
+
if (value?.version !== 1 || !Array.isArray(value.mappings))
|
|
28
|
+
fail('mapping_invalid', 'Invalid worktree destination configuration', 1005);
|
|
29
|
+
const ids = new Set<string>();
|
|
30
|
+
for (const m of value.mappings) {
|
|
31
|
+
if (!m || typeof m.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(m.id) || ids.has(m.id))
|
|
32
|
+
fail('mapping_invalid', 'Invalid mapping identity', 1005);
|
|
33
|
+
ids.add(m.id);
|
|
34
|
+
for (const k of ['source', 'commonDir', 'parent']) {
|
|
35
|
+
if (
|
|
36
|
+
typeof m[k] !== 'string' ||
|
|
37
|
+
!path.isAbsolute(m[k]) ||
|
|
38
|
+
(await realpath(m[k])) !== m[k] ||
|
|
39
|
+
!(await stat(m[k])).isDirectory()
|
|
40
|
+
)
|
|
41
|
+
fail('mapping_invalid', 'Mapping paths must be existing canonical directories', 1005);
|
|
42
|
+
}
|
|
43
|
+
const parentInfo = await stat(m.parent);
|
|
44
|
+
if (process.platform !== 'win32' && (parentInfo.uid !== process.getuid?.() || parentInfo.mode & 0o077))
|
|
45
|
+
fail('mapping_invalid', 'Destination parent must be owner-private', 1005);
|
|
46
|
+
for (const reserved of [path.join(home, 'worktrees'), path.join(home, 'copies'), m.commonDir])
|
|
47
|
+
if (m.parent === reserved || m.parent.startsWith(reserved + path.sep) || reserved.startsWith(m.parent + path.sep))
|
|
48
|
+
fail('mapping_invalid', 'Destination overlaps protected assignment or Git storage', 1005);
|
|
49
|
+
if (m.parent === m.source || m.parent.startsWith(m.source + path.sep) || m.source.startsWith(m.parent + path.sep))
|
|
50
|
+
fail('mapping_invalid', 'Destination parent must be separate from source', 1005);
|
|
51
|
+
}
|
|
52
|
+
return value.mappings;
|
|
53
|
+
}
|
|
54
|
+
export function createWorkspaceWorktrees(
|
|
55
|
+
home: string,
|
|
56
|
+
registry: RegistryService,
|
|
57
|
+
guard: <T>(directory: string, run: () => Promise<T>) => Promise<T>,
|
|
58
|
+
register: (directory: string) => Promise<void>,
|
|
59
|
+
adoptWorkspace?: (directory: string, verify: (canonical: string) => Promise<void>) => Promise<void>
|
|
60
|
+
) {
|
|
61
|
+
const adapter = git();
|
|
62
|
+
async function approved(context: Context, source: string, mappingId: string, native = true) {
|
|
63
|
+
const m = (await worktreeMappings(home)).find((m) => m.id === mappingId && m.source === source);
|
|
64
|
+
if (!m) return fail('outside_workspace', 'Mapping unavailable', 1003);
|
|
65
|
+
if (
|
|
66
|
+
(context.mappingIds && !context.mappingIds.includes(m.id)) ||
|
|
67
|
+
(context.authorizedRoots && !context.authorizedRoots.includes(source))
|
|
68
|
+
)
|
|
69
|
+
fail('outside_workspace', 'Worktree mapping is not approved for this credential', 1003);
|
|
70
|
+
if ((await (native ? adapter.facts(source) : user_worktree.repositoryIdentity(source))).commonDir !== m.commonDir)
|
|
71
|
+
fail('identity_changed', 'Source repository identity changed', 1003);
|
|
72
|
+
return m;
|
|
73
|
+
}
|
|
74
|
+
const workspace = (r: Registry, id: string) =>
|
|
75
|
+
r.workspaces.find((w) => w.id === id) ?? fail('not_found', 'No workspace', 1001);
|
|
76
|
+
async function sourceOf(r: Registry, id: string) {
|
|
77
|
+
const w = workspace(r, id);
|
|
78
|
+
if (w.archivedAt || w.worktree?.removedAt || r.projects.find((p) => p.id === w.projectId)?.removedAt)
|
|
79
|
+
fail('not_found', 'Workspace unavailable', 1001);
|
|
80
|
+
if ((await realpath(w.directory)) !== (w.canonical ?? w.directory))
|
|
81
|
+
fail('identity_changed', 'Source identity changed', 1003);
|
|
82
|
+
return w;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Proves what adopting a managed worktree would certify. The registry row only names what to
|
|
86
|
+
* check; it is never evidence of identity, and never permission to delete.
|
|
87
|
+
*/
|
|
88
|
+
async function adoptionFacts(r: Registry, id: string): Promise<AdoptionFacts> {
|
|
89
|
+
const w = workspace(r, id);
|
|
90
|
+
const meta = w.worktree;
|
|
91
|
+
if (!meta || meta.kind !== 'user' || meta.removedAt || w.archivedAt)
|
|
92
|
+
return fail('not_managed', 'Only a present managed user worktree can be adopted', 1003);
|
|
93
|
+
if (Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === w.id))
|
|
94
|
+
fail('reconciliation_required', 'Workspace is pending reconciliation');
|
|
95
|
+
// The source repository and its commonDir as the host approves them now, not as the row recorded them.
|
|
96
|
+
const mapping = (await worktreeMappings(home)).find(
|
|
97
|
+
(m) => m.id === meta.mappingId && m.source === meta.source && m.commonDir === meta.commonDir
|
|
98
|
+
);
|
|
99
|
+
if (!mapping) return fail('outside_workspace', 'The host does not approve its destination mapping now', 1003);
|
|
100
|
+
const directory = path.join(mapping.parent, w.id);
|
|
101
|
+
const branch = `alp/workspace/${w.id}`;
|
|
102
|
+
if (!/^wks_[0-9a-f]{16}$/.test(w.id) || w.directory !== directory || (w.canonical ?? w.directory) !== directory || meta.branch !== branch)
|
|
103
|
+
fail('identity_changed', 'Not a generated managed worktree', 1003);
|
|
104
|
+
// No symlink anywhere on the path: it is a real directory whose canonical path is itself.
|
|
105
|
+
const info = await lstat(directory).catch(() => undefined);
|
|
106
|
+
if (!info?.isDirectory() || (await realpath(directory).catch(() => undefined)) !== directory)
|
|
107
|
+
fail('identity_changed', 'Managed worktree path is missing or not canonical', 1003);
|
|
108
|
+
const origin = await adapter.facts(mapping.source).catch(() => undefined);
|
|
109
|
+
if (origin?.commonDir !== mapping.commonDir) fail('identity_changed', 'Source repository identity changed', 1003);
|
|
110
|
+
// Git lists it as a linked worktree of that repository on its own branch, neither locked nor prunable.
|
|
111
|
+
const row = await adapter.inspect(mapping.source, directory, branch).catch(() => undefined);
|
|
112
|
+
const target = row ? await adapter.facts(directory).catch(() => undefined) : undefined;
|
|
113
|
+
if (
|
|
114
|
+
!row ||
|
|
115
|
+
!target ||
|
|
116
|
+
target.commonDir !== mapping.commonDir ||
|
|
117
|
+
target.gitDir === target.commonDir ||
|
|
118
|
+
target.gitDir !== meta.gitDir ||
|
|
119
|
+
target.branch !== branch ||
|
|
120
|
+
row.HEAD !== target.head
|
|
121
|
+
)
|
|
122
|
+
return fail('identity_changed', 'Git does not list it as this managed worktree', 1003);
|
|
123
|
+
return { workspaceId: w.id, directory, source: mapping.source, commonDir: mapping.commonDir, gitDir: target.gitDir, branch, head: target.head };
|
|
124
|
+
}
|
|
125
|
+
const owner = (context: Context) => {
|
|
126
|
+
if ((context.principalId ?? 'owner') !== 'owner' || (context.principalEpoch ?? 'owner') !== 'owner' || context.mappingIds || context.authorizedRoots)
|
|
127
|
+
fail('owner_only', 'Only the host owner adopts a workspace', 1003);
|
|
128
|
+
};
|
|
129
|
+
/** Owner-private append-only record of every adoption request and its outcome. */
|
|
130
|
+
async function audit(entry: Record<string, unknown>) {
|
|
131
|
+
const file = path.join(home, 'state', 'workspace-adoptions.jsonl');
|
|
132
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
133
|
+
const handle = await open(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
|
|
134
|
+
try {
|
|
135
|
+
await handle.writeFile(JSON.stringify({ at: new Date().toISOString(), ...entry }) + '\n');
|
|
136
|
+
} finally {
|
|
137
|
+
await handle.close();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function clean(source: string, target: string, branch: string, head: string) {
|
|
141
|
+
if (!(await adapter.inspect(source, target, branch)))
|
|
142
|
+
fail('outcome_unknown', 'Worktree creation needs owner reconciliation', 1005);
|
|
143
|
+
// Reconciliation never resets files: a partially materialized or subsequently edited checkout is retained.
|
|
144
|
+
if ((await adapter.facts(target)).head !== head) fail('outcome_unknown', 'Prepared worktree HEAD changed', 1005);
|
|
145
|
+
await adapter.assertClean(target);
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
async describe(w: WorkspaceRecord) {
|
|
149
|
+
const { worktree, ...row } = w;
|
|
150
|
+
let branch: string | null = null;
|
|
151
|
+
try {
|
|
152
|
+
// The registry keeps the directory as given (it may pass through a symlink, e.g. /var on
|
|
153
|
+
// macOS) and its realpath as canonical; read the checkout only where that identity still
|
|
154
|
+
// holds. A record with no canonical identity is read only at its own, already canonical, path.
|
|
155
|
+
const canonical = await realpath(w.directory);
|
|
156
|
+
if (canonical === (w.canonical ?? w.directory))
|
|
157
|
+
branch = (await user_worktree.repositoryIdentity(canonical)).branch;
|
|
158
|
+
} catch {}
|
|
159
|
+
return { ...row, branch, ...(worktree ? { managedWorktree: true } : {}) };
|
|
160
|
+
},
|
|
161
|
+
/** What adopting this legacy managed worktree would certify (t-c1ba); it changes nothing. */
|
|
162
|
+
async adoption(workspaceId: string, context: Context = {}) {
|
|
163
|
+
owner(context);
|
|
164
|
+
return adoptionFacts(await registry.snapshot(), workspaceId);
|
|
165
|
+
},
|
|
166
|
+
/**
|
|
167
|
+
* Certifies a managed worktree that predates birth certification, once the owner confirmed the
|
|
168
|
+
* facts `adoption` showed. The facts are proven again under the runtime's removal guard, which
|
|
169
|
+
* also refuses any checkout an assignment, claim, lease or session still owns. Removal stays a
|
|
170
|
+
* separate request with all of its own checks.
|
|
171
|
+
*/
|
|
172
|
+
async adopt(p: { workspaceId: string; confirm: AdoptionFacts }, context: Context = {}) {
|
|
173
|
+
owner(context);
|
|
174
|
+
if (!adoptWorkspace) return fail('guard_unavailable', 'Runtime cannot prove safe adoption', 1005);
|
|
175
|
+
const confirmed = (facts: AdoptionFacts) =>
|
|
176
|
+
!!p.confirm &&
|
|
177
|
+
typeof p.confirm === 'object' &&
|
|
178
|
+
Object.keys(p.confirm).length === Object.keys(facts).length &&
|
|
179
|
+
(Object.keys(facts) as (keyof AdoptionFacts)[]).every((k) => p.confirm[k] === facts[k]);
|
|
180
|
+
const facts = await adoptionFacts(await registry.snapshot(), p.workspaceId);
|
|
181
|
+
if (!confirmed(facts)) fail('confirmation_mismatch', 'The workspace differs from what was confirmed; review it and confirm again', 1003);
|
|
182
|
+
// Logged before certification: no adoption happens unrecorded.
|
|
183
|
+
await audit({ event: 'adoption.requested', actor: 'owner', ...facts });
|
|
184
|
+
try {
|
|
185
|
+
await adoptWorkspace(facts.directory, async () => {
|
|
186
|
+
if (!confirmed(await adoptionFacts(await registry.snapshot(), p.workspaceId)))
|
|
187
|
+
fail('confirmation_mismatch', 'The workspace changed after it was confirmed; review it and confirm again', 1003);
|
|
188
|
+
});
|
|
189
|
+
} catch (error: any) {
|
|
190
|
+
await audit({ event: 'adoption.refused', actor: 'owner', workspaceId: facts.workspaceId, reason: error?.data?.reason ?? 'failed', error: error?.message ?? String(error) }).catch(() => {});
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
await audit({ event: 'adoption.certified', actor: 'owner', workspaceId: facts.workspaceId, directory: facts.directory });
|
|
194
|
+
return { adopted: facts };
|
|
195
|
+
},
|
|
196
|
+
async assertAvailable(directory: string) {
|
|
197
|
+
const r = await registry.snapshot();
|
|
198
|
+
const canonical = await realpath(directory).catch(() => path.resolve(directory));
|
|
199
|
+
if (
|
|
200
|
+
Object.values(r.worktreeJournal ?? {}).some(
|
|
201
|
+
(j) => canonical === j.intent.directory || canonical.startsWith(j.intent.directory + path.sep)
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
fail('reconciliation_required', 'Workspace is pending reconciliation');
|
|
205
|
+
},
|
|
206
|
+
async grants(context: Context = {}) {
|
|
207
|
+
const r = await registry.snapshot();
|
|
208
|
+
const mappings: Mapping[] = [];
|
|
209
|
+
for (const m of await worktreeMappings(home)) {
|
|
210
|
+
try {
|
|
211
|
+
await approved(context, m.source, m.id, false);
|
|
212
|
+
mappings.push(m);
|
|
213
|
+
} catch {}
|
|
214
|
+
}
|
|
215
|
+
const workspaces: WorkspaceRecord[] = [];
|
|
216
|
+
for (const w of r.workspaces) {
|
|
217
|
+
const m = w.worktree;
|
|
218
|
+
if (
|
|
219
|
+
!m ||
|
|
220
|
+
m.principalId !== (context.principalId ?? 'owner') ||
|
|
221
|
+
m.grantEpoch !== (context.principalEpoch ?? 'owner') ||
|
|
222
|
+
!mappings.some((a) => a.id === m.mappingId && a.source === m.source && a.commonDir === m.commonDir)
|
|
223
|
+
)
|
|
224
|
+
continue;
|
|
225
|
+
const expected = path.join(mappings.find((a) => a.id === m.mappingId)!.parent, w.id);
|
|
226
|
+
if (w.directory !== expected || w.canonical !== expected) continue;
|
|
227
|
+
const pending = Object.values(r.worktreeJournal ?? {}).find((j) => j.intent.id === w.id);
|
|
228
|
+
if (!m.removedAt && !pending) {
|
|
229
|
+
try {
|
|
230
|
+
const identity = await user_worktree.repositoryIdentity(w.directory);
|
|
231
|
+
if (
|
|
232
|
+
identity.gitDir !== m.gitDir ||
|
|
233
|
+
identity.commonDir !== m.commonDir ||
|
|
234
|
+
identity.branch !== m.branch ||
|
|
235
|
+
(await lstat(path.join(identity.gitDir, 'locked')).catch((e: any) => {
|
|
236
|
+
if (e.code === 'ENOENT') return undefined;
|
|
237
|
+
throw e;
|
|
238
|
+
}))
|
|
239
|
+
)
|
|
240
|
+
continue;
|
|
241
|
+
} catch {
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
workspaces.push(
|
|
246
|
+
Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === w.id)
|
|
247
|
+
? { ...w, archivedAt: w.archivedAt ?? 'pending' }
|
|
248
|
+
: w
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
return { mappings: mappings.map((m) => ({ id: m.id, source: m.source })), workspaces };
|
|
252
|
+
},
|
|
253
|
+
async mutate(method: 'create' | 'remove', p: any, context: Context = {}) {
|
|
254
|
+
const actor = context.principalId ?? 'owner';
|
|
255
|
+
const r = await registry.snapshot();
|
|
256
|
+
const w = workspace(r, p.workspaceId);
|
|
257
|
+
const origin = method === 'create' ? await sourceOf(r, w.id) : w;
|
|
258
|
+
const meta = w.worktree;
|
|
259
|
+
if (
|
|
260
|
+
method === 'remove' &&
|
|
261
|
+
(!meta ||
|
|
262
|
+
meta.kind !== 'user' ||
|
|
263
|
+
meta.principalId !== actor ||
|
|
264
|
+
meta.grantEpoch !== (context.principalEpoch ?? 'owner'))
|
|
265
|
+
)
|
|
266
|
+
fail('not_managed', 'Only your managed user worktrees can be removed', 1003);
|
|
267
|
+
const source = method === 'create' ? await realpath(origin.directory) : meta!.source;
|
|
268
|
+
const mappingId = method === 'create' ? p.mappingId : meta!.mappingId;
|
|
269
|
+
const mapping = await approved(context, source, mappingId);
|
|
270
|
+
return registry.nativeMutation(
|
|
271
|
+
'workspace.worktree.' + method,
|
|
272
|
+
{ workspaceId: p.workspaceId, ...(method === 'create' ? { mappingId: p.mappingId } : {}) },
|
|
273
|
+
{ actor: actor + ':' + (context.principalEpoch ?? 'owner'), requestId: p.requestId, ifRevision: p.ifRevision },
|
|
274
|
+
async (draft) => {
|
|
275
|
+
if (method === 'create') {
|
|
276
|
+
const id = 'wks_' + randomBytes(8).toString('hex');
|
|
277
|
+
const facts = await adapter.facts(source);
|
|
278
|
+
return {
|
|
279
|
+
method,
|
|
280
|
+
id,
|
|
281
|
+
requestId: p.requestId,
|
|
282
|
+
ifRevision: p.ifRevision,
|
|
283
|
+
directory: path.join(mapping.parent, id),
|
|
284
|
+
projectId: origin.projectId,
|
|
285
|
+
sourceWorkspaceId: origin.id,
|
|
286
|
+
source,
|
|
287
|
+
commonDir: mapping.commonDir,
|
|
288
|
+
mappingId,
|
|
289
|
+
principalId: actor,
|
|
290
|
+
grantEpoch: context.principalEpoch ?? 'owner',
|
|
291
|
+
branch: `alp/workspace/${id}`,
|
|
292
|
+
head: facts.head
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
if (w.directory !== path.join(mapping.parent, w.id) || w.canonical !== w.directory)
|
|
296
|
+
fail('identity_changed', 'Managed worktree path changed', 1003);
|
|
297
|
+
// Guard before journaling so ordinary safety refusals do not strand a prepared intent.
|
|
298
|
+
await guard(w.directory, async () => {
|
|
299
|
+
if (Object.values(draft.sessions).includes(w.id))
|
|
300
|
+
fail(
|
|
301
|
+
'workspace_history',
|
|
302
|
+
'Saved sessions reference this checkout; retain its files. This operation does not delete history.'
|
|
303
|
+
);
|
|
304
|
+
try {
|
|
305
|
+
await adapter.assertClean(w.directory);
|
|
306
|
+
} catch {
|
|
307
|
+
fail(
|
|
308
|
+
'workspace_dirty',
|
|
309
|
+
'Worktree has dirty, ignored, hidden-index or submodule data; preserve it before removal'
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
return { method, id: w.id, directory: w.directory, ...meta };
|
|
314
|
+
},
|
|
315
|
+
async (intent, draft) => {
|
|
316
|
+
await approved(context, intent.source, intent.mappingId);
|
|
317
|
+
if (
|
|
318
|
+
intent.principalId !== actor ||
|
|
319
|
+
intent.grantEpoch !== (context.principalEpoch ?? 'owner') ||
|
|
320
|
+
intent.directory !== path.join(mapping.parent, intent.id) ||
|
|
321
|
+
intent.commonDir !== mapping.commonDir
|
|
322
|
+
)
|
|
323
|
+
fail('identity_changed', 'Worktree journal identity changed', 1003);
|
|
324
|
+
if (method === 'create') {
|
|
325
|
+
const row = await adapter.inspect(intent.source, intent.directory, intent.branch);
|
|
326
|
+
if (!row) await adapter.create(intent.source, mapping.parent, intent.id, intent.branch, intent.head);
|
|
327
|
+
await clean(intent.source, intent.directory, intent.branch, intent.head);
|
|
328
|
+
await register(intent.directory);
|
|
329
|
+
const created: WorkspaceRecord = {
|
|
330
|
+
id: intent.id,
|
|
331
|
+
projectId: intent.projectId,
|
|
332
|
+
directory: intent.directory,
|
|
333
|
+
canonical: intent.directory,
|
|
334
|
+
labels: [],
|
|
335
|
+
createdAt: new Date().toISOString(),
|
|
336
|
+
worktree: {
|
|
337
|
+
kind: 'user',
|
|
338
|
+
sourceWorkspaceId: intent.sourceWorkspaceId,
|
|
339
|
+
source: intent.source,
|
|
340
|
+
commonDir: intent.commonDir,
|
|
341
|
+
gitDir: (await user_worktree.repositoryIdentity(intent.directory)).gitDir,
|
|
342
|
+
requestId: intent.requestId,
|
|
343
|
+
ifRevision: intent.ifRevision,
|
|
344
|
+
mappingId: intent.mappingId,
|
|
345
|
+
principalId: actor,
|
|
346
|
+
grantEpoch: context.principalEpoch ?? 'owner',
|
|
347
|
+
branch: intent.branch,
|
|
348
|
+
head: intent.head
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
draft.workspaces.push(created);
|
|
352
|
+
return { workspace: created };
|
|
353
|
+
}
|
|
354
|
+
const finish = async () => {
|
|
355
|
+
if (Object.values(draft.sessions).includes(intent.id))
|
|
356
|
+
fail(
|
|
357
|
+
'workspace_history',
|
|
358
|
+
'Saved sessions reference this checkout; retain its files. This operation does not delete history.'
|
|
359
|
+
);
|
|
360
|
+
const present = await lstat(intent.directory).catch((e: any) => {
|
|
361
|
+
if (e.code === 'ENOENT') return undefined;
|
|
362
|
+
throw e;
|
|
363
|
+
});
|
|
364
|
+
if (present) await adapter.remove(intent.source, intent.directory, intent.branch);
|
|
365
|
+
else if (await adapter.inspect(intent.source, intent.directory, intent.branch))
|
|
366
|
+
fail('outcome_unknown', 'Worktree removal needs reconciliation', 1005);
|
|
367
|
+
const removed = workspace(draft, intent.id);
|
|
368
|
+
removed.archivedAt = new Date().toISOString();
|
|
369
|
+
removed.pinnedAt = null;
|
|
370
|
+
removed.worktree!.removedAt = removed.archivedAt;
|
|
371
|
+
return { workspace: removed, filesRemoved: true, branchRetained: true };
|
|
372
|
+
};
|
|
373
|
+
const present = await lstat(intent.directory).catch((e: any) => {
|
|
374
|
+
if (e.code === 'ENOENT') return undefined;
|
|
375
|
+
throw e;
|
|
376
|
+
});
|
|
377
|
+
return present ? guard(intent.directory, finish) : finish();
|
|
378
|
+
}
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
}
|