@anhlp/alp-core 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.
Files changed (44) hide show
  1. package/dist/backup.js +106 -4
  2. package/dist/bridges.d.ts +27 -0
  3. package/dist/bridges.js +97 -0
  4. package/dist/gate-ledger.d.ts +30 -0
  5. package/dist/gate-ledger.js +99 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +2 -0
  8. package/dist/migrations.js +1 -1
  9. package/dist/models.d.ts +39 -0
  10. package/dist/models.js +51 -1
  11. package/dist/packaged.d.ts +96 -0
  12. package/dist/packaged.js +198 -0
  13. package/dist/providers.d.ts +3 -1
  14. package/dist/providers.js +6 -1
  15. package/dist/task-rows.d.ts +5 -0
  16. package/dist/task-rows.js +1 -1
  17. package/dist/tasks.d.ts +22 -4
  18. package/dist/tasks.js +97 -9
  19. package/dist/template-path.d.ts +2 -2
  20. package/dist/template-path.js +5 -0
  21. package/dist/types.d.ts +1 -0
  22. package/dist/user-worktree.d.ts +29 -0
  23. package/dist/user-worktree.js +242 -0
  24. package/dist/validation.js +19 -4
  25. package/package.json +18 -2
  26. package/src/backup.js +106 -5
  27. package/src/bridges.js +113 -0
  28. package/src/gate-ledger.js +125 -0
  29. package/src/index.js +1 -0
  30. package/src/migrations.js +1 -1
  31. package/src/models.js +63 -1
  32. package/src/packaged.js +255 -0
  33. package/src/providers.js +4 -2
  34. package/src/task-rows.js +1 -1
  35. package/src/tasks.d.ts +22 -4
  36. package/src/tasks.js +126 -10
  37. package/src/template-path.js +6 -1
  38. package/src/types.d.ts +1 -0
  39. package/src/user-worktree.js +259 -0
  40. package/src/validation.js +22 -4
  41. package/templates/agents/main/AGENT.md +4 -0
  42. package/templates/role-skills.json +1 -1
  43. package/templates/skills/compact/SKILL.md +34 -0
  44. package/templates/skills/curate/SKILL.md +35 -0
@@ -0,0 +1,29 @@
1
+ export function repositoryIdentity(directory: any): Promise<{
2
+ gitDir: string;
3
+ commonDir: string;
4
+ branch: string | null;
5
+ }>;
6
+ /** User workspace primitives. Assignment cleanup's force/rm semantics must never be used here. */
7
+ export function userWorktreeGit({ executable, timeoutMs, maxBytes }?: {
8
+ executable?: string | undefined;
9
+ timeoutMs?: number | undefined;
10
+ maxBytes?: number | undefined;
11
+ }): {
12
+ facts: (source: any) => Promise<{
13
+ commonDir: string;
14
+ gitDir: string;
15
+ head: any;
16
+ branch: any;
17
+ }>;
18
+ inspect: (source: any, target: any, branch: any) => Promise<any>;
19
+ assertClean: (target: any) => Promise<void>;
20
+ checkoutFacts(directory: any): Promise<{
21
+ isGit: true;
22
+ repoRoot: any;
23
+ currentBranch: any;
24
+ remoteUrl: any;
25
+ isDirty: boolean;
26
+ }>;
27
+ create(source: any, parent: any, name: any, branch: any, head: any): Promise<string>;
28
+ remove(source: any, target: any, branch: any): Promise<void>;
29
+ };
@@ -0,0 +1,242 @@
1
+ // packages/core/src/user-worktree.js
2
+ import { spawn } from "node:child_process";
3
+ import { lstat, realpath, open } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { constants } from "node:fs";
6
+ async function control(file) {
7
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
8
+ try {
9
+ const info = await handle.stat();
10
+ if (!info.isFile() || info.nlink !== 1 || info.size > 4096) throw new Error("Invalid Git administrative file");
11
+ const bytes = Buffer.alloc(4097);
12
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
13
+ if (bytesRead > 4096) throw new Error("Git administrative file exceeds limit");
14
+ return bytes.subarray(0, bytesRead).toString("utf8").replace(/\r?\n$/, "");
15
+ } finally {
16
+ await handle.close();
17
+ }
18
+ }
19
+ async function repositoryIdentity(directory) {
20
+ if (await realpath(directory) !== directory) throw new Error("Repository root is not canonical");
21
+ const entry = path.join(directory, ".git");
22
+ const info = await lstat(entry);
23
+ let gitDir;
24
+ if (info.isDirectory()) gitDir = await realpath(entry);
25
+ else {
26
+ const value = await control(entry);
27
+ if (!value.startsWith("gitdir: ") || /[\r\n\0]/.test(value)) throw new Error("Invalid Git control link");
28
+ gitDir = await realpath(path.resolve(directory, value.slice(8)));
29
+ }
30
+ const commonEntry = path.join(gitDir, "commondir");
31
+ const hasCommon = await lstat(commonEntry).catch((error) => {
32
+ if (error.code === "ENOENT") return void 0;
33
+ throw error;
34
+ });
35
+ const commonDir = hasCommon ? await realpath(path.resolve(gitDir, await control(commonEntry))) : gitDir;
36
+ if (gitDir !== commonDir) {
37
+ if (path.dirname(gitDir) !== path.join(commonDir, "worktrees") || path.resolve(gitDir, await control(path.join(gitDir, "gitdir"))) !== entry)
38
+ throw new Error("Git worktree backlink changed");
39
+ }
40
+ const head = await control(path.join(gitDir, "HEAD"));
41
+ const branch = head.startsWith("ref: refs/heads/") ? head.slice(16) : null;
42
+ if (branch !== null && (!branch || /[\r\n\0]/.test(branch))) throw new Error("Invalid branch reference");
43
+ return { gitDir, commonDir, branch };
44
+ }
45
+ function userWorktreeGit({ executable = "/usr/bin/git", timeoutMs = 15e3, maxBytes = 2 * 1024 * 1024 } = {}) {
46
+ if (process.platform === "win32") throw new Error("User worktree operations are unavailable on this host");
47
+ if (!path.isAbsolute(executable)) throw new Error("Git executable must be host configured and absolute");
48
+ const disabled = [
49
+ "-c",
50
+ "core.hooksPath=/dev/null",
51
+ "-c",
52
+ "core.fsmonitor=false",
53
+ "-c",
54
+ "core.untrackedCache=false",
55
+ "-c",
56
+ "core.pager=cat",
57
+ "-c",
58
+ "maintenance.auto=false",
59
+ "-c",
60
+ "gc.auto=0",
61
+ "-c",
62
+ "protocol.allow=never",
63
+ "-c",
64
+ "submodule.recurse=false"
65
+ ];
66
+ const env = {
67
+ PATH: "/usr/bin:/bin",
68
+ GIT_CONFIG_NOSYSTEM: "1",
69
+ GIT_CONFIG_GLOBAL: "/dev/null",
70
+ GIT_TERMINAL_PROMPT: "0",
71
+ GIT_OPTIONAL_LOCKS: "0",
72
+ LANG: "C",
73
+ LC_ALL: "C"
74
+ };
75
+ async function raw(cwd, args, extra = []) {
76
+ return new Promise((resolve, reject) => {
77
+ const child = spawn(executable, [...disabled, ...extra, ...args], {
78
+ cwd,
79
+ env,
80
+ stdio: ["ignore", "pipe", "pipe"],
81
+ windowsHide: true,
82
+ detached: true
83
+ });
84
+ let size = 0;
85
+ let overflow = false;
86
+ const stdout = [];
87
+ const stderr = [];
88
+ const kill = () => {
89
+ try {
90
+ process.kill(-child.pid, "SIGKILL");
91
+ } catch {
92
+ child.kill("SIGKILL");
93
+ }
94
+ };
95
+ const timer = setTimeout(() => {
96
+ overflow = true;
97
+ kill();
98
+ }, timeoutMs);
99
+ const collect = (sink) => (chunk) => {
100
+ size += chunk.length;
101
+ if (size > maxBytes) {
102
+ overflow = true;
103
+ kill();
104
+ } else sink.push(chunk);
105
+ };
106
+ child.stdout.on("data", collect(stdout));
107
+ child.stderr.on("data", collect(stderr));
108
+ child.once("error", (error) => {
109
+ clearTimeout(timer);
110
+ reject(error);
111
+ });
112
+ child.once("close", (code) => {
113
+ clearTimeout(timer);
114
+ if (overflow) reject(new Error("Git operation exceeded its host limit"));
115
+ else
116
+ resolve({
117
+ code,
118
+ stdout: Buffer.concat(stdout).toString("utf8"),
119
+ stderr: Buffer.concat(stderr).toString("utf8")
120
+ });
121
+ });
122
+ });
123
+ }
124
+ async function filterOverrides(cwd) {
125
+ const filters = await raw(cwd, [
126
+ "config",
127
+ "--null",
128
+ "--name-only",
129
+ "--get-regexp",
130
+ "^filter\\..*\\.(smudge|clean|process|required)$"
131
+ ]);
132
+ if (filters.code !== 0 && filters.code !== 1) throw new Error("Cannot inspect repository filters");
133
+ const neutral = filters.stdout.split("\0").filter(Boolean).flatMap((key) => ["-c", `${key}=${key.endsWith(".required") ? "false" : ""}`]);
134
+ return neutral;
135
+ }
136
+ async function run(cwd, args, extra = []) {
137
+ return raw(cwd, args, [...await filterOverrides(cwd), ...extra]);
138
+ }
139
+ async function checked(cwd, args, extra = []) {
140
+ const result = await run(cwd, args, extra);
141
+ if (result.code !== 0) throw new Error("Git workspace operation refused");
142
+ return result.stdout.trim();
143
+ }
144
+ async function directory(value) {
145
+ const canonical = await realpath(value);
146
+ if (canonical !== value || !(await lstat(value)).isDirectory())
147
+ throw new Error("Workspace paths must be canonical directories");
148
+ return canonical;
149
+ }
150
+ async function facts(source) {
151
+ await directory(source);
152
+ const top = await checked(source, ["rev-parse", "--show-toplevel"]);
153
+ if (await realpath(top) !== source) throw new Error("Workspace must be a repository top level");
154
+ const commonDir = await realpath(
155
+ await checked(source, ["rev-parse", "--path-format=absolute", "--git-common-dir"])
156
+ );
157
+ const identity = await repositoryIdentity(source);
158
+ if (identity.commonDir !== commonDir) throw new Error("Repository identity changed");
159
+ const head = await checked(source, ["rev-parse", "--verify", "HEAD"]);
160
+ const branch = await run(source, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
161
+ return { commonDir, gitDir: identity.gitDir, head, branch: branch.code === 0 ? branch.stdout.trim() : null };
162
+ }
163
+ async function list(source) {
164
+ const result = await checked(source, ["worktree", "list", "--porcelain", "-z"]);
165
+ return result.split("\0\0").filter(Boolean).map(
166
+ (block) => Object.fromEntries(
167
+ block.split("\0").filter(Boolean).map((line) => {
168
+ const i = line.indexOf(" ");
169
+ return i < 0 ? [line, true] : [line.slice(0, i), line.slice(i + 1)];
170
+ })
171
+ )
172
+ );
173
+ }
174
+ async function inspect(source, target, branch) {
175
+ const row = (await list(source)).find((row2) => row2.worktree === target);
176
+ if (!row) return void 0;
177
+ await directory(target);
178
+ if (row.branch !== `refs/heads/${branch}` || row.locked || row.prunable)
179
+ throw new Error("Managed worktree identity changed");
180
+ const origin = await facts(source);
181
+ const destination = await facts(target);
182
+ if (origin.commonDir !== destination.commonDir) throw new Error("Managed worktree repository changed");
183
+ return row;
184
+ }
185
+ async function assertClean(target) {
186
+ const flags = await checked(target, ["ls-files", "-v", "-z"]);
187
+ if (flags.split("\0").some((row) => row && (row[0] === "S" || /[a-z]/.test(row[0]))))
188
+ throw new Error("Worktree has hidden index state");
189
+ if ((await checked(target, ["ls-files", "--stage", "-z"])).split("\0").some((row) => row.startsWith("160000 ")))
190
+ throw new Error("Worktree has submodules");
191
+ if ((await checked(target, ["status", "--porcelain=v1", "--untracked-files=all", "--ignored"])).length)
192
+ throw new Error("Worktree contains uncommitted or ignored files");
193
+ }
194
+ return {
195
+ facts,
196
+ inspect,
197
+ assertClean,
198
+ async checkoutFacts(directory2) {
199
+ const canonical = await realpath(directory2);
200
+ const repoRoot = await checked(canonical, ["rev-parse", "--show-toplevel"]);
201
+ const branch = await run(canonical, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
202
+ const remote = await run(canonical, ["config", "--get", "remote.origin.url"]);
203
+ const status = await checked(canonical, ["status", "--porcelain=v1", "--untracked-files=all"]);
204
+ return {
205
+ isGit: (
206
+ /** @type {const} */
207
+ true
208
+ ),
209
+ repoRoot,
210
+ currentBranch: branch.code === 0 ? branch.stdout.trim() : null,
211
+ remoteUrl: remote.code === 0 ? remote.stdout.trim() || null : null,
212
+ isDirty: !!status
213
+ };
214
+ },
215
+ async create(source, parent, name, branch, head) {
216
+ await directory(parent);
217
+ if (!/^wks_[0-9a-f]{16}$/.test(name) || branch !== `alp/workspace/${name}` || !/^[0-9a-f]{40,64}$/.test(head))
218
+ throw new Error("Invalid generated worktree identity");
219
+ const target = path.join(parent, name);
220
+ if (await lstat(target).catch((error) => {
221
+ if (error.code === "ENOENT") return void 0;
222
+ throw error;
223
+ }))
224
+ throw new Error("Worktree destination already exists");
225
+ await checked(source, ["worktree", "add", "--quiet", "--no-checkout", "-b", branch, target, head]);
226
+ await checked(target, ["reset", "--hard", "--no-recurse-submodules", head]);
227
+ if (!await inspect(source, target, branch)) throw new Error("Worktree creation needs reconciliation");
228
+ return target;
229
+ },
230
+ async remove(source, target, branch) {
231
+ if (!await inspect(source, target, branch)) throw new Error("Managed worktree is missing");
232
+ await assertClean(target);
233
+ await checked(source, ["worktree", "remove", target], await filterOverrides(target));
234
+ if ((await list(source)).some((row) => row.worktree === target))
235
+ throw new Error("Worktree removal needs reconciliation");
236
+ }
237
+ };
238
+ }
239
+ export {
240
+ repositoryIdentity,
241
+ userWorktreeGit
242
+ };
@@ -11,8 +11,8 @@ function requireValue(condition, code, source, message) {
11
11
  if (!condition) throw new AlpError(code, `${source}: ${message}`);
12
12
  }
13
13
  var EFFORTS = ["none", "off", "low", "medium", "high", "xhigh", "max", "ultra", "ultracode"];
14
- var PROJECT_SETTINGS = ["$schema", "defaultAgent", "workflow", "runtime", "permissions", "verify", "delegation", "team", "profile", "templateDefaults"];
15
- var USER_SETTINGS = ["$schema", "language", "permissions", "limits", "recovery", "web"];
14
+ var PROJECT_SETTINGS = ["$schema", "defaultAgent", "workflow", "runtime", "permissions", "verify", "delegation", "team", "profile", "templateDefaults", "compact", "curate"];
15
+ var USER_SETTINGS = ["$schema", "language", "permissions", "limits", "recovery", "web", "curate"];
16
16
  var RETIRED_SETTINGS = { project: {}, user: {} };
17
17
  function distance(a, b) {
18
18
  const row = Array.from({ length: b.length + 1 }, (_, index) => index);
@@ -45,11 +45,18 @@ var unknownMessage = (unknown, known) => `unknown setting '${unknown.key}'${unkn
45
45
  function settingsWarnings(settings, scope) {
46
46
  return settingsKeys(settings, scope === "user" ? USER_SETTINGS : PROJECT_SETTINGS, RETIRED_SETTINGS[scope]).retired.map(({ key, instead }) => `setting '${key}' is no longer read; ${instead}`);
47
47
  }
48
+ function checkCurate(settings, check) {
49
+ if (settings.curate === void 0) return;
50
+ check(object(settings.curate), "curate must be an object");
51
+ check(Object.keys(settings.curate).every((key) => key === "monthly"), "unsupported curate field; use monthly");
52
+ if (settings.curate.monthly !== void 0) check(typeof settings.curate.monthly === "boolean", "curate.monthly must be true or false");
53
+ }
48
54
  function validateSettings(settings, source) {
49
55
  const check = (ok, message) => requireValue(ok, "INVALID_SETTINGS", source, message);
50
56
  check(object(settings), "expected an object");
51
57
  const { unknown } = settingsKeys(settings, PROJECT_SETTINGS, RETIRED_SETTINGS.project);
52
58
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], PROJECT_SETTINGS) : "");
59
+ checkCurate(settings, check);
53
60
  if (settings.defaultAgent !== void 0) check(nonempty(settings.defaultAgent), "defaultAgent must be a nonempty string");
54
61
  if (settings.workflow !== void 0) {
55
62
  check(object(settings.workflow), "workflow must be an object");
@@ -58,6 +65,12 @@ function validateSettings(settings, source) {
58
65
  if (settings.workflow.maxPeers !== void 0) check(Number.isSafeInteger(settings.workflow.maxPeers) && settings.workflow.maxPeers > 0, "workflow.maxPeers must be a positive integer");
59
66
  if (settings.workflow.supervisor !== void 0) check(typeof settings.workflow.supervisor === "boolean", "workflow.supervisor must be true or false");
60
67
  }
68
+ if (settings.compact !== void 0) {
69
+ check(object(settings.compact), "compact must be an object");
70
+ check(Object.keys(settings.compact).every((key) => ["auto", "threshold"].includes(key)), "compact takes auto and threshold");
71
+ if (settings.compact.auto !== void 0) check(typeof settings.compact.auto === "boolean", "compact.auto must be true or false");
72
+ if (settings.compact.threshold !== void 0) check(typeof settings.compact.threshold === "number" && settings.compact.threshold > 0 && settings.compact.threshold < 1, "compact.threshold must be a number between 0 and 1");
73
+ }
61
74
  if (settings.templateDefaults !== void 0) {
62
75
  check(object(settings.templateDefaults), "templateDefaults must map teams to profile fingerprints");
63
76
  for (const [team, agents] of Object.entries(settings.templateDefaults)) {
@@ -138,6 +151,7 @@ function validateUserSettings(settings, source) {
138
151
  check(object(settings), "expected an object");
139
152
  const { unknown } = settingsKeys(settings, USER_SETTINGS, RETIRED_SETTINGS.user);
140
153
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], USER_SETTINGS) : "");
154
+ checkCurate(settings, check);
141
155
  for (const key of ["limits", "recovery"]) {
142
156
  if (settings[key] === void 0) continue;
143
157
  check(object(settings[key]), `${key} must be an object`);
@@ -147,8 +161,9 @@ function validateUserSettings(settings, source) {
147
161
  }
148
162
  if (settings.web !== void 0) {
149
163
  check(object(settings.web), "web must be an object");
150
- const extra = Object.keys(settings.web).find((field) => !["enabled", "port", "relay"].includes(field));
151
- check(!extra, `unsupported web field '${extra}'; use enabled, port or relay`);
164
+ const extra = Object.keys(settings.web).find((field) => !["enabled", "port", "relay", "permissions"].includes(field));
165
+ check(!extra, `unsupported web field '${extra}'; use enabled, port, relay or permissions`);
166
+ if (settings.web.permissions !== void 0) check(Array.isArray(settings.web.permissions) && settings.web.permissions.every((entry) => typeof entry === "string" && /^[a-z][a-z.]*$/.test(entry)), "web.permissions must be a list of permission names, such as files.read");
152
167
  const relay = settings.web.relay;
153
168
  if (relay !== void 0) {
154
169
  check(object(relay), "web.relay must be an object");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-core",
3
- "version": "0.0.1-beta.3",
3
+ "version": "0.0.1-beta.5",
4
4
  "type": "module",
5
5
  "description": "ALP core module",
6
6
  "files": [
@@ -278,13 +278,29 @@
278
278
  },
279
279
  "types": "./dist/template-path.d.ts",
280
280
  "default": "./src/template-path.js"
281
+ },
282
+ "./bridges": {
283
+ "alp-source": {
284
+ "types": "./src/bridges.js",
285
+ "default": "./src/bridges.js"
286
+ },
287
+ "types": "./dist/bridges.d.ts",
288
+ "default": "./src/bridges.js"
289
+ },
290
+ "./packaged": {
291
+ "alp-source": {
292
+ "types": "./src/packaged.js",
293
+ "default": "./src/packaged.js"
294
+ },
295
+ "types": "./dist/packaged.d.ts",
296
+ "default": "./src/packaged.js"
281
297
  }
282
298
  },
283
299
  "engines": {
284
300
  "node": ">=22.12"
285
301
  },
286
302
  "dependencies": {
287
- "@anhlp/alp-protocol": "0.0.1-beta.3"
303
+ "@anhlp/alp-protocol": "0.0.1-beta.5"
288
304
  },
289
305
  "scripts": {
290
306
  "build": "node ../../scripts/build-workspace.mjs core",
package/src/backup.js CHANGED
@@ -34,7 +34,12 @@ export const BACKUP_FORMAT = 1;
34
34
  export const BACKUP_EXTENSION = '.alpbackup';
35
35
 
36
36
  /** alpd's state: sessions, their timelines and receipts, and the runtime's durable state. */
37
- export const STATE_UNITS = ['state/schema.json', 'state/sessions', 'state/timeline', 'state/receipts', 'state/recall.json', 'state/pause.json', 'state/trust.json', 'state/web-workspaces.json'];
37
+ const RESULT_LEDGER = 'state/assignment-results.json';
38
+ const RESULT_MARKER = `${RESULT_LEDGER}.initialized`;
39
+ const DESTINATIONS = 'worktree-destinations.json';
40
+ // Evidence only: the daemon never loads mapping authority from this path.
41
+ const QUARANTINED_DESTINATIONS = 'state/worktree-destinations.quarantined.json';
42
+ export const STATE_UNITS = [RESULT_LEDGER, RESULT_MARKER, 'state/assignment-archive', 'state/schema.json', 'state/sessions', 'state/timeline', 'state/receipts', 'state/recall.json', 'state/pause.json', 'state/trust.json', 'state/web-workspaces.json'];
38
43
  /**
39
44
  * Live work (running assignments alpd continues after a restart) and the journal of an
40
45
  * unfinished migration are never backed up: a restore of the state removes them, so restored
@@ -43,7 +48,7 @@ export const STATE_UNITS = ['state/schema.json', 'state/sessions', 'state/timeli
43
48
  export const CLEARED_UNITS = ['state/live.json', 'state/migration.json'];
44
49
  /** Everything a backup of $ALP_HOME holds: the state, the user's settings and library, boards and assignment logs. */
45
50
  export const HOME_UNITS = [
46
- ...STATE_UNITS,
51
+ ...STATE_UNITS, DESTINATIONS,
47
52
  'settings.json', 'library.json', 'role-skills.json', 'lessons.md',
48
53
  'agents', 'skills', 'teams', 'hooks', 'mcp', 'providers', 'formulas',
49
54
  'boards', 'runs',
@@ -396,6 +401,100 @@ async function holdTaskLocks(roots, work) {
396
401
  finally { clearInterval(touch); }
397
402
  }
398
403
 
404
+ /**
405
+ * Restore ownership evidence, never checkout birth certification or host authority.
406
+ * Paths in an archive cannot establish the identity of an old or moved checkout. Keep
407
+ * every retained owner (including work after the snapshot), but require audited adoption
408
+ * for old targets. The host must explicitly approve mappings again; archived bytes are
409
+ * kept privately as evidence only. All replacements join the ordinary rollback journal.
410
+ */
411
+ async function prepareWorkspaceRestore(home, root, units, warnings) {
412
+ const relevant = [RESULT_LEDGER, RESULT_MARKER, DESTINATIONS, 'state/sessions', 'state/web-workspaces.json'];
413
+ // Only the transform may stage quarantine; archive-declared copies are never activated.
414
+ const restorable = units.filter(unit => unit.path !== QUARANTINED_DESTINATIONS);
415
+ if (!units.some(unit => relevant.includes(unit.path))) return restorable;
416
+ for (const base of [home, root]) {
417
+ const info = await lstat(path.join(base, 'state')).catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
418
+ if (info && !info.isDirectory()) throw invalid('workspace state must be a real directory');
419
+ }
420
+ const result = restorable.filter(unit => ![RESULT_LEDGER, RESULT_MARKER, DESTINATIONS, 'state/web-workspaces.json'].includes(unit.path));
421
+ async function regular(base, unit, declared) {
422
+ if (declared && declared.kind === 'absent') return undefined;
423
+ const file = path.join(base, unit);
424
+ const info = await lstat(file).catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
425
+ if (!info) {
426
+ if (declared) throw invalid(`${unit} is declared but missing from the backup`);
427
+ return undefined;
428
+ }
429
+ if (!info.isFile()) throw invalid(`${unit} must be a regular file for a workspace restore`);
430
+ return readFile(file, 'utf8');
431
+ }
432
+ const incoming = async unit => {
433
+ const declared = units.find(entry => entry.path === unit);
434
+ return declared ? regular(root, unit, declared) : undefined;
435
+ };
436
+ const owners = new Map();
437
+ let hasLedger = false;
438
+ for (const text of [await incoming(RESULT_LEDGER), await regular(home, RESULT_LEDGER)]) {
439
+ if (text === undefined) continue;
440
+ let value;
441
+ try { value = JSON.parse(text); } catch { throw invalid('assignment result ledger is not readable JSON; repair it before restoring'); }
442
+ const absolute = value => typeof value === 'string' && path.isAbsolute(value);
443
+ if (value?.version !== 1 || !Array.isArray(value.workspaces) || !value.workspaces.every(absolute) ||
444
+ !Array.isArray(value.results) || !value.results.every(entry => entry && typeof entry.assignmentId === 'string' &&
445
+ absolute(entry.checkout) && (entry.worktree === undefined || absolute(entry.worktree))))
446
+ throw invalid('assignment result ledger has an unsupported or invalid shape');
447
+ hasLedger = true;
448
+ for (const entry of value.results) {
449
+ const owner = { assignmentId: entry.assignmentId, checkout: entry.checkout, ...(entry.worktree === undefined ? {} : { worktree: entry.worktree }) };
450
+ const previous = owners.get(owner.assignmentId);
451
+ const identity = value => JSON.stringify({ assignmentId: value.assignmentId, checkout: value.checkout, worktree: value.worktree });
452
+ if (previous && identity(previous) !== identity(owner)) throw invalid('assignment result ownership conflicts with current data; reconcile it before restoring');
453
+ // Its evidence comes along, the current data's first; how it was handled does not, so a restored result is resolved again.
454
+ const evidence = value => !!value && typeof value === 'object' && !Array.isArray(value) &&
455
+ ['agent', 'status', 'finishedAt', 'project', 'brief', 'summary'].every(key => typeof value[key] === 'string') &&
456
+ Array.isArray(value.requesters) && value.requesters.every(id => typeof id === 'string') && (value.taskId === undefined || typeof value.taskId === 'string');
457
+ const result = evidence(entry.result) ? entry.result : previous?.result;
458
+ owners.set(owner.assignmentId, { ...owner, ...(result === undefined ? {} : { result }) });
459
+ }
460
+ }
461
+ const markers = [await incoming(RESULT_MARKER), await regular(home, RESULT_MARKER)];
462
+ if (markers.some(text => text !== undefined && text !== '1\n')) throw invalid('assignment result initialized marker is invalid');
463
+ await mkdir(path.join(root, 'state'), { recursive: true, mode: 0o700 });
464
+ if (hasLedger) await writeAtomic(path.join(root, RESULT_LEDGER), JSON.stringify({ version: 1, workspaces: [], results: [...owners.values()] }) + '\n');
465
+ result.push({ path: RESULT_LEDGER, kind: hasLedger ? 'file' : 'absent' });
466
+ const initialized = markers.some(text => text !== undefined);
467
+ if (initialized) await writeAtomic(path.join(root, RESULT_MARKER), '1\n');
468
+ result.push({ path: RESULT_MARKER, kind: initialized ? 'file' : 'absent' });
469
+ const mappings = await incoming(DESTINATIONS);
470
+ if (mappings !== undefined) {
471
+ await writeAtomic(path.join(root, QUARANTINED_DESTINATIONS), mappings);
472
+ result.push({ path: QUARANTINED_DESTINATIONS, kind: 'file' });
473
+ }
474
+ result.push({ path: DESTINATIONS, kind: 'absent' });
475
+ const registryUnit = 'state/web-workspaces.json';
476
+ const registryDeclaration = units.find(unit => unit.path === registryUnit);
477
+ const registryText = registryDeclaration ? await incoming(registryUnit) : await regular(home, registryUnit);
478
+ if (registryText !== undefined) {
479
+ let registry;
480
+ try { registry = JSON.parse(registryText); } catch { throw invalid('workspace registry is not readable JSON; repair it before restoring'); }
481
+ // Reapproval of the same mapping ID must not reactivate historical token grants.
482
+ // Rotate epochs in rows, pending native intents and cached receipt results alike.
483
+ const epoch = `restore-${randomBytes(16).toString('hex')}`;
484
+ let revoked = false;
485
+ const revoke = value => {
486
+ if (!value || typeof value !== 'object') return;
487
+ if (Object.hasOwn(value, 'grantEpoch')) { value.grantEpoch = epoch; revoked = true; }
488
+ for (const child of Object.values(value)) revoke(child);
489
+ };
490
+ revoke(registry);
491
+ await writeAtomic(path.join(root, registryUnit), revoked ? JSON.stringify(registry) + '\n' : registryText);
492
+ result.push({ path: registryUnit, kind: 'file' });
493
+ } else if (registryDeclaration) result.push({ path: registryUnit, kind: 'absent' });
494
+ if (hasLedger || initialized || mappings !== undefined || await exists(path.join(home, DESTINATIONS))) warnings.push('Workspace restore retains assignment owners but clears checkout birth certification; old targets require an audited migration. Worktree destination mappings are inactive and require explicit host approval; archived mapping evidence is in state/worktree-destinations.quarantined.json. Historical checkout grants remain revoked after reapproval.');
495
+ return result;
496
+ }
497
+
399
498
  /**
400
499
  * Restores a backup over `home` and, with `projects`, over the projects it holds whose
401
500
  * roots exist. The current data is checked first: a home in a state schema newer than
@@ -419,6 +518,7 @@ export async function restoreBackup({ home, file, projects = true, safety = true
419
518
  const warnings = [];
420
519
  const areaBase = area => area === 'home' ? home : header.projects[Number(area.slice(8))].root;
421
520
  const directories = [];
521
+ let homeUnits;
422
522
  // The journal exists from the first staged file on, so a crash at any point leaves nothing behind.
423
523
  const journal = { version: 1, id, file: path.resolve(file), by, startedAt: new Date().toISOString(), phase: 'staging', units: [], staging: [], created: [], locks: [] };
424
524
  const record = () => writeAtomic(journalFile(home), JSON.stringify(journal) + '\n');
@@ -452,6 +552,7 @@ export async function restoreBackup({ home, file, projects = true, safety = true
452
552
  };
453
553
  },
454
554
  });
555
+ homeUnits = await prepareWorkspaceRestore(home, staging.get('home'), header.units, warnings);
455
556
  // Directory modes last, deepest first, once nothing more is written into them.
456
557
  for (const [directory, mode] of directories.reverse()) if (Number.isSafeInteger(mode)) await chmod(directory, mode & 0o777 | 0o700).catch(() => {});
457
558
  } catch (error) {
@@ -472,8 +573,8 @@ export async function restoreBackup({ home, file, projects = true, safety = true
472
573
  const plan = [];
473
574
  for (const [area, root] of staging) {
474
575
  const base = areaBase(area);
475
- const units = area === 'home' ? header.units : header.projects[Number(area.slice(8))].units;
476
- const known = area === 'home' ? HOME_UNITS : PROJECT_UNITS;
576
+ const units = area === 'home' ? homeUnits : header.projects[Number(area.slice(8))].units;
577
+ const known = area === 'home' ? [...HOME_UNITS, QUARANTINED_DESTINATIONS] : PROJECT_UNITS;
477
578
  for (const unit of units) {
478
579
  if (!known.includes(unit.path)) { warnings.push(`${unit.path} is not a unit this ALP restores; left as it is`); continue; }
479
580
  const target = path.join(base, ...unit.path.split('/'));
@@ -497,7 +598,7 @@ export async function restoreBackup({ home, file, projects = true, safety = true
497
598
  let safetyFile;
498
599
  if (safety) {
499
600
  try {
500
- safetyFile = await automaticBackup(home, 'pre-restore', { units: header.units.map(unit => unit.path).filter(unit => HOME_UNITS.includes(unit)), projects: roots, by });
601
+ safetyFile = await automaticBackup(home, 'pre-restore', { units: [...new Set([...header.units.map(unit => unit.path), ...homeUnits.map(unit => unit.path)])].filter(unit => HOME_UNITS.includes(unit) || unit === QUARANTINED_DESTINATIONS), projects: roots, by });
501
602
  } catch (error) {
502
603
  await abandon();
503
604
  throw new AlpError('RESTORE_SAFETY_BACKUP_FAILED', `could not save the current data before restoring (${error?.message ?? error}); nothing was changed`, { cause: error });
package/src/bridges.js ADDED
@@ -0,0 +1,113 @@
1
+ import { createRequire } from 'node:module';
2
+ import { isExecutableName, isPackaged, isSelf, ROLE_ARGS } from './packaged.js';
3
+
4
+ /**
5
+ * The stdio MCP bridges an agent CLI starts to reach alpd's tools (ACP agents and Antigravity).
6
+ * Under Node they run as `node -e <source>`; the ALP executable cannot evaluate `-e`, so it runs
7
+ * them as `alp bridge acp|antigravity`, which calls runBridge (t-1e02).
8
+ */
9
+
10
+ export const ACP_BRIDGE = `
11
+ const net = require('node:net');
12
+ const readline = require('node:readline');
13
+ const socket = net.connect(process.env.ALP_BRIDGE_SOCKET);
14
+ const waiting = new Map();
15
+ let sequence = 0;
16
+ let buffer = '';
17
+ socket.setEncoding('utf8');
18
+ socket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
19
+ socket.on('data', data => {
20
+ buffer += data;
21
+ for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
22
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
23
+ try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
24
+ }
25
+ });
26
+ socket.on('close', () => process.exit(0));
27
+ socket.on('error', () => process.exit(1));
28
+ const ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
29
+ const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
30
+ readline.createInterface({ input: process.stdin }).on('line', async line => {
31
+ let message; try { message = JSON.parse(line); } catch { return; }
32
+ if (message.id === undefined || message.id === null) return;
33
+ try {
34
+ if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });
35
+ if (message.method === 'ping') return send({ id: message.id, result: {} });
36
+ if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
37
+ if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }
38
+ send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
39
+ } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
40
+ });
41
+ process.stdin.on('end', () => process.exit(0));
42
+ `;
43
+
44
+ export const ANTIGRAVITY_BRIDGE = `// ALP Antigravity bridge v1
45
+
46
+ const net = require('node:net');
47
+ const readline = require('node:readline');
48
+ const socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;
49
+ const waiting = new Map();
50
+ let sequence = 0;
51
+ let buffer = '';
52
+ socket?.setEncoding('utf8');
53
+ socket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
54
+ socket?.on('data', data => {
55
+ buffer += data;
56
+ for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
57
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
58
+ try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
59
+ }
60
+ });
61
+ socket?.on('close', () => process.exit(0));
62
+ socket?.on('error', () => process.exit(1));
63
+ const ask = message => !socket ? Promise.resolve({ tools: [], result: { content: [{ type: 'text', text: 'No ALP session' }], isError: true } }) : new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
64
+ const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
65
+ readline.createInterface({ input: process.stdin }).on('line', async line => {
66
+ let message; try { message = JSON.parse(line); } catch { return; }
67
+ if (message.id === undefined || message.id === null) return;
68
+ try {
69
+ if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });
70
+ if (message.method === 'ping') return send({ id: message.id, result: {} });
71
+ if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
72
+ if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }
73
+ send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
74
+ } catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
75
+ });
76
+ process.stdin.on('end', () => process.exit(0));
77
+ `;
78
+
79
+ const BRIDGES = { acp: ACP_BRIDGE, antigravity: ANTIGRAVITY_BRIDGE };
80
+
81
+ /** Runs a bridge in this process, as `node -e` would. @param {string} kind */
82
+ export function runBridge(kind) {
83
+ const source = Object.hasOwn(BRIDGES, kind) ? BRIDGES[/** @type {'acp' | 'antigravity'} */ (kind)] : undefined;
84
+ if (!source) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
85
+ // eslint-disable-next-line no-new-func
86
+ new Function('require', source)(createRequire(import.meta.url));
87
+ }
88
+
89
+ /**
90
+ * The command an agent CLI runs to start a bridge: `node -e <source>` under Node, the executable's
91
+ * `bridge <kind>` subcommand when packaged.
92
+ * @param {'acp' | 'antigravity'} kind
93
+ * @returns {{ command: string, args: string[] }}
94
+ */
95
+ export function bridgeCommand(kind) {
96
+ if (!Object.hasOwn(BRIDGES, kind)) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
97
+ if (isPackaged()) return { command: process.execPath, args: [...ROLE_ARGS[kind === 'acp' ? 'bridge-acp' : 'bridge-antigravity']] };
98
+ return { command: process.execPath, args: ['-e', BRIDGES[kind]] };
99
+ }
100
+
101
+ /**
102
+ * Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or the ALP
103
+ * executable's `bridge <kind>` (only when its command is named alp, so another server is kept).
104
+ * @param {'acp' | 'antigravity'} kind
105
+ * @param {unknown} args
106
+ * @param {unknown} [command]
107
+ */
108
+ export function isBridgeArgs(kind, args, command = undefined) {
109
+ if (!Array.isArray(args)) return false;
110
+ const marker = kind === 'antigravity' ? '// ALP Antigravity bridge v1' : undefined;
111
+ if (marker && args.some(arg => typeof arg === 'string' && arg.startsWith(marker))) return true;
112
+ return typeof command === 'string' && (isExecutableName(command) || isSelf(command)) && args.length === 2 && args[0] === 'bridge' && args[1] === kind;
113
+ }