@anhlp/alp-core 0.0.1-beta.6 → 0.0.1-beta.8

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 (135) hide show
  1. package/dist/bridges.d.ts +5 -6
  2. package/dist/bridges.js +3 -4
  3. package/dist/library-edit.d.ts +51 -2
  4. package/dist/library-edit.js +160 -8
  5. package/dist/library.d.ts +14 -1
  6. package/dist/library.js +73 -5
  7. package/dist/models.d.ts +35 -0
  8. package/dist/models.js +17 -1
  9. package/dist/packaged.d.ts +37 -45
  10. package/dist/packaged.js +42 -156
  11. package/dist/packs.d.ts +57 -0
  12. package/dist/packs.js +247 -0
  13. package/dist/permissions.d.ts +3 -2
  14. package/dist/permissions.js +6 -3
  15. package/dist/profiles.js +6 -6
  16. package/dist/providers.d.ts +2 -5
  17. package/dist/providers.js +22 -6
  18. package/dist/skill-validate.d.ts +85 -0
  19. package/dist/skill-validate.js +298 -0
  20. package/dist/template-path.d.ts +2 -2
  21. package/dist/template-path.js +0 -5
  22. package/dist/types.d.ts +2 -0
  23. package/dist/upgrade.d.ts +10 -0
  24. package/dist/upgrade.js +112 -6
  25. package/dist/validation.js +6 -6
  26. package/package.json +18 -2
  27. package/src/bridges.js +9 -10
  28. package/src/library-edit.js +170 -8
  29. package/src/library.js +96 -6
  30. package/src/models.js +24 -0
  31. package/src/packaged.js +74 -191
  32. package/src/packs.js +246 -0
  33. package/src/permissions.d.ts +3 -2
  34. package/src/permissions.js +13 -3
  35. package/src/profiles.js +7 -7
  36. package/src/providers.js +22 -8
  37. package/src/resolver.js +1 -1
  38. package/src/skill-validate.js +287 -0
  39. package/src/template-path.js +1 -6
  40. package/src/types.d.ts +2 -0
  41. package/src/upgrade.js +54 -6
  42. package/src/validation.js +8 -7
  43. package/templates/ALP.md +52 -52
  44. package/templates/agents/lead/AGENT.md +77 -74
  45. package/templates/agents/main/AGENT.md +153 -145
  46. package/templates/agents/oracle/AGENT.md +38 -37
  47. package/templates/agents/peer/AGENT.md +56 -52
  48. package/templates/agents/reviewer/AGENT.md +63 -65
  49. package/templates/agents/supervisor/AGENT.md +63 -63
  50. package/templates/packs/architecture/agents/architect/AGENT.md +41 -0
  51. package/templates/packs/architecture/agents/architect/agent.json +5 -0
  52. package/templates/packs/architecture/agents/docs-maintainer/AGENT.md +33 -0
  53. package/templates/packs/architecture/agents/docs-maintainer/agent.json +4 -0
  54. package/templates/packs/architecture/pack.json +7 -0
  55. package/templates/packs/architecture/teams/blueprint/HOUSE_RULES.md +12 -0
  56. package/templates/packs/architecture/teams/blueprint/team.json +19 -0
  57. package/templates/packs/backend/pack.json +6 -0
  58. package/templates/packs/backend/skills/backend-development/SKILL.md +102 -0
  59. package/templates/packs/backend/skills/backend-development/references/api-design.md +96 -0
  60. package/templates/packs/backend/skills/backend-development/references/authentication.md +78 -0
  61. package/templates/packs/backend/skills/backend-development/references/error-handling.md +86 -0
  62. package/templates/packs/backend/skills/backend-development/references/testing.md +81 -0
  63. package/templates/packs/backend/skills/databases/SKILL.md +103 -0
  64. package/templates/packs/backend/skills/databases/references/query-performance.md +87 -0
  65. package/templates/packs/backend/skills/databases/references/schema-and-migrations.md +87 -0
  66. package/templates/packs/design/pack.json +6 -0
  67. package/templates/packs/design/skills/ui-design/SKILL.md +86 -0
  68. package/templates/packs/design/skills/ui-design/references/design-tokens.md +67 -0
  69. package/templates/packs/design/skills/ui-design/references/interaction-states.md +73 -0
  70. package/templates/packs/design/skills/ui-design/references/layout-and-typography.md +71 -0
  71. package/templates/packs/design/skills/ui-design/references/ui-review.md +83 -0
  72. package/templates/packs/frontend/pack.json +6 -0
  73. package/templates/packs/frontend/skills/frontend-development/SKILL.md +105 -0
  74. package/templates/packs/frontend/skills/frontend-development/references/accessibility.md +86 -0
  75. package/templates/packs/frontend/skills/frontend-development/references/components-and-state.md +79 -0
  76. package/templates/packs/frontend/skills/frontend-development/references/data-fetching.md +86 -0
  77. package/templates/packs/frontend/skills/frontend-development/references/frameworks.md +77 -0
  78. package/templates/packs/frontend/skills/frontend-development/references/performance.md +78 -0
  79. package/templates/packs/integration/pack.json +6 -0
  80. package/templates/packs/integration/skills/mcp-integration/SKILL.md +100 -0
  81. package/templates/packs/integration/skills/mcp-integration/references/server-implementation.md +95 -0
  82. package/templates/packs/integration/skills/mcp-integration/references/testing.md +78 -0
  83. package/templates/packs/integration/skills/mcp-integration/references/tool-design.md +97 -0
  84. package/templates/packs/operations/pack.json +6 -0
  85. package/templates/packs/operations/skills/devops/SKILL.md +85 -0
  86. package/templates/packs/operations/skills/devops/references/ci-cd.md +84 -0
  87. package/templates/packs/operations/skills/devops/references/containers.md +85 -0
  88. package/templates/packs/operations/skills/devops/references/deployment-and-rollback.md +85 -0
  89. package/templates/packs/operations/skills/devops/references/observability.md +86 -0
  90. package/templates/packs/quality/pack.json +6 -0
  91. package/templates/packs/quality/skills/web-testing/SKILL.md +102 -0
  92. package/templates/packs/quality/skills/web-testing/references/e2e.md +85 -0
  93. package/templates/packs/quality/skills/web-testing/references/performance-testing.md +85 -0
  94. package/templates/packs/quality/skills/web-testing/references/security-testing.md +78 -0
  95. package/templates/packs/quality/skills/web-testing/references/unit-and-component.md +78 -0
  96. package/templates/role-skills.json +4 -4
  97. package/templates/skills/architecture-docs/SKILL.md +81 -0
  98. package/templates/skills/architecture-docs/references/adr.md +62 -0
  99. package/templates/skills/architecture-docs/references/diagrams.md +60 -0
  100. package/templates/skills/architecture-docs/references/evidence-rules.md +49 -0
  101. package/templates/skills/bug-loop/SKILL.md +41 -40
  102. package/templates/skills/bug-loop/references/test-proof.md +21 -19
  103. package/templates/skills/compact/SKILL.md +2 -2
  104. package/templates/skills/curate/SKILL.md +6 -5
  105. package/templates/skills/feature-architecture/SKILL.md +90 -0
  106. package/templates/skills/feature-architecture/references/architecture-contract.md +95 -0
  107. package/templates/skills/feature-architecture/references/feature-design.md +69 -0
  108. package/templates/skills/feature-architecture/scripts/check-boundaries.mjs +270 -0
  109. package/templates/skills/goal-griller/SKILL.md +27 -27
  110. package/templates/skills/prompt-leverage/SKILL.md +29 -27
  111. package/templates/skills/prompt-leverage/references/brief-template.md +9 -9
  112. package/templates/skills/release-readiness/SKILL.md +83 -0
  113. package/templates/skills/release-readiness/references/checklist.md +40 -0
  114. package/templates/skills/release-readiness/references/verdict-template.md +53 -0
  115. package/templates/skills/safe-refactor/SKILL.md +84 -0
  116. package/templates/skills/safe-refactor/references/characterization-tests.md +57 -0
  117. package/templates/skills/safe-refactor/references/compatibility-checklist.md +56 -0
  118. package/templates/skills/security-review/SKILL.md +87 -0
  119. package/templates/skills/security-review/references/checklist.md +74 -0
  120. package/templates/skills/security-review/references/severity.md +61 -0
  121. package/templates/skills/sequence-execution-plan/SKILL.md +41 -38
  122. package/templates/skills/sequence-execution-plan/references/plan-template.md +5 -5
  123. package/templates/skills/skill-authoring/SKILL.md +84 -0
  124. package/templates/skills/skill-authoring/references/evaluation.md +45 -0
  125. package/templates/skills/skill-authoring/references/skill-anatomy.md +74 -0
  126. package/templates/skills/skill-authoring/references/trigger-design.md +52 -0
  127. package/templates/skills/smart-commits/SKILL.md +37 -36
  128. package/templates/skills/test-strategy/SKILL.md +83 -0
  129. package/templates/skills/test-strategy/references/contract-tests.md +46 -0
  130. package/templates/skills/test-strategy/references/risk-matrix.md +53 -0
  131. package/templates/skills/xia/SKILL.md +40 -38
  132. package/templates/teams/cafe/HOUSE_RULES.md +1 -1
  133. package/templates/teams/cafe/team.json +1 -1
  134. package/templates/teams/pho/HOUSE_RULES.md +1 -1
  135. package/templates/teams/pho/team.json +1 -1
package/src/library.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { shippedTemplateRoot } from './template-path.js';
2
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
2
+ import { chmod, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
3
3
  import { moveFile } from './atomic.js';
4
4
  import { createHash, randomUUID } from 'node:crypto';
5
5
  import os from 'node:os';
@@ -42,11 +42,84 @@ async function shippedFiles({ templateRoot, templates }) {
42
42
  return files;
43
43
  }
44
44
 
45
+ /**
46
+ * Every role-skills.json ALP shipped, by sha (CRLF-normalized), with what it gave each role. A
47
+ * library's manifest names the one ALP last wrote, so the built-in skills its user has already been
48
+ * offered are known for a library from before `roleSkillsOffered` was recorded (t-de1a). Add each
49
+ * new shipped version here (packages/core/tests/role-skills-offer.test.js checks the current one is).
50
+ * @type {Readonly<Record<string, Record<string, string[]>>>}
51
+ */
52
+ export const SHIPPED_ROLE_SKILLS = Object.freeze({
53
+ // 0086846 (2026-10-07)
54
+ '7132b9ef1f10db55caea23dbe705a0ab06c83c86f51f074e663d12043a79327a': { main: ['goal-griller', 'xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], lead: ['xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], peer: ['xia', 'bug-loop', 'smart-commits'] },
55
+ // 9ccd54c (2026-10-08): oracle and reviewer, with none
56
+ 'c03f7bcecd61e26e70ef05b268aa7881a75f9e9c45ae5486ae9659cefd6bb449': { main: ['goal-griller', 'xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], lead: ['xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], peer: ['xia', 'bug-loop', 'smart-commits'] },
57
+ // 61181b5 (2026-10-09): supervisor, with none
58
+ '8c5664042d4a4ecd3ded61240d8febbffa6e8965a88af0e9ba0420ad2f2ce8fe': { main: ['goal-griller', 'xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], lead: ['xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], peer: ['xia', 'bug-loop', 'smart-commits'] },
59
+ // 9180aa1 (2026-10-29): compact for main
60
+ 'b12b52102c358119cf834e5f3be54e6a69aa4c9f388fe889dffbb529755292dc': { main: ['goal-griller', 'xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits', 'compact'], lead: ['xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], peer: ['xia', 'bug-loop', 'smart-commits'] },
61
+ // f4d7986 (2026-10-29): curate for main
62
+ 'a84b035d0058cbfcda7e32dc1706b9e83e67764eed24e2e121bdfcd60f924e46': { main: ['goal-griller', 'xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits', 'compact', 'curate'], lead: ['xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits'], peer: ['xia', 'bug-loop', 'smart-commits'] },
63
+ // Skill system v2 (2026-11-05): engineering core skills; reviewer gets its first two
64
+ 'e60be7eec8d9b5180866c9b5a2c14cf0d95a9f1331ed771e93791f7b524af9b1': { main: ['goal-griller', 'xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits', 'compact', 'curate', 'skill-authoring', 'architecture-docs', 'feature-architecture', 'test-strategy', 'safe-refactor', 'security-review', 'release-readiness'], lead: ['xia', 'sequence-execution-plan', 'prompt-leverage', 'bug-loop', 'smart-commits', 'architecture-docs', 'feature-architecture', 'test-strategy', 'safe-refactor', 'security-review', 'release-readiness'], peer: ['xia', 'bug-loop', 'smart-commits', 'feature-architecture', 'test-strategy', 'safe-refactor'], reviewer: ['security-review', 'release-readiness'] },
65
+ });
66
+
67
+ /** An agent → skills object's pairs as `agent/skill` strings (role-skills.json is keyed by agent name); anything else gives none. @param {unknown} roles */
68
+ const rolePairs = roles => roles && typeof roles === 'object' && !Array.isArray(roles)
69
+ ? Object.entries(roles).flatMap(([role, names]) => Array.isArray(names) ? names.filter(skillName).map(name => `${role}/${name}`) : [])
70
+ : [];
71
+
72
+ /**
73
+ * Offers the built-in role skills an edited role-skills.json has never been offered (t-de1a): each
74
+ * goes to the end of its role's list, when that role is listed and lacks it. What was offered is
75
+ * recorded in the manifest (`roleSkillsOffered`), so a skill the user then removes stays removed, and
76
+ * nothing the user wrote is removed or reordered. A role the user's file does not list (setGivenSkills
77
+ * drops a role given none) gets nothing; a file that is missing or not a JSON object is left alone, and
78
+ * its skills are offered again once it can be read. Before the record exists, what the user was offered
79
+ * is what the role-skills.json ALP last wrote gave (SHIPPED_ROLE_SKILLS); an unknown one offers nothing.
80
+ * @returns {Promise<string[]>} the `role/skill` pairs added
81
+ */
82
+ async function offerRoleSkills(home, manifest, shippedText, seeded) {
83
+ const name = 'role-skills.json';
84
+ const shipped = rolePairs(JSON.parse(shippedText));
85
+ const baseline = Array.isArray(manifest.roleSkillsOffered) ? manifest.roleSkillsOffered
86
+ : seeded !== undefined && Object.hasOwn(SHIPPED_ROLE_SKILLS, seeded) ? rolePairs(SHIPPED_ROLE_SKILLS[seeded])
87
+ : shipped;
88
+ const offered = new Set(baseline.filter(pair => typeof pair === 'string'));
89
+ const fresh = shipped.filter(pair => !offered.has(pair));
90
+ const record = () => { manifest.roleSkillsOffered = [...new Set([...offered, ...shipped])].sort(); };
91
+ if (!fresh.length) { const before = JSON.stringify(manifest.roleSkillsOffered); record(); return { added: [], changed: before !== JSON.stringify(manifest.roleSkillsOffered) }; }
92
+ const target = path.join(home, name);
93
+ const text = await optional(target);
94
+ if (text === undefined) { record(); return { added: [], changed: true }; }
95
+ let roles;
96
+ try { roles = JSON.parse(text); } catch { return { added: [], changed: false }; }
97
+ if (!roles || typeof roles !== 'object' || Array.isArray(roles)) return { added: [], changed: false };
98
+ const added = [];
99
+ for (const pair of fresh) {
100
+ const [role, skill] = pair.split('/');
101
+ if (!Array.isArray(roles[role]) || roles[role].includes(skill)) continue;
102
+ roles[role].push(skill);
103
+ added.push(pair);
104
+ }
105
+ if (added.length) {
106
+ const next = JSON.stringify(roles, null, 2) + '\n';
107
+ const temporary = `${target}.${randomUUID().slice(0, 8)}.tmp`;
108
+ await writeFile(temporary, next);
109
+ await moveFile(temporary, target);
110
+ }
111
+ record();
112
+ return { added, changed: true };
113
+ }
114
+
45
115
  /**
46
116
  * Seeds or updates the library in `home`. A file is written when ALP never
47
117
  * shipped it before, and replaced only while it still holds what ALP last wrote.
118
+ * With `offerRoleSkills` (alp upgrade, alp update-template), an edited role-skills.json
119
+ * is also offered the built-in role skills it never was (offerRoleSkills above).
48
120
  * @param {string} home
49
- * @param {{ templateRoot?: URL, templates?: Record<string, string> }} [options]
121
+ * @param {{ templateRoot?: URL, templates?: Record<string, string>, offerRoleSkills?: boolean }} [options]
122
+ * @returns {Promise<{ created: string[], updated: string[], offered?: string[] }>} offered only with offerRoleSkills
50
123
  */
51
124
  export async function seedLibrary(home, options = {}) {
52
125
  const shipped = await shippedFiles(options);
@@ -56,6 +129,8 @@ export async function seedLibrary(home, options = {}) {
56
129
  const manifest = manifestText ? JSON.parse(manifestText) : { files: {} };
57
130
  const created = [];
58
131
  const updated = [];
132
+ // What ALP last wrote of role-skills.json, before this run's update of it (offerRoleSkills).
133
+ const seededRoles = manifest.files['role-skills.json'];
59
134
  for (const [name, content] of Object.entries(shipped).sort(([a], [b]) => a.localeCompare(b))) {
60
135
  const target = path.join(home, ...name.split('/'));
61
136
  const current = await optional(target);
@@ -64,23 +139,38 @@ export async function seedLibrary(home, options = {}) {
64
139
  // A file the user made under a shipped name stays theirs.
65
140
  if (current !== undefined) continue;
66
141
  await mkdir(path.dirname(target), { recursive: true });
67
- await writeFile(target, content, { flag: 'wx' }).catch(error => { if (error.code !== 'EEXIST') throw error; });
142
+ const wrote = await writeFile(target, content, { flag: 'wx' }).then(() => true, error => { if (error.code !== 'EEXIST') throw error; return false; });
143
+ if (wrote) await keepExecutable(name, target, content);
68
144
  manifest.files[name] = sha(content);
69
145
  created.push(name);
70
146
  } else if (current !== undefined && sha(current) === seeded && seeded !== sha(content)) {
71
147
  await writeFile(target, content);
148
+ await keepExecutable(name, target, content);
72
149
  manifest.files[name] = sha(content);
73
150
  updated.push(name);
74
151
  }
75
152
  // Missing after seeding: the user deleted it. Changed: the user edited it. Both are kept.
76
153
  }
77
- if (created.length || updated.length || manifestText === undefined) {
154
+ const offer = options.offerRoleSkills && shipped['role-skills.json'] !== undefined
155
+ ? await offerRoleSkills(home, manifest, shipped['role-skills.json'], seededRoles)
156
+ : undefined;
157
+ if (created.length || updated.length || offer?.changed || manifestText === undefined) {
78
158
  await mkdir(home, { recursive: true });
79
159
  const temporary = `${manifestPath}.${randomUUID().slice(0, 8)}.tmp`;
80
160
  await writeFile(temporary, JSON.stringify(manifest, null, 2) + '\n');
81
161
  await moveFile(temporary, manifestPath);
82
162
  }
83
- return { created, updated };
163
+ return { created, updated, ...(options.offerRoleSkills ? { offered: offer?.added ?? [] } : {}) };
164
+ }
165
+
166
+ /**
167
+ * Bundles carry shipped templates as text, so a script's executable bit cannot travel with it: a
168
+ * shipped skill script that starts with `#!` is made executable where ALP writes it (Level 3
169
+ * resources; the validator holds shipped skills to UTF-8 text). Nothing runs it.
170
+ */
171
+ async function keepExecutable(name, target, content) {
172
+ if (process.platform === 'win32' || !/^skills\/[^/]+\/scripts\//.test(name) || !content.startsWith('#!')) return;
173
+ await chmod(target, 0o755);
84
174
  }
85
175
 
86
176
  const seeding = new Map();
@@ -105,7 +195,7 @@ export async function librarySkills(home, agent) {
105
195
  let roles;
106
196
  try { roles = JSON.parse(text); }
107
197
  catch (cause) { throw new AlpError('INVALID_LIBRARY', `${file}: ${cause.message}`, { cause }); }
108
- if (!roles || typeof roles !== 'object' || Array.isArray(roles)) throw new AlpError('INVALID_LIBRARY', `${file}: expected an object of role names to skill lists`);
198
+ if (!roles || typeof roles !== 'object' || Array.isArray(roles)) throw new AlpError('INVALID_LIBRARY', `${file}: expected an object of agent names to skill lists`);
109
199
  const names = roles[agent] ?? [];
110
200
  if (!Array.isArray(names) || !names.every(skillName)) throw new AlpError('INVALID_LIBRARY', `${file}: ${agent} must list skill directory names`);
111
201
  const skills = [];
package/src/models.js CHANGED
@@ -90,6 +90,30 @@ export function mergeCatalog(base, live) {
90
90
  });
91
91
  }
92
92
 
93
+ /** Every effort ALP knows; no catalog widens a model beyond these. */
94
+ export const EFFORTS = ['none', 'off', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'ultracode'];
95
+
96
+ /** @type {typeof MODELS | undefined} */
97
+ let liveRows;
98
+ /**
99
+ * The rows effort checks consult in this process (t-086c): alpd's runtime installs its live catalog
100
+ * here as it changes, and alp setup the cached one it read. Nothing here reads the network; without
101
+ * rows, MODELS serve. @param {typeof MODELS | undefined} rows
102
+ */
103
+ export function useLiveModels(rows) { liveRows = Array.isArray(rows) && rows.length ? rows : undefined; }
104
+ /** The live rows when this process has them, else MODELS. */
105
+ export const knownModels = () => liveRows ?? MODELS;
106
+ /**
107
+ * The row for a runtime-prefixed model id, its efforts kept to EFFORTS; undefined for a model no
108
+ * catalog lists (any effort in EFFORTS stays accepted for it). @param {string} id
109
+ */
110
+ export function knownModel(id) {
111
+ const row = knownModels().find(model => `${model.runtime}:${model.id}` === id);
112
+ if (!row) return undefined;
113
+ const efforts = (row.efforts ?? []).filter(effort => EFFORTS.includes(effort));
114
+ return { ...row, efforts, ...(row.effort && efforts.includes(row.effort) ? { effort: row.effort } : { effort: undefined }) };
115
+ }
116
+
93
117
  /** Where alpd caches the live catalog: ALP_HOME/cache/models.json. @param {string} home */
94
118
  export const catalogCacheFile = home => path.join(home, 'cache', 'models.json');
95
119
 
package/src/packaged.js CHANGED
@@ -1,21 +1,19 @@
1
- import { createHash } from 'node:crypto';
2
- import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
- import os from 'node:os';
1
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
4
2
  import path from 'node:path';
5
3
 
6
4
  /**
7
- * ALP runs either as npm scripts under Node (`node cli.js`, `node alpd.js`) or as one self-contained
8
- * executable (`alp`, built with `bun build --compile`, t-1e02). In the executable, `process.execPath`
9
- * is ALP itself: it cannot run a script path, and `-e code` is not evaluated. Every place that starts
10
- * another ALP process asks this module for the command instead of spawning `process.execPath`.
5
+ * How ALP starts its own processes, and where its bundle lives. ALP always runs under Node: from npm
6
+ * (`node cli.js`, `node alpd.js`) or from the ALP bundle (t-1807), which is the same npm install
7
+ * beside an official Node release, started by `bin/alp`:
11
8
  *
12
- * The executable's entry registers itself before importing anything else; the registration lives
13
- * on globalThis because alpd.js and the CLI each inline their own copy of this module.
9
+ * <app>/<version>/{bin/alp, node/bin/node, lib/node_modules/@anhlp/alp-cli, alp-bundle.json}
10
+ * <app>/current → <version> (install.sh and `alp update` move it)
11
+ *
12
+ * Paths that outlive this process (a launchd/systemd service, alpd's install record) name the bundle
13
+ * through `current`, so an update never leaves them on a removed version.
14
14
  */
15
15
 
16
- const KEY = Symbol.for('alp.packaged');
17
-
18
- /** Subcommands of the executable that run each ALP role (the npm CLI understands them too). */
16
+ /** Subcommands of `alp` that run each ALP role in that process (`alp daemon run`, `alp web serve`, `alp bridge acp`). */
19
17
  export const ROLE_ARGS = Object.freeze({
20
18
  daemon: Object.freeze(['daemon', 'run']),
21
19
  web: Object.freeze(['web', 'serve']),
@@ -24,34 +22,15 @@ export const ROLE_ARGS = Object.freeze({
24
22
  });
25
23
 
26
24
  /**
27
- * @typedef {{ path: string, sha256: string, size: number }} PackagedAsset
28
- * @typedef {{ version: string, assets?: Record<string, PackagedAsset>, roles?: Record<string, () => Promise<unknown>>, modules?: Record<string, () => Promise<unknown>> }} PackagedRegistration
29
- */
30
-
31
- /** Called once by the executable's entry. @param {PackagedRegistration} registration */
32
- export function registerPackaged(registration) {
33
- if (!registration || typeof registration.version !== 'string') throw new TypeError('registerPackaged needs a version');
34
- // assetDir rides along so dependency-free adapters (native-terminal.js) can reach the cache via globalThis alone.
35
- Object.defineProperty(globalThis, KEY, { value: Object.freeze({ ...registration, assetDir: () => assetDir() }), configurable: true, enumerable: false, writable: false });
36
- }
37
-
38
- /** The registration when this process is the ALP executable, else undefined. @returns {PackagedRegistration | undefined} */
39
- export function packagedInfo() { return /** @type {any} */ (globalThis)[KEY]; }
40
-
41
- /** Whether this process is the self-contained ALP executable. */
42
- export function isPackaged() { return packagedInfo() !== undefined; }
43
-
44
- /**
45
- * A string only ALP's executable carries: its generated entry embeds it, so discovery can tell ALP
46
- * from an unrelated native program that happens to be called `alp` without running it.
25
+ * Whether `file` is named like the `alp` command (alp, alp.exe, alp.cmd) rather than a script: an
26
+ * install record or service written by the single-file executable of 0.0.1-beta.5/6 names it, and the
27
+ * bundle's launcher keeps that name.
28
+ * @param {string} file
47
29
  */
48
- export const EXECUTABLE_MARKER = 'alp-standalone-executable:v1:2b6f0c1e';
30
+ export const isExecutableName = file => /^alp(\.exe|\.cmd)?$/i.test(file.split(/[\\/]/).pop() ?? '');
49
31
 
50
- /** Whether `file` is named like the ALP executable (alp, alp.exe). @param {string} file */
51
- export const isExecutableName = file => /^alp(\.exe)?$/i.test(file.split(/[\\/]/).pop() ?? '');
52
-
53
- /** Whether `file` is this process's own ALP executable, whatever it is called (alp-darwin-arm64, a rename). @param {unknown} file */
54
- export const isSelf = file => isPackaged() && typeof file === 'string' && samePath(file, process.execPath);
32
+ /** A file path that names a JavaScript entry rather than a command. @param {string} file */
33
+ export const isScript = file => /\.[cm]?js$/i.test(file);
55
34
 
56
35
  /** The canonical form of a path: symlinks resolved when it exists, case-folded where the filesystem usually is. @param {string} file */
57
36
  const canonical = file => {
@@ -60,12 +39,9 @@ const canonical = file => {
60
39
  return process.platform === 'darwin' || process.platform === 'win32' ? resolved.toLowerCase() : resolved;
61
40
  };
62
41
 
63
- /** Whether two paths name the same file (a symlink such as ~/.alp/bin/alp, or a differently cased path on macOS/Windows). @param {string} a @param {string} b */
42
+ /** Whether two paths name the same file (a symlink, or a differently cased path on macOS/Windows). @param {string} a @param {string} b */
64
43
  export const samePath = (a, b) => canonical(a) === canonical(b);
65
44
 
66
- /** A file path that names a JavaScript entry rather than an executable. @param {string} file */
67
- export const isScript = file => /\.[cm]?js$/i.test(file);
68
-
69
45
  /** The role's argument prefix. @param {keyof typeof ROLE_ARGS} role */
70
46
  function roleArgs(role) {
71
47
  const args = ROLE_ARGS[role];
@@ -74,20 +50,68 @@ function roleArgs(role) {
74
50
  }
75
51
 
76
52
  /**
77
- * The command that starts ALP's `role` from this process: the executable's subcommand when packaged,
78
- * else `script` under this Node, exactly as before.
53
+ * @typedef {{ root: string, version: string, platform: string, app: string, current?: string }} BundleInfo
54
+ * root: the bundle directory (real path); app: its parent; current: `<app>/current` when it points at root.
55
+ */
56
+
57
+ const bundles = new Map();
58
+
59
+ /**
60
+ * The ALP bundle this Node belongs to, or undefined for any other Node (an npm install).
61
+ * @param {string} [execPath]
62
+ * @returns {BundleInfo | undefined}
63
+ */
64
+ export function bundleInfo(execPath = process.execPath) {
65
+ if (bundles.has(execPath)) return bundles.get(execPath);
66
+ let info;
67
+ try {
68
+ const real = realpathSync(execPath);
69
+ // node/bin/node on macOS and Linux, node/node.exe on Windows.
70
+ const nodeDir = path.basename(path.dirname(real)) === 'bin' ? path.dirname(path.dirname(real)) : path.dirname(real);
71
+ const root = path.dirname(nodeDir);
72
+ if (path.basename(nodeDir) === 'node') {
73
+ const manifest = JSON.parse(readFileSync(path.join(root, 'alp-bundle.json'), 'utf8'));
74
+ if (manifest?.name === 'alp' && typeof manifest.version === 'string') {
75
+ const app = path.dirname(root);
76
+ const current = path.join(app, 'current');
77
+ info = { root, version: manifest.version, platform: String(manifest.platform ?? ''), app, ...(existsSync(current) && samePath(current, root) ? { current } : {}) };
78
+ }
79
+ }
80
+ } catch {}
81
+ bundles.set(execPath, info);
82
+ return info;
83
+ }
84
+
85
+ /**
86
+ * `file` named through `<app>/current` when it lies inside this process's bundle and `current` points
87
+ * at that bundle; otherwise `file` unchanged. For paths written to disk for later processes.
88
+ * @param {string} file
89
+ * @param {{ bundle?: BundleInfo | undefined }} [options]
90
+ */
91
+ export function stablePath(file, { bundle = bundleInfo() } = {}) {
92
+ if (!bundle?.current) return file;
93
+ let real;
94
+ try { real = realpathSync(file); } catch { return file; }
95
+ const relative = path.relative(bundle.root, real);
96
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return file;
97
+ return path.join(bundle.current, relative);
98
+ }
99
+
100
+ /**
101
+ * The command that starts ALP's `role` from this process: `script` under this Node.
79
102
  * @param {keyof typeof ROLE_ARGS} role
80
103
  * @param {{ script: string, args?: string[] }} options
81
104
  * @returns {{ command: string, args: string[] }}
82
105
  */
83
106
  export function selfCommand(role, { script, args = [] }) {
84
- if (isPackaged()) return { command: process.execPath, args: [...roleArgs(role), ...args] };
107
+ roleArgs(role);
85
108
  return { command: process.execPath, args: [script, ...args] };
86
109
  }
87
110
 
88
111
  /**
89
112
  * The command that runs an `entry` found on disk (an install record, a service definition, a CLI
90
- * on PATH): a script runs under `execPath`; an executable runs its own role subcommand.
113
+ * on PATH): a script runs under `execPath`; an `alp` command (the bundle's launcher, or what a
114
+ * 0.0.1-beta.5/6 single-file install recorded) runs its role subcommand.
91
115
  * @param {string} entry
92
116
  * @param {keyof typeof ROLE_ARGS} role
93
117
  * @param {string[]} [args]
@@ -96,160 +120,19 @@ export function selfCommand(role, { script, args = [] }) {
96
120
  * @returns {{ command: string, args: string[] }}
97
121
  */
98
122
  export function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
99
- // Only a file named alp/alp.exe, or this very executable under any name, is native; anything else
100
- // (alpd.js, alpd.ts, a launcher) is a script.
101
- if (scriptOnly || isScript(entry) || !(isExecutableName(entry) || isSelf(entry))) {
102
- // The executable cannot run a script itself; a script entry then needs a real Node.
103
- if (isPackaged() && execPath === process.execPath) return { command: 'node', args: [entry, ...args] };
104
- return { command: execPath, args: [entry, ...args] };
105
- }
123
+ if (scriptOnly || isScript(entry) || !isExecutableName(entry)) return { command: execPath, args: [entry, ...args] };
106
124
  return { command: entry, args: [...roleArgs(role), ...args] };
107
125
  }
108
126
 
109
127
  /**
110
- * The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows)
111
- * with this process's runtime. The executable runs it as Bun does when BUN_BE_BUN is set.
128
+ * The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows) with this Node.
112
129
  * @param {string} script
113
130
  * @param {string[]} [args]
114
131
  * @returns {{ command: string, args: string[], env?: Record<string, string> }}
115
132
  */
116
133
  export function scriptCommand(script, args = []) {
117
- if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: '1' } };
118
134
  return { command: process.execPath, args: [script, ...args] };
119
135
  }
120
136
 
121
- /** The ALP executable's path when this process is it, else undefined. */
122
- export function executablePath() { return isPackaged() ? process.execPath : undefined; }
123
-
124
- /** Where this process's own entry lives: the executable when packaged, else `script`. @param {string} script */
125
- export function selfEntry(script) { return isPackaged() ? process.execPath : script; }
126
-
127
- const sha256 = (/** @type {Buffer} */ bytes) => createHash('sha256').update(bytes).digest('hex');
128
- const MARKER = '.alp-assets.json';
129
-
130
- /** The directory the executable's assets are extracted to. @param {string} version @param {NodeJS.ProcessEnv} [env] */
131
- export function assetCacheDir(version, env = process.env) {
132
- if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) throw new TypeError(`Invalid ALP version for the asset cache: ${JSON.stringify(version)}`);
133
- const home = env.ALP_HOME ? path.resolve(env.ALP_HOME) : path.join(os.homedir(), '.alp');
134
- return path.join(home, 'cache', version);
135
- }
136
-
137
- /** The manifest digest the marker records, so a changed build never reuses an older extraction. @param {Record<string, PackagedAsset>} assets */
138
- const manifestDigest = assets => sha256(Buffer.from(JSON.stringify(Object.keys(assets).sort().map(name => [name, assets[name].sha256, assets[name].size]))));
139
-
140
- /** Rejects names that would leave the cache directory. @param {string} name */
141
- function assertAssetName(name) {
142
- if (!name || path.isAbsolute(name) || name.split(/[\\/]/).some(part => part === '..' || part === '' || part === '.') || name === MARKER) throw new Error(`Invalid packaged asset name: ${JSON.stringify(name)}`);
143
- }
144
-
145
- /** A private directory we own, not a symlink. @param {string} directory */
146
- function assertPrivate(directory) {
147
- const info = lstatSync(directory);
148
- if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache is not a directory: ${directory}`);
149
- if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)) throw new Error(`ALP asset cache must be private to the current user (0700): ${directory}`);
150
- }
151
-
152
- /** The cache parent (<ALP_HOME>/cache): a real directory of ours that nobody else may write into. @param {string} directory */
153
- function assertParent(directory) {
154
- const info = lstatSync(directory);
155
- if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache parent is not a directory: ${directory}`);
156
- if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) throw new Error(`ALP asset cache parent must belong to the current user and not be group- or world-writable: ${directory}`);
157
- }
158
-
159
- /** Whether `directory` holds exactly this manifest's extraction: every file's size and sha256 match. */
160
- function extracted(/** @type {string} */ directory, /** @type {string} */ digest, /** @type {Record<string, PackagedAsset>} */ assets) {
161
- try {
162
- if (JSON.parse(readFileSync(path.join(directory, MARKER), 'utf8')).digest !== digest) return false;
163
- return Object.entries(assets).every(([name, asset]) => {
164
- const file = path.join(directory, name);
165
- const info = lstatSync(file);
166
- return info.isFile() && info.size === asset.size && sha256(readFileSync(file)) === asset.sha256;
167
- });
168
- } catch { return false; }
169
- }
170
-
171
- const STAGING = /^(.+)\.tmp-(\d+)-(\d+)$/;
172
- const STALE_MS = 60 * 60 * 1000;
173
- const SWEEP_MIN_MS = 10 * 60 * 1000;
174
-
175
- /** Removes staging directories another process left behind (it crashed, or was killed mid-extraction). @param {string} parent */
176
- function sweepStaging(parent) {
177
- let names;
178
- try { names = readdirSync(parent); } catch { return; }
179
- for (const name of names) {
180
- const match = STAGING.exec(name);
181
- if (!match) continue;
182
- const pid = Number(match[2]);
183
- if (pid === process.pid) continue;
184
- const age = Date.now() - Number(match[3]);
185
- // Another pid namespace (a bind-mounted ALP_HOME) may hold a live extractor this one cannot see,
186
- // so even a dead-looking pid's staging is kept for a few minutes; past an hour nothing is running.
187
- if (age < SWEEP_MIN_MS) continue;
188
- let alive = false;
189
- try { process.kill(pid, 0); alive = true; } catch (error) { alive = /** @type {any} */ (error)?.code === 'EPERM'; }
190
- if (alive && age < STALE_MS) continue;
191
- try { rmSync(path.join(parent, name), { recursive: true, force: true }); } catch {}
192
- }
193
- }
194
-
195
- /**
196
- * The directory holding the executable's embedded assets (templates, the web app, the native
197
- * terminal helper), extracted once per version to `<ALP_HOME or ~/.alp>/cache/<version>/` and
198
- * checked against the build's sha256 manifest. Undefined when not packaged: callers then use the
199
- * files beside their scripts, as before.
200
- * @param {{ env?: NodeJS.ProcessEnv, info?: PackagedRegistration }} [options]
201
- * @returns {string | undefined}
202
- */
203
- export function assetDir({ env = process.env, info = packagedInfo() } = {}) {
204
- if (!info) return undefined;
205
- const assets = info.assets ?? {};
206
- const directory = assetCacheDir(info.version, env);
207
- const digest = manifestDigest(assets);
208
- // Checked once per process and directory; later calls (every template read) reuse the answer.
209
- const key = `${directory}\0${digest}`;
210
- if (verified.has(key) && existsSync(path.join(directory, MARKER))) return directory;
211
- const result = extract(directory, digest, assets, info.version);
212
- verified.add(key);
213
- return result;
214
- }
215
-
216
- const verified = new Set();
217
-
218
- /** @param {string} directory @param {string} digest @param {Record<string, PackagedAsset>} assets @param {string} version */
219
- function extract(directory, digest, assets, version) {
220
- const parent = path.dirname(directory);
221
- mkdirSync(parent, { recursive: true, mode: 0o700 });
222
- assertParent(parent);
223
- sweepStaging(parent);
224
- if (existsSync(directory)) {
225
- assertPrivate(directory);
226
- if (extracted(directory, digest, assets)) return directory;
227
- }
228
- const staging = `${directory}.tmp-${process.pid}-${Date.now()}`;
229
- mkdirSync(staging, { mode: 0o700 });
230
- try {
231
- for (const [name, asset] of Object.entries(assets)) {
232
- assertAssetName(name);
233
- const bytes = readFileSync(asset.path);
234
- if (bytes.length !== asset.size || sha256(bytes) !== asset.sha256) throw new Error(`Packaged asset ${name} does not match its manifest`);
235
- const target = path.join(staging, name);
236
- mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
237
- writeFileSync(target, bytes, { mode: 0o600 });
238
- if (/(^|\/)terminal-owner(\.exe)?$/.test(name)) chmodSync(target, 0o700);
239
- }
240
- writeFileSync(path.join(staging, MARKER), JSON.stringify({ version, digest }), { mode: 0o600 });
241
- // Another ALP process may have finished the same extraction first; its copy is equivalent.
242
- if (existsSync(directory)) {
243
- assertPrivate(directory);
244
- if (extracted(directory, digest, assets)) { rmSync(staging, { recursive: true, force: true }); return directory; }
245
- rmSync(directory, { recursive: true, force: true });
246
- }
247
- renameSync(staging, directory);
248
- if (!extracted(directory, digest, assets)) throw new Error(`ALP asset cache ${directory} is incomplete after extraction`);
249
- } catch (error) {
250
- rmSync(staging, { recursive: true, force: true });
251
- if (existsSync(directory) && extracted(directory, digest, assets)) return directory;
252
- throw error;
253
- }
254
- return directory;
255
- }
137
+ /** Where this process's own entry lives, for records that later processes read: `script`, through `current` in a bundle. @param {string} script */
138
+ export function selfEntry(script) { return stablePath(script); }