@anhlp/alp-core 0.0.1-beta.7 → 0.0.1-beta.9

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.js +2 -2
  2. package/dist/library-edit.d.ts +51 -2
  3. package/dist/library-edit.js +160 -8
  4. package/dist/library.d.ts +14 -1
  5. package/dist/library.js +73 -5
  6. package/dist/models.d.ts +35 -0
  7. package/dist/models.js +17 -1
  8. package/dist/packaged.d.ts +45 -12
  9. package/dist/packaged.js +46 -5
  10. package/dist/packs.d.ts +57 -0
  11. package/dist/packs.js +247 -0
  12. package/dist/permissions.d.ts +3 -2
  13. package/dist/permissions.js +6 -3
  14. package/dist/profiles.js +3 -3
  15. package/dist/providers.d.ts +2 -4
  16. package/dist/providers.js +20 -4
  17. package/dist/skill-validate.d.ts +85 -0
  18. package/dist/skill-validate.js +298 -0
  19. package/dist/upgrade.d.ts +10 -0
  20. package/dist/upgrade.js +112 -6
  21. package/dist/user-settings.d.ts +2 -0
  22. package/dist/user-settings.js +40 -1
  23. package/dist/validation.d.ts +1 -0
  24. package/dist/validation.js +16 -10
  25. package/package.json +18 -2
  26. package/src/bridges.js +3 -2
  27. package/src/library-edit.js +170 -8
  28. package/src/library.js +96 -6
  29. package/src/models.js +24 -0
  30. package/src/packaged.js +77 -8
  31. package/src/packs.js +246 -0
  32. package/src/permissions.d.ts +3 -2
  33. package/src/permissions.js +13 -3
  34. package/src/profiles.js +4 -4
  35. package/src/providers.js +20 -5
  36. package/src/resolver.js +1 -1
  37. package/src/skill-validate.js +287 -0
  38. package/src/upgrade.js +54 -6
  39. package/src/user-settings.d.ts +2 -0
  40. package/src/user-settings.js +51 -1
  41. package/src/validation.d.ts +1 -0
  42. package/src/validation.js +21 -12
  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/packaged.js CHANGED
@@ -13,10 +13,35 @@ import path from 'node:path';
13
13
  * through `current`, so an update never leaves them on a removed version.
14
14
  */
15
15
 
16
- /** Subcommands of `alp` that run each ALP role in that process (`alp daemon run`, `alp web serve`, `alp bridge acp`). */
16
+ /**
17
+ * The native alpd (t-81b0.9): alpd compiled with `bun build --compile` into one executable, shipped as
18
+ * `<bundle>/bin/alpd` beside the bundle's Node. Only alpd is native; the `alp` CLI still runs on the
19
+ * bundle's Node. Its entry (packages/daemon/src/native-entry.ts) registers itself here before alpd loads:
20
+ * `modules` holds what alpd would otherwise import by a computed name (the Claude Agent SDK); `distDir`
21
+ * names the bundle's @anhlp/alp-cli dist, where the terminal helper is (undefined outside a bundle).
22
+ * @typedef {{ modules: { claudeAgentSdk?: () => Promise<any> }, distDir?: () => string | undefined }} NativeDaemon
23
+ */
24
+ const NATIVE = Symbol.for('alp.nativeDaemon');
25
+
26
+ /** Registers this process as the native alpd. Only native-entry.ts calls it. @param {NativeDaemon} native */
27
+ export function registerNativeDaemon(native) { /** @type {any} */ (globalThis)[NATIVE] = native; }
28
+
29
+ /** The native alpd's registration when this process is the native alpd, else undefined. @returns {NativeDaemon | undefined} */
30
+ export function nativeDaemon() { return /** @type {any} */ (globalThis)[NATIVE]; }
31
+
32
+ /** The native alpd's file name on this platform. */
33
+ export const NATIVE_DAEMON = process.platform === 'win32' ? 'alpd.exe' : 'alpd';
34
+
35
+ /** Whether `file` is named like the native alpd (alpd, alpd.exe). @param {string} file */
36
+ export const isNativeDaemonName = file => /^alpd(\.exe)?$/i.test(file.split(/[\\/]/).pop() ?? '');
37
+
38
+ /** Whether `file` is an ALP bundle's native alpd: `<bundle>/bin/alpd` beside alp-bundle.json. @param {string} file */
39
+ export const isBundleDaemon = file => isNativeDaemonName(file) && path.basename(path.dirname(file)) === 'bin' && existsSync(path.join(path.dirname(path.dirname(file)), 'alp-bundle.json'));
40
+
41
+ /** Subcommands of `alp` that run each ALP role in that process (`alp daemon run`, `alp dashboard serve`, `alp bridge acp`). */
17
42
  export const ROLE_ARGS = Object.freeze({
18
43
  daemon: Object.freeze(['daemon', 'run']),
19
- web: Object.freeze(['web', 'serve']),
44
+ dashboard: Object.freeze(['dashboard', 'serve']),
20
45
  'bridge-acp': Object.freeze(['bridge', 'acp']),
21
46
  'bridge-antigravity': Object.freeze(['bridge', 'antigravity']),
22
47
  });
@@ -66,10 +91,11 @@ export function bundleInfo(execPath = process.execPath) {
66
91
  let info;
67
92
  try {
68
93
  const real = realpathSync(execPath);
69
- // node/bin/node on macOS and Linux, node/node.exe on Windows.
94
+ // node/bin/node on macOS and Linux, node/node.exe on Windows; or the native alpd, bin/alpd.
95
+ const native = isNativeDaemonName(real) && path.basename(path.dirname(real)) === 'bin';
70
96
  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') {
97
+ const root = native ? nodeDir : path.dirname(nodeDir);
98
+ if (native || path.basename(nodeDir) === 'node') {
73
99
  const manifest = JSON.parse(readFileSync(path.join(root, 'alp-bundle.json'), 'utf8'));
74
100
  if (manifest?.name === 'alp' && typeof manifest.version === 'string') {
75
101
  const app = path.dirname(root);
@@ -82,6 +108,26 @@ export function bundleInfo(execPath = process.execPath) {
82
108
  return info;
83
109
  }
84
110
 
111
+ /** The bundle's own Node executable. @param {BundleInfo} bundle */
112
+ export const bundleNode = bundle => path.join(bundle.root, 'node', process.platform === 'win32' ? 'node.exe' : 'bin/node');
113
+
114
+ /** The bundle's native alpd, whether or not it exists. @param {BundleInfo} bundle */
115
+ export const bundleDaemon = bundle => path.join(bundle.root, 'bin', NATIVE_DAEMON);
116
+
117
+ /** Where @anhlp/alp-cli's dist lies in the bundle (alpd.js, the terminal helper). @param {BundleInfo} bundle */
118
+ export const bundleDist = bundle => path.join(bundle.root, 'lib', 'node_modules', '@anhlp', 'alp-cli', 'dist');
119
+
120
+ /**
121
+ * The Node that runs JavaScript for this process: process.execPath, except in the native alpd, which
122
+ * cannot run a script (`spawn(execPath, [script])` would start alpd again, and `-e` is not evaluated):
123
+ * there it is the bundle's Node, or `node` on PATH for a native alpd outside a bundle.
124
+ */
125
+ export function nodeExecutable() {
126
+ if (!nativeDaemon()) return process.execPath;
127
+ const bundle = bundleInfo();
128
+ return bundle ? bundleNode(bundle) : 'node';
129
+ }
130
+
85
131
  /**
86
132
  * `file` named through `<app>/current` when it lies inside this process's bundle and `current` points
87
133
  * at that bundle; otherwise `file` unchanged. For paths written to disk for later processes.
@@ -105,6 +151,11 @@ export function stablePath(file, { bundle = bundleInfo() } = {}) {
105
151
  */
106
152
  export function selfCommand(role, { script, args = [] }) {
107
153
  roleArgs(role);
154
+ // The native alpd is its own entry: it starts itself with its options only, never a script path.
155
+ if (nativeDaemon()) {
156
+ if (role !== 'daemon') throw new Error(`The native alpd cannot start ALP's ${role}`);
157
+ return { command: process.execPath, args: [...args] };
158
+ }
108
159
  return { command: process.execPath, args: [script, ...args] };
109
160
  }
110
161
 
@@ -120,6 +171,9 @@ export function selfCommand(role, { script, args = [] }) {
120
171
  * @returns {{ command: string, args: string[] }}
121
172
  */
122
173
  export function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
174
+ // The native alpd (t-81b0.9) runs on its own, with alpd's options: only a bundle's bin/alpd, so an
175
+ // extensionless script named alpd (an npm .bin shim, a source checkout) still runs under execPath.
176
+ if (!scriptOnly && role === 'daemon' && isBundleDaemon(entry)) return { command: entry, args: [...args] };
123
177
  if (scriptOnly || isScript(entry) || !isExecutableName(entry)) return { command: execPath, args: [entry, ...args] };
124
178
  return { command: entry, args: [...roleArgs(role), ...args] };
125
179
  }
@@ -131,8 +185,23 @@ export function entryCommand(entry, role, args = [], execPath = process.execPath
131
185
  * @returns {{ command: string, args: string[], env?: Record<string, string> }}
132
186
  */
133
187
  export function scriptCommand(script, args = []) {
134
- return { command: process.execPath, args: [script, ...args] };
188
+ return { command: nodeExecutable(), args: [script, ...args] };
135
189
  }
136
190
 
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); }
191
+ /**
192
+ * Where this process's own entry lives, for records that later processes read: `script`, through
193
+ * `current` in a bundle; the native alpd's own executable in the native alpd.
194
+ * @param {string} script
195
+ */
196
+ export function selfEntry(script) { return stablePath(nativeDaemon() ? process.execPath : script); }
197
+
198
+ /**
199
+ * What starts alpd for this `alp`: the bundle's native alpd when the bundle ships one, else `script`
200
+ * (alpd.js), each named through `current`. ALP_NATIVE_DAEMON=0 keeps alpd on the bundle's Node.
201
+ * @param {string} script alpd.js
202
+ * @param {{ bundle?: BundleInfo | undefined, env?: NodeJS.ProcessEnv }} [options]
203
+ */
204
+ export function daemonEntry(script, { bundle = bundleInfo(), env = process.env } = {}) {
205
+ const native = bundle && env.ALP_NATIVE_DAEMON !== '0' ? bundleDaemon(bundle) : undefined;
206
+ return stablePath(native && existsSync(native) ? native : script, { bundle });
207
+ }
package/src/packs.js ADDED
@@ -0,0 +1,246 @@
1
+ import { chmod, lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { moveFile } from './atomic.js';
5
+ import { AlpError } from './errors.js';
6
+ import { assertNoSymlinks } from './safe-path.js';
7
+ import { seedLibrary } from './library.js';
8
+ import { BASES, validatePermissions } from './permissions.js';
9
+ import { validateSkill } from './skill-validate.js';
10
+ import { shippedTemplateRoot } from './template-path.js';
11
+ import { validateTeam } from './teams.js';
12
+ import { validateAgentConfig } from './validation.js';
13
+
14
+ /**
15
+ * Optional packs (skill system v2): groups of specialist skills, custom agents and teams that ship
16
+ * in ALP's templates under packs/<id>/ but are never seeded. A user opts in with `alp pack install`,
17
+ * which copies the entries into the library or a project's .alp/ like any entry the user made
18
+ * there: an entry that already exists is kept, whatever it holds, so an update or a reinstall never
19
+ * overwrites the user's version. Nothing is assigned to a role unless asked (`assign`), nothing is
20
+ * installed or run besides copying files, and no dependency is fetched.
21
+ *
22
+ * packs/<id>/pack.json { label, description, skills?, agents?, teams?, assign?, permissions? }
23
+ * packs/<id>/skills/<name>/... packs/<id>/agents/<name>/... packs/<id>/teams/<name>/...
24
+ */
25
+
26
+ const KINDS = ['skills', 'agents', 'teams'];
27
+ const PACK_KEYS = ['label', 'description', ...KINDS, 'assign', 'permissions'];
28
+ const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
29
+ const fail = (code, message) => { throw new AlpError(code, message); };
30
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
31
+
32
+ /** Every shipped pack file, as packs/<id>/<path> -> text: from a bundle's templates or the package. */
33
+ async function shippedPackFiles({ templates } = {}) {
34
+ if (templates) return Object.fromEntries(Object.entries(templates).filter(([name]) => name.startsWith('packs/')));
35
+ const root = new URL('packs/', shippedTemplateRoot());
36
+ const files = {};
37
+ const walk = async relative => {
38
+ let entries;
39
+ try { entries = await readdir(new URL(relative, root), { withFileTypes: true }); }
40
+ catch (error) { if (error.code === 'ENOENT') return; throw error; }
41
+ for (const entry of entries) {
42
+ if (entry.isDirectory()) await walk(`${relative}${entry.name}/`);
43
+ else if (entry.isFile()) files[`packs/${relative}${entry.name}`] = await readFile(new URL(`${relative}${entry.name}`, root), 'utf8');
44
+ }
45
+ };
46
+ await walk('');
47
+ return files;
48
+ }
49
+
50
+ /** Checks a pack.json against the files the pack holds. */
51
+ export function validatePack(id, manifest, files) {
52
+ const where = `packs/${id}/pack.json`;
53
+ const bad = message => fail('INVALID_PACK', `${where}: ${message}`);
54
+ if (!object(manifest)) bad('expected a JSON object');
55
+ for (const key of Object.keys(manifest)) if (!PACK_KEYS.includes(key)) bad(`unknown key '${key}'; expected ${PACK_KEYS.join(', ')}`);
56
+ for (const key of ['label', 'description']) if (typeof manifest[key] !== 'string' || !manifest[key].trim()) bad(`${key} must be nonempty text`);
57
+ for (const kind of KINDS) {
58
+ const names = manifest[kind] ?? [];
59
+ if (!Array.isArray(names) || !names.every(name => typeof name === 'string' && NAME.test(name))) bad(`${kind} must list entry names`);
60
+ const main = { skills: 'SKILL.md', agents: 'AGENT.md', teams: 'team.json' }[kind];
61
+ for (const name of names) if (files[`packs/${id}/${kind}/${name}/${main}`] === undefined) bad(`${kind} names '${name}', which has no ${kind}/${name}/${main}`);
62
+ }
63
+ if (!(manifest.skills?.length || manifest.agents?.length || manifest.teams?.length)) bad('a pack holds at least one skill, agent or team');
64
+ if (manifest.assign !== undefined) {
65
+ if (!object(manifest.assign)) bad('assign must map roles to skills');
66
+ for (const [role, skills] of Object.entries(manifest.assign)) {
67
+ if (!Array.isArray(skills) || !skills.every(skill => (manifest.skills ?? []).includes(skill))) bad(`assign.${role} may name only this pack's skills`);
68
+ }
69
+ }
70
+ if (manifest.permissions !== undefined) {
71
+ if (!object(manifest.permissions)) bad('permissions must map agents to a base mode');
72
+ for (const [agent, base] of Object.entries(manifest.permissions)) {
73
+ if (!(manifest.agents ?? []).includes(agent)) bad(`permissions names '${agent}', which is not one of this pack's agents`);
74
+ if (!BASES.includes(base)) bad(`permissions.${agent} must be one of ${BASES.join(', ')}`);
75
+ }
76
+ }
77
+ return manifest;
78
+ }
79
+
80
+ /**
81
+ * The packs ALP ships.
82
+ * @returns {Promise<Array<{ id: string, label: string, description: string, skills: string[], agents: string[], teams: string[], assign: Record<string, string[]>, permissions: Record<string, string> }>>}
83
+ */
84
+ export async function listPacks(options = {}) {
85
+ const files = await shippedPackFiles(options);
86
+ const ids = [...new Set(Object.keys(files).filter(name => /^packs\/[^/]+\/pack\.json$/.test(name)).map(name => name.split('/')[1]))].sort();
87
+ return ids.map(id => {
88
+ let manifest;
89
+ try { manifest = JSON.parse(files[`packs/${id}/pack.json`]); }
90
+ catch (cause) { throw new AlpError('INVALID_PACK', `packs/${id}/pack.json: ${cause.message}`, { cause }); }
91
+ validatePack(id, manifest, files);
92
+ return { id, label: manifest.label, description: manifest.description, skills: manifest.skills ?? [], agents: manifest.agents ?? [], teams: manifest.teams ?? [], assign: manifest.assign ?? {}, permissions: manifest.permissions ?? {} };
93
+ });
94
+ }
95
+
96
+ const present = target => lstat(target).then(() => true, error => { if (error.code === 'ENOENT') return false; throw error; });
97
+
98
+ async function writeJsonAtomic(file, value) {
99
+ await mkdir(path.dirname(file), { recursive: true });
100
+ const temporary = `${file}.${randomUUID().slice(0, 8)}.tmp`;
101
+ await writeFile(temporary, JSON.stringify(value, null, 2) + '\n');
102
+ await moveFile(temporary, file);
103
+ }
104
+
105
+ /**
106
+ * Installs a pack into the library (`scope: 'library'`) or a project's .alp/ (`scope: 'project'`).
107
+ * Each entry is written to a temporary directory, checked (skills strictly, agent.json and team.json
108
+ * by their schemas), then renamed into place; an entry of that name already there is kept as is.
109
+ * `assign` (library only) adds the pack's suggested skills to roles in role-skills.json; the
110
+ * permissions a pack's agents need (an advisor's read-only cap) are added to that scope's settings
111
+ * only when the agent has no entry there, and a different entry is reported, never changed.
112
+ * @param {string} id
113
+ * @param {{ scope: 'library' | 'project', root?: string, library?: string, assign?: boolean, templates?: Record<string, string> }} options
114
+ */
115
+ export async function installPack(id, { scope, root, library, assign = false, templates } = {}) {
116
+ if (typeof id !== 'string' || !NAME.test(id)) fail('INVALID_NAME', `'${id}' is not a pack name`);
117
+ const packs = await listPacks({ templates });
118
+ const pack = packs.find(candidate => candidate.id === id) ?? fail('NOT_FOUND', `No pack '${id}'; packs are ${packs.map(candidate => candidate.id).join(', ')}`);
119
+ if (scope !== 'library' && scope !== 'project') fail('INVALID_SCOPE', 'Scope must be library or project');
120
+ if (scope === 'library' && !library) fail('INVALID_SCOPE', 'No library: ALP_HOME is not set');
121
+ if (scope === 'project' && !root) fail('INVALID_SCOPE', 'No project directory');
122
+ if (assign && scope !== 'library') fail('INVALID_SCOPE', 'Only the library assigns skills to roles (role-skills.json); in a project, name the skills in a project agent: alp agent edit <role> --project --skills a,b');
123
+ // The core skills a pack's agents name live in the library.
124
+ if (library) await seedLibrary(library, templates ? { templates } : {});
125
+ // Everything is written below the scope's real directory, through no symbolic link: a project's .alp
126
+ // comes with its repository, and a link there (to the user's home, say) must not redirect a write.
127
+ const given = scope === 'library' ? library : path.resolve(root);
128
+ const scopeRoot = await realpath(given);
129
+ const inScope = scope === 'library' ? '' : '.alp';
130
+ const base = path.join(scopeRoot, inScope);
131
+ // Paths are reported below the directory the caller named (macOS's /var, not /private/var).
132
+ const shown = (kind, name) => path.join(given, inScope, kind, name);
133
+ const guard = relative => assertNoSymlinks(scopeRoot, path.join(inScope, relative));
134
+ await guard('.');
135
+ // Preflight every file this install may write, so a refused link stops it before anything is written.
136
+ for (const kind of KINDS) if (pack[kind].length) await guard(kind);
137
+ if (Object.keys(pack.permissions).length) await guard('settings.json');
138
+ if (assign) await guard('role-skills.json');
139
+ await mkdir(base, { recursive: true, ...(scope === 'library' ? { mode: 0o700 } : {}) });
140
+ const files = await shippedPackFiles({ templates });
141
+ for (const file of Object.keys(files)) {
142
+ const parts = file.split('/');
143
+ if (parts.some(part => !part || part === '.' || part === '..' || !/^[\w.@+-]+$/.test(part))) fail('INVALID_PACK', `${file}: a pack file path must be plain relative names`);
144
+ }
145
+ const installed = [];
146
+ const kept = [];
147
+ for (const kind of KINDS) {
148
+ for (const name of pack[kind]) {
149
+ const target = path.join(base, kind, name);
150
+ await guard(kind);
151
+ // An entry there already, a link included, is the user's: never written through.
152
+ if (await present(target)) { kept.push({ kind, name, path: shown(kind, name) }); continue; }
153
+ const prefix = `packs/${id}/${kind}/${name}/`;
154
+ // Staged outside the kind's directory, under the entry's own name, so no listing sees it half-written.
155
+ const stagingName = `.alp-pack-${randomUUID().slice(0, 8)}.tmp`;
156
+ const stagingRoot = path.join(base, stagingName);
157
+ const staging = path.join(stagingRoot, name);
158
+ await guard(stagingName);
159
+ try {
160
+ await mkdir(stagingRoot, { recursive: false, ...(scope === 'library' ? { mode: 0o700 } : {}) });
161
+ for (const [file, content] of Object.entries(files).filter(([file]) => file.startsWith(prefix))) {
162
+ const relative = file.slice(prefix.length);
163
+ const destination = path.join(staging, ...relative.split('/'));
164
+ await mkdir(path.dirname(destination), { recursive: true, ...(scope === 'library' ? { mode: 0o700 } : {}) });
165
+ // A new file in a directory made just now: never one that exists, or a link.
166
+ await writeFile(destination, content, { flag: 'wx' });
167
+ // Bundles carry templates as text; a script's executable bit follows its #! line.
168
+ if (process.platform !== 'win32' && relative.startsWith('scripts/') && content.startsWith('#!')) await chmod(destination, 0o755);
169
+ }
170
+ if (kind === 'skills') {
171
+ const { errors } = await validateSkill(staging, { mode: 'strict' });
172
+ if (errors.length) fail('INVALID_PACK', `packs/${id}/skills/${name}: ${errors.map(finding => finding.message).join('; ')}`);
173
+ }
174
+ if (kind === 'agents') {
175
+ const config = await readFile(path.join(staging, 'agent.json'), 'utf8').then(JSON.parse, error => { if (error.code === 'ENOENT') return {}; throw error; });
176
+ validateAgentConfig(config, `${prefix}agent.json`);
177
+ }
178
+ if (kind === 'teams') validateTeam(JSON.parse(await readFile(path.join(staging, 'team.json'), 'utf8')), `${prefix}team.json`);
179
+ // Checked again just before the move: made meanwhile by someone else, theirs is kept.
180
+ await guard(kind);
181
+ await guard(path.join(stagingName, name));
182
+ if (await present(target)) { kept.push({ kind, name, path: shown(kind, name) }); continue; }
183
+ await mkdir(path.dirname(target), { recursive: true });
184
+ await guard(kind);
185
+ await rename(staging, target);
186
+ installed.push({ kind, name, path: shown(kind, name) });
187
+ } finally {
188
+ await rm(stagingRoot, { recursive: true, force: true });
189
+ }
190
+ }
191
+ }
192
+
193
+ const permissions = { set: [], kept: [], conflicts: [] };
194
+ if (Object.keys(pack.permissions).length) {
195
+ const file = path.join(base, 'settings.json');
196
+ await guard('settings.json');
197
+ const text = await readFile(file, 'utf8').catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
198
+ let settings = {};
199
+ if (text !== undefined) {
200
+ try { settings = JSON.parse(text); } catch (cause) { throw new AlpError('INVALID_SETTINGS', `${file}: ${cause.message}`, { cause }); }
201
+ if (!object(settings)) fail('INVALID_SETTINGS', `${file}: expected a JSON object`);
202
+ }
203
+ const current = object(settings.permissions) ? settings.permissions : {};
204
+ const agents = object(current.agents) ? current.agents : {};
205
+ let changed = false;
206
+ for (const [agent, required] of Object.entries(pack.permissions)) {
207
+ // An agent of that name that was already there is the user's: its permissions are theirs to set.
208
+ if (!installed.some(entry => entry.kind === 'agents' && entry.name === agent)) { if (!Object.hasOwn(agents, agent) || agents[agent] !== required) permissions.conflicts.push(`${agent}: your own ${agent} agent was kept, so its permissions were left as they are; the pack's ${agent} expects '${required}'`); continue; }
209
+ if (!Object.hasOwn(agents, agent)) { agents[agent] = required; permissions.set.push(`${agent}: ${required}`); changed = true; }
210
+ else if (agents[agent] === required) permissions.kept.push(`${agent}: ${required}`);
211
+ else permissions.conflicts.push(`${agent}: ${file} gives '${agents[agent]}', the pack expects '${required}'; left as it is`);
212
+ }
213
+ if (changed) {
214
+ const next = { ...settings, permissions: { ...current, agents } };
215
+ validatePermissions(next.permissions, file);
216
+ await guard('settings.json');
217
+ await writeJsonAtomic(file, next);
218
+ }
219
+ }
220
+
221
+ const assigned = [];
222
+ if (assign && Object.keys(pack.assign).length) {
223
+ const file = path.join(base, 'role-skills.json');
224
+ await guard('role-skills.json');
225
+ const text = await readFile(file, 'utf8').catch(error => { if (error.code === 'ENOENT') return '{}'; throw error; });
226
+ let roles;
227
+ try { roles = JSON.parse(text); } catch (cause) { throw new AlpError('INVALID_LIBRARY', `${file}: ${cause.message}; the pack was installed but no agent was given its skills`, { cause }); }
228
+ if (!object(roles)) fail('INVALID_LIBRARY', `${file}: expected an object of agent names to skill lists`);
229
+ for (const [role, skills] of Object.entries(pack.assign)) {
230
+ const list = Array.isArray(roles[role]) ? roles[role] : (roles[role] = []);
231
+ for (const skill of skills) if (!list.includes(skill)) { list.push(skill); assigned.push(`${role}/${skill}`); }
232
+ }
233
+ if (assigned.length) await writeJsonAtomic(file, roles);
234
+ }
235
+ return { pack: id, scope, installed, kept, assigned, permissions };
236
+ }
237
+
238
+ /** Which of a pack's entries a scope already has: for listings. */
239
+ export async function packStatus(pack, { root, library } = {}) {
240
+ const has = async base => {
241
+ if (!base) return false;
242
+ for (const kind of KINDS) for (const name of pack[kind]) if (!(await present(path.join(base, kind, name)))) return false;
243
+ return true;
244
+ };
245
+ return { library: await has(library), project: await has(root ? path.join(path.resolve(root), '.alp') : undefined) };
246
+ }
@@ -1,13 +1,14 @@
1
1
  export type PermissionBase = 'read-only' | 'workspace-write' | 'full-access';
2
- export type PermissionProfile = { name: string; base: PermissionBase; allow: string[]; ask: string[]; deny: string[]; beyondMode: 'refuse' | 'ask'; workdir?: 'copy' };
2
+ export type PermissionProfile = { name: string; base: PermissionBase; allow: string[]; ask: string[]; deny: string[]; beyondMode: 'refuse' | 'ask'; workdir?: 'copy'; cappedFrom?: PermissionBase };
3
3
  export const BASES: PermissionBase[];
4
4
  export const ADVISORS: string[];
5
+ export const READ_ONLY_ROLES: string[];
5
6
  export const MAX_RULES: number;
6
7
  export const TOOLS: string[];
7
8
  export function parseRule(rule: unknown, source?: string): { tool: string; specifier?: string };
8
9
  export function validatePermissions(value: unknown, source: string): { profiles: Record<string, { base?: PermissionBase; beyondMode?: 'refuse' | 'ask'; workdir?: 'copy'; allow: string[]; ask: string[]; deny: string[] }>; agents: Record<string, string> };
9
10
  export function addAllowRule(projectRoot: string, home: string | undefined, profileName: string, rule: string): Promise<string>;
10
- export function profileFor(projectRoot: string, home: string | undefined, agent: string): Promise<PermissionProfile | null>;
11
+ export function profileFor(projectRoot: string, home: string | undefined, agent: string, options?: { readOnly?: boolean }): Promise<PermissionProfile | null>;
11
12
  export function capMode(mode: string, base: string): string;
12
13
  export function unwrapShell(command: string): string;
13
14
  export function simpleCommands(line: string): string[] | null;
@@ -27,6 +27,11 @@ export const BASES = ['read-only', 'workspace-write', 'full-access'];
27
27
  const RANK = { 'read-only': 0, 'workspace-write': 1, 'full-access': 2 };
28
28
  /** Agents that advise, review or watch: their profiles stay read-only. */
29
29
  export const ADVISORS = ['oracle', 'reviewer', 'supervisor'];
30
+ /**
31
+ * Team roles that advise or review. A member serving in one is read-only whatever its name, its
32
+ * agent.json mode or a profile settings give it: callers pass `readOnly` for such a member.
33
+ */
34
+ export const READ_ONLY_ROLES = ['advisor', 'reviewer'];
30
35
  export const MAX_RULES = 200;
31
36
  const NAME = /^[\w.-]{1,64}$/;
32
37
  const RULE = /^([A-Za-z][\w-]*)(?:\((.*)\))?$/s;
@@ -101,14 +106,18 @@ async function settingsPermissions(file) {
101
106
  * keeps the runtime's defaults. Advisors without a profile get a read-only one.
102
107
  * `workdir: 'copy'` runs the agent in a disposable copy of its requester's tree,
103
108
  * where it may write, build and test; the requester's tree stays untouched.
109
+ * `readOnly` (a member serving as a team advisor or reviewer, READ_ONLY_ROLES): the profile is
110
+ * capped at read-only, and a profile settings give it with a higher base is capped, not obeyed;
111
+ * its rules still apply, as they do for the built-in advisors.
112
+ * @param {{ readOnly?: boolean }} [options]
104
113
  * @returns {Promise<{ name: string, base: string, allow: string[], ask: string[], deny: string[], beyondMode: 'refuse' | 'ask', workdir?: 'copy' } | null>}
105
114
  */
106
- export async function profileFor(projectRoot, home, agent) {
115
+ export async function profileFor(projectRoot, home, agent, { readOnly = false } = {}) {
107
116
  const project = await settingsPermissions(path.join(projectRoot, '.alp', 'settings.json'));
108
117
  const user = home ? await settingsPermissions(path.join(home, 'settings.json')) : { profiles: {}, agents: {} };
109
118
  const name = own(project.agents, agent) ?? own(user.agents, agent);
110
119
  const advisor = ADVISORS.includes(agent);
111
- if (!name) return advisor ? { name: 'read-only', base: 'read-only', allow: [], ask: [], deny: [], beyondMode: 'refuse' } : null;
120
+ if (!name) return advisor || readOnly ? { name: 'read-only', base: 'read-only', allow: [], ask: [], deny: [], beyondMode: 'refuse' } : null;
112
121
  const defined = [own(project.profiles, name), own(user.profiles, name)].filter(Boolean);
113
122
  if (!defined.length && !BASES.includes(name)) {
114
123
  throw new AlpError('INVALID_SETTINGS', `permissions.agents.${agent} names profile '${name}', which no settings file defines`);
@@ -119,7 +128,8 @@ export async function profileFor(projectRoot, home, agent) {
119
128
  if (copy && base !== 'read-only') throw new AlpError('INVALID_SETTINGS', `Profile '${name}' has workdir copy, which needs base read-only`);
120
129
  if (advisor && base !== 'read-only') throw new AlpError('INVALID_SETTINGS', `${agent} is an advisor; its profile '${name}' must have base read-only`);
121
130
  return {
122
- name, base,
131
+ name, base: readOnly ? 'read-only' : base,
132
+ ...(readOnly && base !== 'read-only' ? { cappedFrom: base } : {}),
123
133
  allow: [...new Set(defined.flatMap(profile => profile.allow ?? []))],
124
134
  ask: [...new Set(defined.flatMap(profile => profile.ask ?? []))],
125
135
  deny: [...new Set(defined.flatMap(profile => profile.deny ?? []))],
package/src/profiles.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import os from 'node:os';
3
3
  import { createHash } from 'node:crypto';
4
- import { MODELS } from './models.js';
4
+ import { knownModel } from './models.js';
5
5
  import { resolveTeam, teamSources } from './teams.js';
6
6
 
7
7
  export const userLibrary = () => process.env.ALP_HOME ?? path.join(os.homedir(), '.alp');
@@ -31,13 +31,13 @@ export const parseProfile = profile => {
31
31
  };
32
32
  /** The string form of a profile: "provider:model", with ":effort" when it has one. */
33
33
  export const profileString = profile => `${profileModel(profile)}${profile.effort ? `:${profile.effort}` : ''}`;
34
- /** The efforts a runtime-prefixed model takes, for the models ALP knows; undefined for others. */
35
- export const modelEfforts = id => MODELS.find(model => `${model.runtime}:${model.id}` === id)?.efforts;
34
+ /** The efforts a runtime-prefixed model takes, for the models ALP knows (the live catalog when loaded, t-086c); undefined for others. */
35
+ export const modelEfforts = id => knownModel(id)?.efforts;
36
36
  /** An effort the model takes: the one wanted, or else the model's own default. */
37
37
  export const fitEffort = (id, effort) => {
38
38
  const efforts = modelEfforts(id);
39
39
  if (!efforts?.length || efforts.includes(effort)) return effort;
40
- return MODELS.find(model => `${model.runtime}:${model.id}` === id)?.effort ?? efforts[0];
40
+ return knownModel(id)?.effort ?? efforts[0];
41
41
  };
42
42
  /** Whether a profile stands for every model of its provider. */
43
43
  export const anyModel = profile => profile?.model === '*';
package/src/providers.js CHANGED
@@ -5,6 +5,8 @@ import { AlpError } from './errors.js';
5
5
  import { settingsKeys, unknownMessage } from './validation.js';
6
6
  import { scriptCommand } from './packaged.js';
7
7
 
8
+ const legacyWarnings = new Set();
9
+
8
10
  /**
9
11
  * ACP providers (ALPD §46): agents that speak the Agent Client Protocol, such as Gemini
10
12
  * CLI or opencode, defined in the user's library as providers/<id>.json. An agent runs
@@ -20,7 +22,7 @@ import { scriptCommand } from './packaged.js';
20
22
  * Paseo's catalog carries and ALP keeps without using.
21
23
  */
22
24
 
23
- export const PROVIDER_SETTINGS = ['$schema', 'kind', 'label', 'description', 'command', 'args', 'env', 'models', 'additionalModels', 'enabled', 'params', 'readOnlyMode'];
25
+ export const PROVIDER_SETTINGS = ['$schema', 'kind', 'label', 'description', 'command', 'args', 'env', 'models', 'additionalModels', 'enabled', 'params'];
24
26
  /** Runtimes ALP has built in; no provider takes their names. */
25
27
  export const BUILTIN_RUNTIMES = ['codex', 'claude', 'acp', 'antigravity'];
26
28
  /** Names no provider takes: the runtimes, and `alp`, which the web app lists ALP's teams under. */
@@ -35,11 +37,12 @@ export function validateProvider(config, source, id) {
35
37
  const check = (ok, message) => { if (!ok) throw new AlpError('INVALID_PROVIDER', `${source}: ${message}`); };
36
38
  if (id !== undefined) check(validId(id) && (!RESERVED_PROVIDERS.includes(id) || (id === 'antigravity' && config?.kind === 'antigravity')), `'${id}' cannot name a provider: ${RESERVED_PROVIDERS.join(', ')} are taken`);
37
39
  check(object(config), 'expected an object');
40
+ check(!Object.hasOwn(config, 'readOnlyMode'), 'readOnlyMode was removed; delete it and choose the session mode (read-only, workspace-write or full-access). Existing native sessions keep their mode');
38
41
  const { unknown } = settingsKeys(config, PROVIDER_SETTINGS);
39
42
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], PROVIDER_SETTINGS) : '');
40
43
  check(['acp', 'antigravity'].includes(config.kind), 'kind must be "acp" or "antigravity"');
41
44
  if (config.kind === 'antigravity' && id !== undefined) check(id === 'antigravity', 'Antigravity must use provider ID antigravity');
42
- if (config.readOnlyMode !== undefined) check(config.kind === 'antigravity' && ['instructions', 'reject'].includes(config.readOnlyMode), 'readOnlyMode is only for Antigravity and must be "instructions" or "reject"');
45
+
43
46
  for (const key of ['label', 'description']) if (config[key] !== undefined) check(typeof config[key] === 'string', `${key} must be a string`);
44
47
  check(nonempty(config.command), 'command must be a nonempty string');
45
48
  if (config.args !== undefined) check(Array.isArray(config.args) && config.args.every(arg => typeof arg === 'string'), 'args must be a list of strings');
@@ -58,7 +61,7 @@ export function validateProvider(config, source, id) {
58
61
 
59
62
  /**
60
63
  * A provider of the library, with its id; undefined when there is none.
61
- * @returns {Promise<{ id: string, kind: 'acp' | 'antigravity', label: string, description?: string, command: string, args: string[], env: Record<string, string>, models?: Array<{ id: string, label?: string, description?: string }>, additionalModels?: Array<{ id: string, label?: string, description?: string }>, enabled?: boolean, params?: Record<string, unknown>, readOnlyMode?: 'instructions' | 'reject' } | undefined>}
64
+ * @returns {Promise<{ id: string, kind: 'acp' | 'antigravity', label: string, description?: string, command: string, args: string[], env: Record<string, string>, models?: Array<{ id: string, label?: string, description?: string }>, additionalModels?: Array<{ id: string, label?: string, description?: string }>, enabled?: boolean, params?: Record<string, unknown> } | undefined>}
62
65
  */
63
66
  export async function loadProvider(library, id) {
64
67
  if (!library || !validId(id) || (RESERVED_PROVIDERS.includes(id) && id !== 'antigravity')) return undefined;
@@ -67,6 +70,16 @@ export async function loadProvider(library, id) {
67
70
  try { text = await readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
68
71
  let config;
69
72
  try { config = JSON.parse(text); } catch (cause) { throw new AlpError('INVALID_PROVIDER', `${file}: ${cause.message}`, { cause }); }
73
+ // Compatibility for old provider files: this setting never controlled native permissions.
74
+ // Normalize only the loaded copy; no existing native session or file is changed.
75
+ if (config?.kind === 'antigravity' && Object.hasOwn(config, 'readOnlyMode')) {
76
+ config = { ...config };
77
+ delete config.readOnlyMode;
78
+ if (!legacyWarnings.has(file)) {
79
+ legacyWarnings.add(file);
80
+ console.warn(`${file}: readOnlyMode was removed; delete it and select a session mode (read-only, workspace-write or full-access). Existing sessions keep their mode.`);
81
+ }
82
+ }
70
83
  validateProvider(config, file, id);
71
84
  // A relative command path is the provider file's; a bare name is looked up on PATH.
72
85
  const command = /[\\/]/.test(config.command) ? path.resolve(path.dirname(file), config.command) : config.command;
@@ -74,13 +87,15 @@ export async function loadProvider(library, id) {
74
87
  }
75
88
 
76
89
  /** Every provider of the library, by id. */
77
- export async function listProviders(library) {
90
+ export async function listProviders(library, { onError } = {}) {
78
91
  if (!library) return [];
79
92
  let names = [];
80
93
  try { names = await readdir(path.join(library, 'providers')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
81
94
  const providers = [];
82
95
  for (const name of names.filter(name => name.endsWith('.json')).sort()) {
83
- const provider = await loadProvider(library, name.slice(0, -5));
96
+ let provider;
97
+ // With onError, one invalid file is reported and skipped instead of failing the whole list.
98
+ try { provider = await loadProvider(library, name.slice(0, -5)); } catch (error) { if (!onError) throw error; onError(error, name); continue; }
84
99
  if (provider) providers.push(provider);
85
100
  }
86
101
  return providers;
package/src/resolver.js CHANGED
@@ -170,7 +170,7 @@ export async function resolveAgent(projectRoot, { agent, library, templates } =
170
170
  }
171
171
  validateAgentConfig(config, configPath);
172
172
 
173
- // The role's library skills; a project skill of the same name in .alp/skills replaces one.
173
+ // The library skills role-skills.json lists under this agent's name (not its role); a project skill of the same name in .alp/skills replaces one.
174
174
  const skills = [];
175
175
  for (const skill of library ? await librarySkills(library, name) : []) {
176
176
  skills.push({ name: skill.name, path: (await namedEntry(root, undefined, 'skills', skill.name, entry => path.join(entry, 'SKILL.md'))) ?? skill.path });