@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
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');
@@ -19,7 +19,7 @@ export const oracleProfiles = config => config?.profiles ?? [config?.claude, con
19
19
  export const agentProfiles = (config, name) => {
20
20
  if (!config) return [];
21
21
  if (name === 'oracle') return oracleProfiles(config).map(parseProfile);
22
- const { autocompact, ...legacy } = config;
22
+ const { autocompact, commands, ...legacy } = config;
23
23
  return (config.profiles ?? [legacy]).map(parseProfile);
24
24
  };
25
25
 
@@ -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 === '*';
@@ -56,7 +56,7 @@ export function normalizeAgentProfiles(config, name) {
56
56
  if (config.profiles) return { ...config, profiles: config.profiles.map(profile => typeof profile === 'string' ? profile : profileString(profile)), autocompact: config.autocompact ?? 'auto' };
57
57
  const profiles = agentProfiles(config, name);
58
58
  if (!profiles.length || profiles.some(profile => !profile.model)) return config;
59
- return { profiles: profiles.map(profile => profileString({ ...profile, provider: profile.provider ?? profile.model.split(':')[0] })), autocompact: config.autocompact ?? 'auto' };
59
+ return { profiles: profiles.map(profile => profileString({ ...profile, provider: profile.provider ?? profile.model.split(':')[0] })), autocompact: config.autocompact ?? 'auto', ...(config.commands ? { commands: config.commands } : {}) };
60
60
  }
61
61
 
62
62
  export const profileModel = config => config?.model ? config.model.includes(':') ? config.model : `${config.provider}:${config.model}` : undefined;
@@ -128,7 +128,7 @@ export async function syncTemplateProfiles(settings, options = {}) {
128
128
  for (const name of new Set([...Object.keys(previous[id] ?? {}), ...(options.replaceModels ? Object.keys(current) : []), ...Object.keys(desired)])) {
129
129
  const config = current[name];
130
130
  if (!options.replaceModels && config && profileFingerprint(config, name) !== previous[id]?.[name]) continue;
131
- if (desired[name]) current[name] = { ...desired[name], autocompact: config?.autocompact ?? desired[name].autocompact };
131
+ if (desired[name]) current[name] = { ...desired[name], autocompact: config?.autocompact ?? desired[name].autocompact, ...(config?.commands ? { commands: config.commands } : {}) };
132
132
  else delete current[name];
133
133
  }
134
134
  if (Object.keys(current).length) next.team[id] = current;
package/src/providers.js CHANGED
@@ -3,6 +3,9 @@ import { readdir, readFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { AlpError } from './errors.js';
5
5
  import { settingsKeys, unknownMessage } from './validation.js';
6
+ import { scriptCommand } from './packaged.js';
7
+
8
+ const legacyWarnings = new Set();
6
9
 
7
10
  /**
8
11
  * ACP providers (ALPD §46): agents that speak the Agent Client Protocol, such as Gemini
@@ -19,7 +22,7 @@ import { settingsKeys, unknownMessage } from './validation.js';
19
22
  * Paseo's catalog carries and ALP keeps without using.
20
23
  */
21
24
 
22
- 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'];
23
26
  /** Runtimes ALP has built in; no provider takes their names. */
24
27
  export const BUILTIN_RUNTIMES = ['codex', 'claude', 'acp', 'antigravity'];
25
28
  /** Names no provider takes: the runtimes, and `alp`, which the web app lists ALP's teams under. */
@@ -34,11 +37,12 @@ export function validateProvider(config, source, id) {
34
37
  const check = (ok, message) => { if (!ok) throw new AlpError('INVALID_PROVIDER', `${source}: ${message}`); };
35
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`);
36
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');
37
41
  const { unknown } = settingsKeys(config, PROVIDER_SETTINGS);
38
42
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], PROVIDER_SETTINGS) : '');
39
43
  check(['acp', 'antigravity'].includes(config.kind), 'kind must be "acp" or "antigravity"');
40
44
  if (config.kind === 'antigravity' && id !== undefined) check(id === 'antigravity', 'Antigravity must use provider ID antigravity');
41
- 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
+
42
46
  for (const key of ['label', 'description']) if (config[key] !== undefined) check(typeof config[key] === 'string', `${key} must be a string`);
43
47
  check(nonempty(config.command), 'command must be a nonempty string');
44
48
  if (config.args !== undefined) check(Array.isArray(config.args) && config.args.every(arg => typeof arg === 'string'), 'args must be a list of strings');
@@ -57,7 +61,7 @@ export function validateProvider(config, source, id) {
57
61
 
58
62
  /**
59
63
  * A provider of the library, with its id; undefined when there is none.
60
- * @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>}
61
65
  */
62
66
  export async function loadProvider(library, id) {
63
67
  if (!library || !validId(id) || (RESERVED_PROVIDERS.includes(id) && id !== 'antigravity')) return undefined;
@@ -66,6 +70,16 @@ export async function loadProvider(library, id) {
66
70
  try { text = await readFile(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
67
71
  let config;
68
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
+ }
69
83
  validateProvider(config, file, id);
70
84
  // A relative command path is the provider file's; a bare name is looked up on PATH.
71
85
  const command = /[\\/]/.test(config.command) ? path.resolve(path.dirname(file), config.command) : config.command;
@@ -73,13 +87,15 @@ export async function loadProvider(library, id) {
73
87
  }
74
88
 
75
89
  /** Every provider of the library, by id. */
76
- export async function listProviders(library) {
90
+ export async function listProviders(library, { onError } = {}) {
77
91
  if (!library) return [];
78
92
  let names = [];
79
93
  try { names = await readdir(path.join(library, 'providers')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
80
94
  const providers = [];
81
95
  for (const name of names.filter(name => name.endsWith('.json')).sort()) {
82
- 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; }
83
99
  if (provider) providers.push(provider);
84
100
  }
85
101
  return providers;
@@ -100,7 +116,7 @@ export function acpModel(model) {
100
116
  * native executable it calls, or the Node script, under this Node. A bare name with an .exe or
101
117
  * .com on PATH, any other command, and every command elsewhere are returned as they are.
102
118
  * @param {string} command @param {string[]} [args] @param {Record<string, string | undefined>} [env]
103
- * @returns {{ command: string, args: string[] }}
119
+ * @returns {{ command: string, args: string[], env?: Record<string, string> }}
104
120
  */
105
121
  export function launchCommand(command, args = [], env = process.env) {
106
122
  if (process.platform !== 'win32' || /[\\/]/.test(command) || path.extname(command)) return { command, args };
@@ -113,7 +129,7 @@ export function launchCommand(command, args = [], env = process.env) {
113
129
  // for a Node script. Anything else (a hand-written batch file) stays refused by spawn, as before.
114
130
  const text = readFileSync(shim, 'utf8');
115
131
  const script = /"%_prog%"((?:\s+[^\s"]+)*)\s+"%~?dp0%\\?([^"]+)"\s+%\*/i.exec(text);
116
- if (script) return { command: process.execPath, args: [...script[1].split(/\s+/).filter(Boolean), path.join(directory, script[2]), ...args] };
132
+ if (script) { const flags = script[1].split(/\s+/).filter(Boolean); const run = scriptCommand(path.join(directory, script[2]), args); return { command: run.command, args: [...flags, ...run.args] }; }
117
133
  const native = /^\s*"%~?dp0%\\?([^"]+\.(?:exe|com))"\s+%\*/im.exec(text);
118
134
  if (native) return { command: path.join(directory, native[1]), args };
119
135
  break;
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 });