@anhlp/alp-core 0.0.0-beta.2 → 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.
Files changed (158) hide show
  1. package/dist/backup.js +106 -4
  2. package/dist/bridges.d.ts +26 -0
  3. package/dist/bridges.js +96 -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/library-edit.d.ts +57 -5
  9. package/dist/library-edit.js +216 -11
  10. package/dist/library.d.ts +14 -1
  11. package/dist/library.js +73 -5
  12. package/dist/migrations.js +1 -1
  13. package/dist/models.d.ts +74 -0
  14. package/dist/models.js +67 -1
  15. package/dist/packaged.d.ts +122 -0
  16. package/dist/packaged.js +125 -0
  17. package/dist/packs.d.ts +57 -0
  18. package/dist/packs.js +247 -0
  19. package/dist/permissions.d.ts +3 -2
  20. package/dist/permissions.js +6 -3
  21. package/dist/profiles.js +6 -6
  22. package/dist/providers.d.ts +4 -5
  23. package/dist/providers.js +26 -5
  24. package/dist/skill-validate.d.ts +85 -0
  25. package/dist/skill-validate.js +298 -0
  26. package/dist/task-rows.d.ts +5 -0
  27. package/dist/task-rows.js +1 -1
  28. package/dist/tasks.d.ts +23 -4
  29. package/dist/tasks.js +103 -9
  30. package/dist/types.d.ts +3 -0
  31. package/dist/upgrade.d.ts +10 -0
  32. package/dist/upgrade.js +112 -6
  33. package/dist/user-settings.d.ts +2 -0
  34. package/dist/user-settings.js +40 -1
  35. package/dist/user-worktree.d.ts +29 -0
  36. package/dist/user-worktree.js +242 -0
  37. package/dist/validation.d.ts +1 -0
  38. package/dist/validation.js +35 -13
  39. package/package.json +34 -2
  40. package/src/backup.js +106 -5
  41. package/src/bridges.js +113 -0
  42. package/src/gate-ledger.js +125 -0
  43. package/src/index.js +1 -0
  44. package/src/library-edit.js +227 -12
  45. package/src/library.js +96 -6
  46. package/src/migrations.js +1 -1
  47. package/src/models.js +87 -1
  48. package/src/packaged.js +207 -0
  49. package/src/packs.js +246 -0
  50. package/src/permissions.d.ts +3 -2
  51. package/src/permissions.js +13 -3
  52. package/src/profiles.js +7 -7
  53. package/src/providers.js +23 -7
  54. package/src/resolver.js +1 -1
  55. package/src/skill-validate.js +287 -0
  56. package/src/task-rows.js +1 -1
  57. package/src/tasks.d.ts +23 -4
  58. package/src/tasks.js +137 -10
  59. package/src/types.d.ts +3 -0
  60. package/src/upgrade.js +54 -6
  61. package/src/user-settings.d.ts +2 -0
  62. package/src/user-settings.js +51 -1
  63. package/src/user-worktree.js +259 -0
  64. package/src/validation.d.ts +1 -0
  65. package/src/validation.js +43 -14
  66. package/templates/ALP.md +52 -52
  67. package/templates/agents/lead/AGENT.md +77 -74
  68. package/templates/agents/main/AGENT.md +153 -141
  69. package/templates/agents/oracle/AGENT.md +38 -37
  70. package/templates/agents/peer/AGENT.md +56 -52
  71. package/templates/agents/reviewer/AGENT.md +63 -65
  72. package/templates/agents/supervisor/AGENT.md +63 -63
  73. package/templates/packs/architecture/agents/architect/AGENT.md +41 -0
  74. package/templates/packs/architecture/agents/architect/agent.json +5 -0
  75. package/templates/packs/architecture/agents/docs-maintainer/AGENT.md +33 -0
  76. package/templates/packs/architecture/agents/docs-maintainer/agent.json +4 -0
  77. package/templates/packs/architecture/pack.json +7 -0
  78. package/templates/packs/architecture/teams/blueprint/HOUSE_RULES.md +12 -0
  79. package/templates/packs/architecture/teams/blueprint/team.json +19 -0
  80. package/templates/packs/backend/pack.json +6 -0
  81. package/templates/packs/backend/skills/backend-development/SKILL.md +102 -0
  82. package/templates/packs/backend/skills/backend-development/references/api-design.md +96 -0
  83. package/templates/packs/backend/skills/backend-development/references/authentication.md +78 -0
  84. package/templates/packs/backend/skills/backend-development/references/error-handling.md +86 -0
  85. package/templates/packs/backend/skills/backend-development/references/testing.md +81 -0
  86. package/templates/packs/backend/skills/databases/SKILL.md +103 -0
  87. package/templates/packs/backend/skills/databases/references/query-performance.md +87 -0
  88. package/templates/packs/backend/skills/databases/references/schema-and-migrations.md +87 -0
  89. package/templates/packs/design/pack.json +6 -0
  90. package/templates/packs/design/skills/ui-design/SKILL.md +86 -0
  91. package/templates/packs/design/skills/ui-design/references/design-tokens.md +67 -0
  92. package/templates/packs/design/skills/ui-design/references/interaction-states.md +73 -0
  93. package/templates/packs/design/skills/ui-design/references/layout-and-typography.md +71 -0
  94. package/templates/packs/design/skills/ui-design/references/ui-review.md +83 -0
  95. package/templates/packs/frontend/pack.json +6 -0
  96. package/templates/packs/frontend/skills/frontend-development/SKILL.md +105 -0
  97. package/templates/packs/frontend/skills/frontend-development/references/accessibility.md +86 -0
  98. package/templates/packs/frontend/skills/frontend-development/references/components-and-state.md +79 -0
  99. package/templates/packs/frontend/skills/frontend-development/references/data-fetching.md +86 -0
  100. package/templates/packs/frontend/skills/frontend-development/references/frameworks.md +77 -0
  101. package/templates/packs/frontend/skills/frontend-development/references/performance.md +78 -0
  102. package/templates/packs/integration/pack.json +6 -0
  103. package/templates/packs/integration/skills/mcp-integration/SKILL.md +100 -0
  104. package/templates/packs/integration/skills/mcp-integration/references/server-implementation.md +95 -0
  105. package/templates/packs/integration/skills/mcp-integration/references/testing.md +78 -0
  106. package/templates/packs/integration/skills/mcp-integration/references/tool-design.md +97 -0
  107. package/templates/packs/operations/pack.json +6 -0
  108. package/templates/packs/operations/skills/devops/SKILL.md +85 -0
  109. package/templates/packs/operations/skills/devops/references/ci-cd.md +84 -0
  110. package/templates/packs/operations/skills/devops/references/containers.md +85 -0
  111. package/templates/packs/operations/skills/devops/references/deployment-and-rollback.md +85 -0
  112. package/templates/packs/operations/skills/devops/references/observability.md +86 -0
  113. package/templates/packs/quality/pack.json +6 -0
  114. package/templates/packs/quality/skills/web-testing/SKILL.md +102 -0
  115. package/templates/packs/quality/skills/web-testing/references/e2e.md +85 -0
  116. package/templates/packs/quality/skills/web-testing/references/performance-testing.md +85 -0
  117. package/templates/packs/quality/skills/web-testing/references/security-testing.md +78 -0
  118. package/templates/packs/quality/skills/web-testing/references/unit-and-component.md +78 -0
  119. package/templates/role-skills.json +4 -4
  120. package/templates/skills/architecture-docs/SKILL.md +81 -0
  121. package/templates/skills/architecture-docs/references/adr.md +62 -0
  122. package/templates/skills/architecture-docs/references/diagrams.md +60 -0
  123. package/templates/skills/architecture-docs/references/evidence-rules.md +49 -0
  124. package/templates/skills/bug-loop/SKILL.md +41 -40
  125. package/templates/skills/bug-loop/references/test-proof.md +21 -19
  126. package/templates/skills/compact/SKILL.md +34 -0
  127. package/templates/skills/curate/SKILL.md +36 -0
  128. package/templates/skills/feature-architecture/SKILL.md +90 -0
  129. package/templates/skills/feature-architecture/references/architecture-contract.md +95 -0
  130. package/templates/skills/feature-architecture/references/feature-design.md +69 -0
  131. package/templates/skills/feature-architecture/scripts/check-boundaries.mjs +270 -0
  132. package/templates/skills/goal-griller/SKILL.md +27 -27
  133. package/templates/skills/prompt-leverage/SKILL.md +29 -27
  134. package/templates/skills/prompt-leverage/references/brief-template.md +9 -9
  135. package/templates/skills/release-readiness/SKILL.md +83 -0
  136. package/templates/skills/release-readiness/references/checklist.md +40 -0
  137. package/templates/skills/release-readiness/references/verdict-template.md +53 -0
  138. package/templates/skills/safe-refactor/SKILL.md +84 -0
  139. package/templates/skills/safe-refactor/references/characterization-tests.md +57 -0
  140. package/templates/skills/safe-refactor/references/compatibility-checklist.md +56 -0
  141. package/templates/skills/security-review/SKILL.md +87 -0
  142. package/templates/skills/security-review/references/checklist.md +74 -0
  143. package/templates/skills/security-review/references/severity.md +61 -0
  144. package/templates/skills/sequence-execution-plan/SKILL.md +41 -38
  145. package/templates/skills/sequence-execution-plan/references/plan-template.md +5 -5
  146. package/templates/skills/skill-authoring/SKILL.md +84 -0
  147. package/templates/skills/skill-authoring/references/evaluation.md +45 -0
  148. package/templates/skills/skill-authoring/references/skill-anatomy.md +74 -0
  149. package/templates/skills/skill-authoring/references/trigger-design.md +52 -0
  150. package/templates/skills/smart-commits/SKILL.md +37 -36
  151. package/templates/skills/test-strategy/SKILL.md +83 -0
  152. package/templates/skills/test-strategy/references/contract-tests.md +46 -0
  153. package/templates/skills/test-strategy/references/risk-matrix.md +53 -0
  154. package/templates/skills/xia/SKILL.md +40 -38
  155. package/templates/teams/cafe/HOUSE_RULES.md +1 -1
  156. package/templates/teams/cafe/team.json +1 -1
  157. package/templates/teams/pho/HOUSE_RULES.md +1 -1
  158. package/templates/teams/pho/team.json +1 -1
@@ -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
+ };
@@ -1,5 +1,6 @@
1
1
  export const PROJECT_SETTINGS: string[];
2
2
  export const USER_SETTINGS: string[];
3
+ export const DASHBOARD_SETTINGS: readonly string[];
3
4
  export const RETIRED_SETTINGS: { project: Record<string, string>; user: Record<string, string> };
4
5
  export function settingsKeys(settings: unknown, known: string[], retired?: Record<string, string>): { unknown: Array<{ key: string; suggestion?: string }>; retired: Array<{ key: string; instead: string }> };
5
6
  export function settingsWarnings(settings: unknown, scope: 'project' | 'user'): string[];
@@ -1,7 +1,7 @@
1
1
  // packages/core/src/validation.js
2
2
  import path from "node:path";
3
3
  import { AlpError } from "./errors.js";
4
- import { MODELS } from "./models.js";
4
+ import { EFFORTS, knownModel } from "./models.js";
5
5
  import { validatePermissions } from "./permissions.js";
6
6
  import { validateVerify } from "./verify.js";
7
7
  var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -10,9 +10,9 @@ var stringMap = (value) => object(value) && Object.values(value).every((v) => ty
10
10
  function requireValue(condition, code, source, message) {
11
11
  if (!condition) throw new AlpError(code, `${source}: ${message}`);
12
12
  }
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"];
13
+ var PROJECT_SETTINGS = ["$schema", "defaultAgent", "workflow", "runtime", "permissions", "verify", "delegation", "team", "profile", "templateDefaults", "compact", "curate"];
14
+ var USER_SETTINGS = ["$schema", "language", "permissions", "limits", "recovery", "dashboard", "web", "curate"];
15
+ var DASHBOARD_SETTINGS = Object.freeze(["enabled", "port", "permissions"]);
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)) {
@@ -85,8 +98,9 @@ function validateSettings(settings, source) {
85
98
  const where = `${key}.${team}.${agent}`;
86
99
  check(object(config), `${where} must be an object`);
87
100
  if (config.autocompact !== void 0) validateAutoCompact(config.autocompact, check, `${where}.autocompact`);
101
+ if (config.commands !== void 0) check(Array.isArray(config.commands) && config.commands.every((name) => typeof name === "string" && /^[^\s/]{1,256}$/.test(name)), `${where}.commands must be a list of command names, without whitespace or /`);
88
102
  if (Object.hasOwn(config, "profiles")) {
89
- check(Object.keys(config).every((key2) => ["profiles", "autocompact"].includes(key2)), `${where}: use profiles and autocompact`);
103
+ check(Object.keys(config).every((key2) => ["profiles", "autocompact", "commands"].includes(key2)), `${where}: use profiles, autocompact and commands`);
90
104
  check(Array.isArray(config.profiles) && config.profiles.length > 0, `${where}.profiles must be a nonempty list`);
91
105
  const models = [];
92
106
  for (const [index, entry] of config.profiles.entries()) {
@@ -96,7 +110,7 @@ function validateSettings(settings, source) {
96
110
  const [provider, model, effort] = entry.split(":");
97
111
  check(model !== "*" || agent !== "oracle" && agent !== "main", `${at}: ${agent} runs on a named model, not any model`);
98
112
  if (effort !== void 0) {
99
- const known = MODELS.find((candidate) => candidate.runtime === provider && candidate.id === model);
113
+ const known = knownModel(`${provider}:${model}`);
100
114
  check(EFFORTS.includes(effort), `${at}: effort ${effort} is unsupported`);
101
115
  check(!known?.efforts.length || known.efforts.includes(effort), `${at}: ${provider}:${model} takes effort ${known?.efforts.join(", ")}`);
102
116
  }
@@ -110,14 +124,14 @@ function validateSettings(settings, source) {
110
124
  check(new Set(models).size === models.length, `${where}.profiles must not repeat the same model`);
111
125
  check(agent !== "main" || config.profiles.length === 1, `${where}.profiles: main runs on exactly one model`);
112
126
  } else if (agent === "oracle") {
113
- const entries = Object.entries(config).filter(([key2]) => key2 !== "autocompact");
127
+ const entries = Object.entries(config).filter(([key2]) => key2 !== "autocompact" && key2 !== "commands");
114
128
  check(entries.length > 0 && entries.every(([provider]) => ["claude", "codex"].includes(provider)), `${where} must define profiles or claude/codex lenses`);
115
129
  for (const [provider, lens] of entries) {
116
130
  validateChoice(lens, `${where}.${provider}`);
117
131
  check(lens.provider === provider && nonempty(lens.model), `${where}.${provider}: specify matching provider and model`);
118
132
  }
119
133
  } else {
120
- const { autocompact, ...legacy } = config;
134
+ const { autocompact, commands, ...legacy } = config;
121
135
  validateChoice(legacy, where);
122
136
  }
123
137
  }
@@ -138,6 +152,7 @@ function validateUserSettings(settings, source) {
138
152
  check(object(settings), "expected an object");
139
153
  const { unknown } = settingsKeys(settings, USER_SETTINGS, RETIRED_SETTINGS.user);
140
154
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], USER_SETTINGS) : "");
155
+ checkCurate(settings, check);
141
156
  for (const key of ["limits", "recovery"]) {
142
157
  if (settings[key] === void 0) continue;
143
158
  check(object(settings[key]), `${key} must be an object`);
@@ -145,10 +160,18 @@ function validateUserSettings(settings, source) {
145
160
  check(!extra, `unsupported ${key} field '${extra}'; use autoResume`);
146
161
  if (settings[key].autoResume !== void 0) check(typeof settings[key].autoResume === "boolean", `${key}.autoResume must be true or false`);
147
162
  }
163
+ for (const key of ["dashboard", "web"]) {
164
+ const section = settings[key];
165
+ if (section === void 0) continue;
166
+ check(object(section), `${key} must be an object`);
167
+ const allowed = key === "web" ? [...DASHBOARD_SETTINGS, "relay"] : DASHBOARD_SETTINGS;
168
+ const extra = Object.keys(section).find((field) => !allowed.includes(field));
169
+ check(!extra, `unsupported ${key} field '${extra}'; use ${allowed.slice(0, -1).join(", ")} or ${allowed.at(-1)}`);
170
+ if (section.permissions !== void 0) check(Array.isArray(section.permissions) && section.permissions.every((entry) => typeof entry === "string" && /^[a-z][a-z.]*$/.test(entry)), `${key}.permissions must be a list of permission names, such as files.read`);
171
+ if (section.enabled !== void 0) check(typeof section.enabled === "boolean", `${key}.enabled must be true or false`);
172
+ if (section.port !== void 0) check(Number.isInteger(section.port) && section.port >= 1024 && section.port <= 65535, `${key}.port must be a port from 1024 to 65535`);
173
+ }
148
174
  if (settings.web !== void 0) {
149
- 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`);
152
175
  const relay = settings.web.relay;
153
176
  if (relay !== void 0) {
154
177
  check(object(relay), "web.relay must be an object");
@@ -158,8 +181,6 @@ function validateUserSettings(settings, source) {
158
181
  if (relay.endpoint !== void 0) check(typeof relay.endpoint === "string" && /^[a-z0-9.-]+:\d{1,5}$/i.test(relay.endpoint), "web.relay.endpoint must be host:port, such as relay.paseo.sh:443");
159
182
  if (relay.useTls !== void 0) check(typeof relay.useTls === "boolean", "web.relay.useTls must be true or false");
160
183
  }
161
- if (settings.web.enabled !== void 0) check(typeof settings.web.enabled === "boolean", "web.enabled must be true or false");
162
- if (settings.web.port !== void 0) check(Number.isInteger(settings.web.port) && settings.web.port >= 1024 && settings.web.port <= 65535, "web.port must be a port from 1024 to 65535");
163
184
  }
164
185
  if (settings.language !== void 0) check(nonempty(settings.language) && settings.language.trim().length <= 40, "language must be a language name of at most 40 characters, such as Vietnamese or English");
165
186
  validatePermissions(settings.permissions, source);
@@ -278,6 +299,7 @@ export {
278
299
  AGENT_SETTINGS,
279
300
  BLOCKING_HOOK_EVENTS,
280
301
  CONTEXT_TOKENS,
302
+ DASHBOARD_SETTINGS,
281
303
  HOOK_EVENTS,
282
304
  HOOK_SETTINGS,
283
305
  PROJECT_SETTINGS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-core",
3
- "version": "0.0.0-beta.2",
3
+ "version": "0.0.1-beta.10",
4
4
  "type": "module",
5
5
  "description": "ALP core module",
6
6
  "files": [
@@ -278,13 +278,45 @@
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"
297
+ },
298
+ "./skill-validate": {
299
+ "alp-source": {
300
+ "types": "./src/skill-validate.js",
301
+ "default": "./src/skill-validate.js"
302
+ },
303
+ "types": "./dist/skill-validate.d.ts",
304
+ "default": "./src/skill-validate.js"
305
+ },
306
+ "./packs": {
307
+ "alp-source": {
308
+ "types": "./src/packs.js",
309
+ "default": "./src/packs.js"
310
+ },
311
+ "types": "./dist/packs.d.ts",
312
+ "default": "./src/packs.js"
281
313
  }
282
314
  },
283
315
  "engines": {
284
316
  "node": ">=22.12"
285
317
  },
286
318
  "dependencies": {
287
- "@anhlp/alp-protocol": "0.0.0-beta.2"
319
+ "@anhlp/alp-protocol": "0.0.1-beta.10"
288
320
  },
289
321
  "scripts": {
290
322
  "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 });