@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.
- package/dist/backup.js +106 -4
- package/dist/bridges.d.ts +26 -0
- package/dist/bridges.js +96 -0
- package/dist/gate-ledger.d.ts +30 -0
- package/dist/gate-ledger.js +99 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/library-edit.d.ts +57 -5
- package/dist/library-edit.js +216 -11
- package/dist/library.d.ts +14 -1
- package/dist/library.js +73 -5
- package/dist/migrations.js +1 -1
- package/dist/models.d.ts +74 -0
- package/dist/models.js +67 -1
- package/dist/packaged.d.ts +122 -0
- package/dist/packaged.js +125 -0
- package/dist/packs.d.ts +57 -0
- package/dist/packs.js +247 -0
- package/dist/permissions.d.ts +3 -2
- package/dist/permissions.js +6 -3
- package/dist/profiles.js +6 -6
- package/dist/providers.d.ts +4 -5
- package/dist/providers.js +26 -5
- package/dist/skill-validate.d.ts +85 -0
- package/dist/skill-validate.js +298 -0
- package/dist/task-rows.d.ts +5 -0
- package/dist/task-rows.js +1 -1
- package/dist/tasks.d.ts +23 -4
- package/dist/tasks.js +103 -9
- package/dist/types.d.ts +3 -0
- package/dist/upgrade.d.ts +10 -0
- package/dist/upgrade.js +112 -6
- package/dist/user-settings.d.ts +2 -0
- package/dist/user-settings.js +40 -1
- package/dist/user-worktree.d.ts +29 -0
- package/dist/user-worktree.js +242 -0
- package/dist/validation.d.ts +1 -0
- package/dist/validation.js +35 -13
- package/package.json +34 -2
- package/src/backup.js +106 -5
- package/src/bridges.js +113 -0
- package/src/gate-ledger.js +125 -0
- package/src/index.js +1 -0
- package/src/library-edit.js +227 -12
- package/src/library.js +96 -6
- package/src/migrations.js +1 -1
- package/src/models.js +87 -1
- package/src/packaged.js +207 -0
- package/src/packs.js +246 -0
- package/src/permissions.d.ts +3 -2
- package/src/permissions.js +13 -3
- package/src/profiles.js +7 -7
- package/src/providers.js +23 -7
- package/src/resolver.js +1 -1
- package/src/skill-validate.js +287 -0
- package/src/task-rows.js +1 -1
- package/src/tasks.d.ts +23 -4
- package/src/tasks.js +137 -10
- package/src/types.d.ts +3 -0
- package/src/upgrade.js +54 -6
- package/src/user-settings.d.ts +2 -0
- package/src/user-settings.js +51 -1
- package/src/user-worktree.js +259 -0
- package/src/validation.d.ts +1 -0
- package/src/validation.js +43 -14
- package/templates/ALP.md +52 -52
- package/templates/agents/lead/AGENT.md +77 -74
- package/templates/agents/main/AGENT.md +153 -141
- package/templates/agents/oracle/AGENT.md +38 -37
- package/templates/agents/peer/AGENT.md +56 -52
- package/templates/agents/reviewer/AGENT.md +63 -65
- package/templates/agents/supervisor/AGENT.md +63 -63
- package/templates/packs/architecture/agents/architect/AGENT.md +41 -0
- package/templates/packs/architecture/agents/architect/agent.json +5 -0
- package/templates/packs/architecture/agents/docs-maintainer/AGENT.md +33 -0
- package/templates/packs/architecture/agents/docs-maintainer/agent.json +4 -0
- package/templates/packs/architecture/pack.json +7 -0
- package/templates/packs/architecture/teams/blueprint/HOUSE_RULES.md +12 -0
- package/templates/packs/architecture/teams/blueprint/team.json +19 -0
- package/templates/packs/backend/pack.json +6 -0
- package/templates/packs/backend/skills/backend-development/SKILL.md +102 -0
- package/templates/packs/backend/skills/backend-development/references/api-design.md +96 -0
- package/templates/packs/backend/skills/backend-development/references/authentication.md +78 -0
- package/templates/packs/backend/skills/backend-development/references/error-handling.md +86 -0
- package/templates/packs/backend/skills/backend-development/references/testing.md +81 -0
- package/templates/packs/backend/skills/databases/SKILL.md +103 -0
- package/templates/packs/backend/skills/databases/references/query-performance.md +87 -0
- package/templates/packs/backend/skills/databases/references/schema-and-migrations.md +87 -0
- package/templates/packs/design/pack.json +6 -0
- package/templates/packs/design/skills/ui-design/SKILL.md +86 -0
- package/templates/packs/design/skills/ui-design/references/design-tokens.md +67 -0
- package/templates/packs/design/skills/ui-design/references/interaction-states.md +73 -0
- package/templates/packs/design/skills/ui-design/references/layout-and-typography.md +71 -0
- package/templates/packs/design/skills/ui-design/references/ui-review.md +83 -0
- package/templates/packs/frontend/pack.json +6 -0
- package/templates/packs/frontend/skills/frontend-development/SKILL.md +105 -0
- package/templates/packs/frontend/skills/frontend-development/references/accessibility.md +86 -0
- package/templates/packs/frontend/skills/frontend-development/references/components-and-state.md +79 -0
- package/templates/packs/frontend/skills/frontend-development/references/data-fetching.md +86 -0
- package/templates/packs/frontend/skills/frontend-development/references/frameworks.md +77 -0
- package/templates/packs/frontend/skills/frontend-development/references/performance.md +78 -0
- package/templates/packs/integration/pack.json +6 -0
- package/templates/packs/integration/skills/mcp-integration/SKILL.md +100 -0
- package/templates/packs/integration/skills/mcp-integration/references/server-implementation.md +95 -0
- package/templates/packs/integration/skills/mcp-integration/references/testing.md +78 -0
- package/templates/packs/integration/skills/mcp-integration/references/tool-design.md +97 -0
- package/templates/packs/operations/pack.json +6 -0
- package/templates/packs/operations/skills/devops/SKILL.md +85 -0
- package/templates/packs/operations/skills/devops/references/ci-cd.md +84 -0
- package/templates/packs/operations/skills/devops/references/containers.md +85 -0
- package/templates/packs/operations/skills/devops/references/deployment-and-rollback.md +85 -0
- package/templates/packs/operations/skills/devops/references/observability.md +86 -0
- package/templates/packs/quality/pack.json +6 -0
- package/templates/packs/quality/skills/web-testing/SKILL.md +102 -0
- package/templates/packs/quality/skills/web-testing/references/e2e.md +85 -0
- package/templates/packs/quality/skills/web-testing/references/performance-testing.md +85 -0
- package/templates/packs/quality/skills/web-testing/references/security-testing.md +78 -0
- package/templates/packs/quality/skills/web-testing/references/unit-and-component.md +78 -0
- package/templates/role-skills.json +4 -4
- package/templates/skills/architecture-docs/SKILL.md +81 -0
- package/templates/skills/architecture-docs/references/adr.md +62 -0
- package/templates/skills/architecture-docs/references/diagrams.md +60 -0
- package/templates/skills/architecture-docs/references/evidence-rules.md +49 -0
- package/templates/skills/bug-loop/SKILL.md +41 -40
- package/templates/skills/bug-loop/references/test-proof.md +21 -19
- package/templates/skills/compact/SKILL.md +34 -0
- package/templates/skills/curate/SKILL.md +36 -0
- package/templates/skills/feature-architecture/SKILL.md +90 -0
- package/templates/skills/feature-architecture/references/architecture-contract.md +95 -0
- package/templates/skills/feature-architecture/references/feature-design.md +69 -0
- package/templates/skills/feature-architecture/scripts/check-boundaries.mjs +270 -0
- package/templates/skills/goal-griller/SKILL.md +27 -27
- package/templates/skills/prompt-leverage/SKILL.md +29 -27
- package/templates/skills/prompt-leverage/references/brief-template.md +9 -9
- package/templates/skills/release-readiness/SKILL.md +83 -0
- package/templates/skills/release-readiness/references/checklist.md +40 -0
- package/templates/skills/release-readiness/references/verdict-template.md +53 -0
- package/templates/skills/safe-refactor/SKILL.md +84 -0
- package/templates/skills/safe-refactor/references/characterization-tests.md +57 -0
- package/templates/skills/safe-refactor/references/compatibility-checklist.md +56 -0
- package/templates/skills/security-review/SKILL.md +87 -0
- package/templates/skills/security-review/references/checklist.md +74 -0
- package/templates/skills/security-review/references/severity.md +61 -0
- package/templates/skills/sequence-execution-plan/SKILL.md +41 -38
- package/templates/skills/sequence-execution-plan/references/plan-template.md +5 -5
- package/templates/skills/skill-authoring/SKILL.md +84 -0
- package/templates/skills/skill-authoring/references/evaluation.md +45 -0
- package/templates/skills/skill-authoring/references/skill-anatomy.md +74 -0
- package/templates/skills/skill-authoring/references/trigger-design.md +52 -0
- package/templates/skills/smart-commits/SKILL.md +37 -36
- package/templates/skills/test-strategy/SKILL.md +83 -0
- package/templates/skills/test-strategy/references/contract-tests.md +46 -0
- package/templates/skills/test-strategy/references/risk-matrix.md +53 -0
- package/templates/skills/xia/SKILL.md +40 -38
- package/templates/teams/cafe/HOUSE_RULES.md +1 -1
- package/templates/teams/cafe/team.json +1 -1
- package/templates/teams/pho/HOUSE_RULES.md +1 -1
- package/templates/teams/pho/team.json +1 -1
package/src/bridges.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { isExecutableName, nodeExecutable, stablePath } from './packaged.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The stdio MCP bridges an agent CLI starts to reach alpd's tools (ACP agents and Antigravity).
|
|
6
|
+
* They run as `node -e <source>`; `alp bridge acp|antigravity` (which calls runBridge) remains for
|
|
7
|
+
* the MCP entries the single-file executable of 0.0.1-beta.5/6 wrote.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const ACP_BRIDGE = `
|
|
11
|
+
const net = require('node:net');
|
|
12
|
+
const readline = require('node:readline');
|
|
13
|
+
const socket = net.connect(process.env.ALP_BRIDGE_SOCKET);
|
|
14
|
+
const waiting = new Map();
|
|
15
|
+
let sequence = 0;
|
|
16
|
+
let buffer = '';
|
|
17
|
+
socket.setEncoding('utf8');
|
|
18
|
+
socket.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
|
|
19
|
+
socket.on('data', data => {
|
|
20
|
+
buffer += data;
|
|
21
|
+
for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
|
|
22
|
+
const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
|
|
23
|
+
try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
socket.on('close', () => process.exit(0));
|
|
27
|
+
socket.on('error', () => process.exit(1));
|
|
28
|
+
const ask = message => new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
|
|
29
|
+
const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
|
|
30
|
+
readline.createInterface({ input: process.stdin }).on('line', async line => {
|
|
31
|
+
let message; try { message = JSON.parse(line); } catch { return; }
|
|
32
|
+
if (message.id === undefined || message.id === null) return;
|
|
33
|
+
try {
|
|
34
|
+
if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });
|
|
35
|
+
if (message.method === 'ping') return send({ id: message.id, result: {} });
|
|
36
|
+
if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
|
|
37
|
+
if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }
|
|
38
|
+
send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
|
|
39
|
+
} catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
|
|
40
|
+
});
|
|
41
|
+
process.stdin.on('end', () => process.exit(0));
|
|
42
|
+
`;
|
|
43
|
+
|
|
44
|
+
export const ANTIGRAVITY_BRIDGE = `// ALP Antigravity bridge v1
|
|
45
|
+
|
|
46
|
+
const net = require('node:net');
|
|
47
|
+
const readline = require('node:readline');
|
|
48
|
+
const socket = process.env.ALP_BRIDGE_SOCKET ? net.connect(process.env.ALP_BRIDGE_SOCKET) : null;
|
|
49
|
+
const waiting = new Map();
|
|
50
|
+
let sequence = 0;
|
|
51
|
+
let buffer = '';
|
|
52
|
+
socket?.setEncoding('utf8');
|
|
53
|
+
socket?.write(JSON.stringify({ token: process.env.ALP_BRIDGE_TOKEN }) + '\\n');
|
|
54
|
+
socket?.on('data', data => {
|
|
55
|
+
buffer += data;
|
|
56
|
+
for (let index; (index = buffer.indexOf('\\n')) >= 0;) {
|
|
57
|
+
const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
|
|
58
|
+
try { const message = JSON.parse(line); const waiter = waiting.get(message.id); if (waiter) { waiting.delete(message.id); waiter(message); } } catch {}
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
socket?.on('close', () => process.exit(0));
|
|
62
|
+
socket?.on('error', () => process.exit(1));
|
|
63
|
+
const ask = message => !socket ? Promise.resolve({ tools: [], result: { content: [{ type: 'text', text: 'No ALP session' }], isError: true } }) : new Promise(resolve => { const id = ++sequence; waiting.set(id, resolve); socket.write(JSON.stringify({ ...message, id }) + '\\n'); });
|
|
64
|
+
const send = value => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...value }) + '\\n');
|
|
65
|
+
readline.createInterface({ input: process.stdin }).on('line', async line => {
|
|
66
|
+
let message; try { message = JSON.parse(line); } catch { return; }
|
|
67
|
+
if (message.id === undefined || message.id === null) return;
|
|
68
|
+
try {
|
|
69
|
+
if (message.method === 'initialize') return send({ id: message.id, result: { protocolVersion: (message.params && message.params.protocolVersion) || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'alp', version: '1' } } });
|
|
70
|
+
if (message.method === 'ping') return send({ id: message.id, result: {} });
|
|
71
|
+
if (message.method === 'tools/list') { const reply = await ask({ op: 'list' }); return send({ id: message.id, result: { tools: reply.tools } }); }
|
|
72
|
+
if (message.method === 'tools/call') { const reply = await ask({ op: 'call', name: message.params.name, arguments: message.params.arguments || {} }); return send({ id: message.id, result: reply.result }); }
|
|
73
|
+
send({ id: message.id, error: { code: -32601, message: 'Method not found' } });
|
|
74
|
+
} catch (error) { send({ id: message.id, error: { code: -32603, message: String((error && error.message) || error) } }); }
|
|
75
|
+
});
|
|
76
|
+
process.stdin.on('end', () => process.exit(0));
|
|
77
|
+
`;
|
|
78
|
+
|
|
79
|
+
const BRIDGES = { acp: ACP_BRIDGE, antigravity: ANTIGRAVITY_BRIDGE };
|
|
80
|
+
|
|
81
|
+
/** Runs a bridge in this process, as `node -e` would. @param {string} kind */
|
|
82
|
+
export function runBridge(kind) {
|
|
83
|
+
const source = Object.hasOwn(BRIDGES, kind) ? BRIDGES[/** @type {'acp' | 'antigravity'} */ (kind)] : undefined;
|
|
84
|
+
if (!source) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
|
|
85
|
+
// eslint-disable-next-line no-new-func
|
|
86
|
+
new Function('require', source)(createRequire(import.meta.url));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The command an agent CLI runs to start a bridge: `node -e <source>` under this Node.
|
|
91
|
+
* @param {'acp' | 'antigravity'} kind
|
|
92
|
+
* @returns {{ command: string, args: string[] }}
|
|
93
|
+
*/
|
|
94
|
+
export function bridgeCommand(kind) {
|
|
95
|
+
if (!Object.hasOwn(BRIDGES, kind)) throw new Error(`Unknown bridge: ${kind}; expected acp or antigravity`);
|
|
96
|
+
// Agents keep this command in their MCP configuration: name the ALP bundle's Node through app/current.
|
|
97
|
+
// In the native alpd (t-81b0.9) that is still the bundle's Node: the native alpd does not evaluate -e.
|
|
98
|
+
return { command: stablePath(nodeExecutable()), args: ['-e', BRIDGES[kind]] };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Whether an MCP server entry is one of ALP's bridge launchers: the `-e` source, or `alp bridge <kind>`
|
|
103
|
+
* as the single-file executable of 0.0.1-beta.5/6 wrote it (only when its command is named alp, so another server is kept).
|
|
104
|
+
* @param {'acp' | 'antigravity'} kind
|
|
105
|
+
* @param {unknown} args
|
|
106
|
+
* @param {unknown} [command]
|
|
107
|
+
*/
|
|
108
|
+
export function isBridgeArgs(kind, args, command = undefined) {
|
|
109
|
+
if (!Array.isArray(args)) return false;
|
|
110
|
+
const marker = kind === 'antigravity' ? '// ALP Antigravity bridge v1' : undefined;
|
|
111
|
+
if (marker && args.some(arg => typeof arg === 'string' && arg.startsWith(marker))) return true;
|
|
112
|
+
return typeof command === 'string' && isExecutableName(command) && args.length === 2 && args[0] === 'bridge' && args[1] === kind;
|
|
113
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { alpHome } from './library.js';
|
|
6
|
+
import { AlpError } from './errors.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A record of the human gates ALP opened and the clears ALP itself made, kept in
|
|
10
|
+
* $ALP_HOME, outside the project. The task files in .alp/tasks are plain files an
|
|
11
|
+
* agent can edit; when one shows a ledgered human gate cleared or gone without a
|
|
12
|
+
* clear here, loadTasks reopens it and marks it `tampered`.
|
|
13
|
+
*
|
|
14
|
+
* This detects an edit of the task file only. It is not a security boundary: an
|
|
15
|
+
* agent running as the same OS user can edit this file too (t-ca1f residual risk).
|
|
16
|
+
* Human gates from before the ledger enter it the next time ALP writes their task.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const key = (taskId, gate) => `${taskId}/${gate.id}@${gate.at}`;
|
|
20
|
+
|
|
21
|
+
/** One project's ledger, by its real path: /tmp and /private/tmp are the same project. */
|
|
22
|
+
function realRoot(projectRoot) {
|
|
23
|
+
try { return realpathSync.native(path.resolve(projectRoot)); } catch { return path.resolve(projectRoot); }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function ledgerFile(projectRoot) {
|
|
27
|
+
const hash = createHash('sha256').update(realRoot(projectRoot)).digest('hex').slice(0, 24);
|
|
28
|
+
return path.join(alpHome(), 'gates', `${hash}.json`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The project's ledger. A missing one is empty. On read (`strict` false) an unreadable or corrupt
|
|
33
|
+
* one detects nothing and never blocks the task graph; a writer (`strict`) refuses it instead,
|
|
34
|
+
* so it never overwrites entries it could not read.
|
|
35
|
+
*/
|
|
36
|
+
export async function readLedger(projectRoot, { strict = false } = {}) {
|
|
37
|
+
let data;
|
|
38
|
+
try {
|
|
39
|
+
data = JSON.parse(await readFile(ledgerFile(projectRoot), 'utf8'));
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error.code === 'ENOENT') return { gates: {} };
|
|
42
|
+
if (strict) throw new AlpError('GATE_LEDGER_UNREADABLE', `The gate ledger ${ledgerFile(projectRoot)} is unreadable (${error.message}); fix or remove it`);
|
|
43
|
+
return { gates: {} };
|
|
44
|
+
}
|
|
45
|
+
if (data && typeof data === 'object' && data.gates && typeof data.gates === 'object') return data;
|
|
46
|
+
if (strict) throw new AlpError('GATE_LEDGER_UNREADABLE', `The gate ledger ${ledgerFile(projectRoot)} is not a ledger; fix or remove it`);
|
|
47
|
+
return { gates: {} };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function writeLedger(projectRoot, ledger) {
|
|
51
|
+
const file = ledgerFile(projectRoot);
|
|
52
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
53
|
+
const temporary = `${file}.${randomUUID().slice(0, 8)}.tmp`;
|
|
54
|
+
await writeFile(temporary, JSON.stringify(ledger, null, 2) + '\n', { mode: 0o600 });
|
|
55
|
+
await rename(temporary, file);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Records the open human gates of a task ALP just wrote (addGate, a formula's human step, a beads import) that it does not hold yet. */
|
|
59
|
+
export async function ledgerAdopt(projectRoot, task) {
|
|
60
|
+
const open = (task.gates ?? []).filter(gate => gate.kind === 'human' && !gate.resolved && typeof gate.at === 'string' && /^g\d+$/.test(gate.id));
|
|
61
|
+
if (!open.length) return;
|
|
62
|
+
const ledger = await readLedger(projectRoot, { strict: true });
|
|
63
|
+
const missing = open.filter(gate => !ledger.gates[key(task.id, gate)]);
|
|
64
|
+
if (!missing.length) return;
|
|
65
|
+
ledger.project = realRoot(projectRoot);
|
|
66
|
+
for (const gate of missing) ledger.gates[key(task.id, gate)] = { opened: gate.at };
|
|
67
|
+
await writeLedger(projectRoot, ledger);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Records that ALP cleared or removed a human gate. Written under the task lock once every check
|
|
72
|
+
* passed and before the task file: should the file write fail, the gate stays open in the file.
|
|
73
|
+
*/
|
|
74
|
+
export async function ledgerResolve(projectRoot, taskId, gate, { by, channel, removed = false }) {
|
|
75
|
+
const ledger = await readLedger(projectRoot, { strict: true });
|
|
76
|
+
const entry = ledger.gates[key(taskId, gate)];
|
|
77
|
+
if (!entry) return;
|
|
78
|
+
entry.resolved = { at: new Date().toISOString(), by, ...(channel ? { channel } : {}), ...(removed ? { removed: true } : {}) };
|
|
79
|
+
await writeLedger(projectRoot, ledger);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Reopens, in the loaded tasks, every ledgered human gate the files show cleared or
|
|
84
|
+
* removed without a clear in the ledger, marking it `tampered`.
|
|
85
|
+
*/
|
|
86
|
+
export function applyLedger(tasks, ledger) {
|
|
87
|
+
const byId = new Map(tasks.map(task => [task.id, task]));
|
|
88
|
+
for (const [name, entry] of Object.entries(ledger.gates ?? {})) {
|
|
89
|
+
if (!entry || entry.resolved) continue;
|
|
90
|
+
const match = /^(.+)\/(g\d+)@(.+)$/.exec(name);
|
|
91
|
+
if (!match) continue;
|
|
92
|
+
const [, taskId, gateId, at] = match;
|
|
93
|
+
const task = byId.get(taskId);
|
|
94
|
+
if (!task) continue;
|
|
95
|
+
task.gates = Array.isArray(task.gates) ? task.gates : [];
|
|
96
|
+
const gate = task.gates.find(item => item.id === gateId);
|
|
97
|
+
if (gate && gate.at === at && gate.kind === 'human' && !gate.resolved) continue;
|
|
98
|
+
if (gate) {
|
|
99
|
+
const { resolved, ...open } = gate;
|
|
100
|
+
task.gates = task.gates.map(item => item === gate ? { ...open, kind: 'human', at, ...(open.note ? {} : { note: 'restored: this human gate was changed outside ALP' }), tampered: { at: resolved?.at ?? null, by: resolved?.by ?? null } } : item);
|
|
101
|
+
} else {
|
|
102
|
+
task.gates = [...task.gates, { id: gateId, kind: 'human', note: 'restored: this human gate was removed outside ALP', at, tampered: { removed: true } }];
|
|
103
|
+
}
|
|
104
|
+
// A step closed by the forged approval opens again.
|
|
105
|
+
if (task.step?.human && task.status === 'closed') { task.status = 'open'; task.closed = null; }
|
|
106
|
+
}
|
|
107
|
+
return tasks;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Drops the entries that no longer guard anything (t-f438): the cleared ones, which applyLedger
|
|
112
|
+
* skips. An open entry stays even for a closed or missing task: status and presence are file
|
|
113
|
+
* state an agent can edit, so only a clear ALP recorded ends an entry. Called from compaction.
|
|
114
|
+
*/
|
|
115
|
+
export async function ledgerPrune(projectRoot) {
|
|
116
|
+
const ledger = await readLedger(projectRoot, { strict: true });
|
|
117
|
+
let dropped = 0;
|
|
118
|
+
for (const [name, entry] of Object.entries(ledger.gates)) {
|
|
119
|
+
if (entry && !entry.resolved) continue;
|
|
120
|
+
delete ledger.gates[name];
|
|
121
|
+
dropped += 1;
|
|
122
|
+
}
|
|
123
|
+
if (dropped) await writeLedger(projectRoot, ledger);
|
|
124
|
+
return dropped;
|
|
125
|
+
}
|
package/src/index.js
CHANGED
package/src/library-edit.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
1
|
+
import { cp, lstat, mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { moveFile } from './atomic.js';
|
|
@@ -8,6 +8,26 @@ import { agentSources, builtinText, jsonObject, libraryEntries, optionalText } f
|
|
|
8
8
|
import { teamSources, validateTeam } from './teams.js';
|
|
9
9
|
import { normalizeMcp, validateAgentConfig, validateHook } from './validation.js';
|
|
10
10
|
import { validateProvider } from './providers.js';
|
|
11
|
+
import { checkFrontmatter, skillReferences, specName, splitSkill } from './skill-validate.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A SKILL.md with its frontmatter `name` set to `name`, so a copied or renamed skill stays valid:
|
|
15
|
+
* the name must equal the skill's directory. A SKILL.md without frontmatter is left as it is.
|
|
16
|
+
*/
|
|
17
|
+
export function withSkillName(body, name) {
|
|
18
|
+
const match = /^(\uFEFF?---(\r?\n))([\s\S]*?)(\r?\n---[ \t]*(?:\r?\n|$))/.exec(body);
|
|
19
|
+
if (!match) return body;
|
|
20
|
+
const lines = match[3].split(/\r?\n/);
|
|
21
|
+
const at = lines.findIndex(line => /^name[ \t]*:/.test(line));
|
|
22
|
+
if (at >= 0) lines[at] = `name: ${name}`;
|
|
23
|
+
else lines.unshift(`name: ${name}`);
|
|
24
|
+
return match[1] + lines.join(match[2]) + match[4] + body.slice(match[0].length);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A skill's new name, when it carries the format's name into its frontmatter: the format's rules. */
|
|
28
|
+
function skillTarget(body, name) {
|
|
29
|
+
if (splitSkill(body).frontmatter !== undefined && !specName(name)) fail('INVALID_NAME', `'${name}' is not a skill name: use 1-64 lowercase letters, digits and single hyphens`);
|
|
30
|
+
}
|
|
11
31
|
|
|
12
32
|
/**
|
|
13
33
|
* Editing the library (ALPD §43): agents, skills, MCP servers, hooks and teams, in the
|
|
@@ -60,6 +80,46 @@ function base(scope, { root, library }, kind) {
|
|
|
60
80
|
}
|
|
61
81
|
const revisionOf = content => content === undefined ? null : createHash('sha256').update(JSON.stringify(content)).digest('hex').slice(0, 16);
|
|
62
82
|
|
|
83
|
+
/** Strict payload contract for opt-in project-data writes. Instructions carry prompt authority;
|
|
84
|
+
* executable configuration and references to it have no place in this policy. */
|
|
85
|
+
export function assertProjectDataContent(kind, content) {
|
|
86
|
+
const deny = () => fail('UNSAFE_LIBRARY_WRITE', 'Project-data writes allow only instruction entries and non-executable agent configuration');
|
|
87
|
+
if (!object(content) || !['agents', 'skills'].includes(kind)) deny();
|
|
88
|
+
const keys = kind === 'skills' ? ['body'] : ['instructions', 'config'];
|
|
89
|
+
if (Object.keys(content).some(key => !keys.includes(key))) deny();
|
|
90
|
+
const text = kind === 'skills' ? content.body : content.instructions;
|
|
91
|
+
if (typeof text !== 'string' || !text.trim()) deny();
|
|
92
|
+
if (content.config !== undefined) {
|
|
93
|
+
const config = content.config;
|
|
94
|
+
if (!object(config)) deny();
|
|
95
|
+
const allowed = ['description', 'model', 'thinking', 'context', 'autocompact'];
|
|
96
|
+
if (Object.keys(config).some(key => !allowed.includes(key))) deny();
|
|
97
|
+
for (const key of ['description', 'thinking']) if (config[key] !== undefined && typeof config[key] !== 'string') deny();
|
|
98
|
+
if (config.model !== undefined && (typeof config.model !== 'string' || !/^(codex|claude):[^\s/\\:]{1,240}$/.test(config.model))) deny();
|
|
99
|
+
for (const key of ['context', 'autocompact']) if (config[key] !== undefined && !(typeof config[key] === 'string' || typeof config[key] === 'number' && Number.isFinite(config[key]))) deny();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Authoritative mutation preflight. Reject sidecars and lower-layer collisions rather than
|
|
104
|
+
* moving executable assets or revealing a different host configuration. Like safeEntryPaths,
|
|
105
|
+
* this protects static repository input, not a concurrently malicious same-user process. */
|
|
106
|
+
async function projectDataEntry(kind, name, { scope, root, library, templates }) {
|
|
107
|
+
if (scope !== 'project' || !root || !['agents', 'skills'].includes(kind)) fail('UNSAFE_LIBRARY_WRITE', 'Project-data writes require project scope and agents or skills');
|
|
108
|
+
nameOf(name);
|
|
109
|
+
const directory = base(scope, { root, library }, kind);
|
|
110
|
+
await safeEntryPaths(directory, kind, name);
|
|
111
|
+
const found = await layers(kind, name, { root, library, templates });
|
|
112
|
+
if (found.library !== undefined || found.builtin !== undefined) fail('UNSAFE_LIBRARY_WRITE', 'Project-data writes cannot shadow or reveal a library or built-in entry');
|
|
113
|
+
if (found.project !== undefined) assertProjectDataContent(kind, found.project);
|
|
114
|
+
const owned = path.join(directory, kind, name);
|
|
115
|
+
const files = await readdir(owned).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
116
|
+
const allowed = new Set(FILES[kind](name).map(([file]) => path.basename(file)));
|
|
117
|
+
for (const file of files) {
|
|
118
|
+
const info = await lstat(path.join(owned, file));
|
|
119
|
+
if (!allowed.has(file) || !info.isFile() || info.isSymbolicLink() || info.nlink !== 1) fail('UNSAFE_LIBRARY_WRITE', 'Project-data entries cannot contain sidecars, links or executable assets');
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
63
123
|
/** Reject repository-controlled links before any entry read or mutation. This is
|
|
64
124
|
* a preflight for static repository input, not a sandbox against same-user races. */
|
|
65
125
|
async function safeEntryPaths(directory, kind, name) {
|
|
@@ -138,12 +198,12 @@ export async function getEntry(kind, name, { root, library, templates, scope } =
|
|
|
138
198
|
async function readGiven(library) {
|
|
139
199
|
const file = path.join(library, 'role-skills.json');
|
|
140
200
|
const text = await optionalText(file);
|
|
141
|
-
if (text === undefined) return { file, roles:
|
|
201
|
+
if (text === undefined) return { file, roles: Object.create(null) };
|
|
142
202
|
let roles;
|
|
143
203
|
try { roles = JSON.parse(text); }
|
|
144
204
|
catch (cause) { throw new AlpError('INVALID_LIBRARY', `${file}: ${cause.message}`, { cause }); }
|
|
145
205
|
if (!object(roles)) fail('INVALID_LIBRARY', `${file}: expected an object of agent names to skill lists`);
|
|
146
|
-
return { file, roles };
|
|
206
|
+
return { file, roles: Object.assign(Object.create(null), roles) };
|
|
147
207
|
}
|
|
148
208
|
|
|
149
209
|
/** The skills the library gives `agent`, as role-skills.json lists them. */
|
|
@@ -169,6 +229,102 @@ export async function setGivenSkills(agent, skills, { library } = {}) {
|
|
|
169
229
|
return { skills: unique };
|
|
170
230
|
}
|
|
171
231
|
|
|
232
|
+
/** Where alp_skill_retire keeps retired skills, and the metadata file it writes in each. */
|
|
233
|
+
export const RETIRED_SKILLS = 'retired-skills';
|
|
234
|
+
export const RETIRED_METADATA = 'retired.json';
|
|
235
|
+
// <name>-<ISO time with ':' and '.' replaced by '-'>, as alp_skill_retire names the folder.
|
|
236
|
+
const RETIRED_FOLDER = /^(.+)-(\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d-\d{3}Z)$/;
|
|
237
|
+
|
|
238
|
+
async function retiredMetadata(directory) {
|
|
239
|
+
const text = await optionalText(path.join(directory, RETIRED_METADATA));
|
|
240
|
+
if (text === undefined) return undefined;
|
|
241
|
+
let data;
|
|
242
|
+
try { data = JSON.parse(text); } catch (cause) { throw new AlpError('INVALID_LIBRARY', `${path.join(directory, RETIRED_METADATA)}: ${cause.message}`, { cause }); }
|
|
243
|
+
if (!object(data) || !Array.isArray(data.roles) || !data.roles.every(validName)) fail('INVALID_LIBRARY', `${path.join(directory, RETIRED_METADATA)}: expected { name, roles: [...] }`);
|
|
244
|
+
return data;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The library's retired skills, newest first. `roles` is what retired.json recorded,
|
|
249
|
+
* or null for a skill retired before ALP wrote it.
|
|
250
|
+
* @returns {Promise<{ name: string, directory: string, retiredAt: string, roles: string[] | null, agent: string | null }[]>}
|
|
251
|
+
*/
|
|
252
|
+
export async function listRetiredSkills({ library } = {}) {
|
|
253
|
+
if (!library) fail('INVALID_SCOPE', 'No library: ALP_HOME is not set');
|
|
254
|
+
const root = path.join(library, RETIRED_SKILLS);
|
|
255
|
+
const entries = await readdir(root, { withFileTypes: true }).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
|
|
256
|
+
const rows = [];
|
|
257
|
+
for (const entry of entries) {
|
|
258
|
+
const match = entry.isDirectory() && RETIRED_FOLDER.exec(entry.name);
|
|
259
|
+
if (!match) continue;
|
|
260
|
+
const directory = path.join(root, entry.name);
|
|
261
|
+
// A corrupt retired.json must not hide the other retired skills: list the copy
|
|
262
|
+
// without roles, and restore then asks for --roles or --no-roles.
|
|
263
|
+
let meta, invalid;
|
|
264
|
+
try { meta = await retiredMetadata(directory); } catch (error) { invalid = error.message; }
|
|
265
|
+
const stamp = match[2].replace(/T(\d\d)-(\d\d)-(\d\d)-(\d{3})Z$/, 'T$1:$2:$3.$4Z');
|
|
266
|
+
rows.push({ name: match[1], directory, retiredAt: typeof meta?.retiredAt === 'string' ? meta.retiredAt : stamp, roles: meta ? meta.roles : null, agent: typeof meta?.agent === 'string' ? meta.agent : null, ...(invalid ? { invalid } : {}) });
|
|
267
|
+
}
|
|
268
|
+
return rows.sort((a, b) => b.retiredAt.localeCompare(a.retiredAt) || b.directory.localeCompare(a.directory));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Moves a retired skill back to <library>/skills/<name> and gives it to roles again in
|
|
273
|
+
* role-skills.json: `roles` when given ([] for none), else the roles retired.json recorded.
|
|
274
|
+
* Takes `from` when given, else the newest retired copy of the name. Refuses when the
|
|
275
|
+
* library already has the skill, or when neither `roles` nor retired.json says the roles.
|
|
276
|
+
* @returns {Promise<{ name: string, restored: string, from: string, roles: string[] }>}
|
|
277
|
+
*/
|
|
278
|
+
export async function restoreSkill(name, { library, from, roles } = {}) {
|
|
279
|
+
nameOf(name);
|
|
280
|
+
if (!library) fail('INVALID_SCOPE', 'No library: ALP_HOME is not set');
|
|
281
|
+
if (roles !== undefined && (!Array.isArray(roles) || !roles.every(validName))) fail('INVALID_ENTRY', 'Roles must be a list of agent names');
|
|
282
|
+
let source;
|
|
283
|
+
if (from !== undefined) {
|
|
284
|
+
source = path.resolve(from);
|
|
285
|
+
const info = await lstat(source).catch(() => undefined);
|
|
286
|
+
if (info?.isSymbolicLink()) fail('INVALID_ENTRY', `${source} is a symbolic link; pass the directory itself`);
|
|
287
|
+
if (!info?.isDirectory()) fail('NOT_FOUND', `${source} is not a directory`);
|
|
288
|
+
} else {
|
|
289
|
+
const found = (await listRetiredSkills({ library })).find(row => row.name === name);
|
|
290
|
+
if (!found) fail('NOT_FOUND', `No retired skill '${name}' in ${path.join(library, RETIRED_SKILLS)}`);
|
|
291
|
+
source = found.directory;
|
|
292
|
+
}
|
|
293
|
+
if (!(await exists(path.join(source, 'SKILL.md')))) fail('NOT_FOUND', `${source} has no SKILL.md`);
|
|
294
|
+
const target = path.join(library, 'skills', name);
|
|
295
|
+
if (await lstat(target).then(() => true, () => false)) fail('ALREADY_EXISTS', `The library already has a skill '${name}' (${target}); nothing was restored`);
|
|
296
|
+
const metaFile = path.join(source, RETIRED_METADATA);
|
|
297
|
+
const metaText = await optionalText(metaFile);
|
|
298
|
+
let meta;
|
|
299
|
+
try { meta = await retiredMetadata(source); } catch (error) { if (error?.code !== 'INVALID_LIBRARY' || roles === undefined) throw error; }
|
|
300
|
+
if (meta && meta.name !== undefined && meta.name !== name) fail('INVALID_ENTRY', `${metaFile} is for the skill '${meta.name}', not '${name}'`);
|
|
301
|
+
const given = roles ?? meta?.roles;
|
|
302
|
+
if (!given) fail('ROLES_REQUIRED', `${source} does not record the roles that had '${name}'; pass --roles a,b or --no-roles`);
|
|
303
|
+
const unique = [...new Set(given)];
|
|
304
|
+
const { file: rolesFile, roles: current } = await readGiven(library);
|
|
305
|
+
const before = await optionalText(rolesFile);
|
|
306
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
307
|
+
await moveFile(source, target);
|
|
308
|
+
try {
|
|
309
|
+
if (metaText !== undefined) await rm(path.join(target, RETIRED_METADATA), { force: true });
|
|
310
|
+
if (unique.length) {
|
|
311
|
+
for (const role of unique) {
|
|
312
|
+
const list = Array.isArray(current[role]) ? current[role] : [];
|
|
313
|
+
if (!list.includes(name)) list.push(name);
|
|
314
|
+
current[role] = list;
|
|
315
|
+
}
|
|
316
|
+
await writeAtomic(rolesFile, JSON.stringify(current, null, 2) + '\n');
|
|
317
|
+
}
|
|
318
|
+
} catch (error) {
|
|
319
|
+
// Put everything back, so a failed restore changes nothing.
|
|
320
|
+
if (before !== undefined) await writeAtomic(rolesFile, before).catch(() => {});
|
|
321
|
+
if (metaText !== undefined) await writeFile(path.join(target, RETIRED_METADATA), metaText).catch(() => {});
|
|
322
|
+
await moveFile(target, source).catch(() => {});
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
return { name, restored: target, from: source, roles: unique };
|
|
326
|
+
}
|
|
327
|
+
|
|
172
328
|
/** Every entry of a kind with its source and users, as `alp <kind>` lists them. */
|
|
173
329
|
export async function listEntries(kind, { root, library, templates } = {}) {
|
|
174
330
|
kindOf(kind);
|
|
@@ -272,10 +428,28 @@ const exists = target => stat(target).then(() => true, () => false);
|
|
|
272
428
|
/**
|
|
273
429
|
* Creates or replaces an entry in a scope. `revision` is what getEntry returned for
|
|
274
430
|
* that scope (null to create); a different current revision refuses the save.
|
|
275
|
-
*
|
|
431
|
+
* `strict` (the CLI creating a skill): a new skill must meet the skill format; `warnings` names
|
|
432
|
+
* files its SKILL.md points to that are not there yet. Edits and other callers are unchanged.
|
|
433
|
+
* @param {string} kind
|
|
434
|
+
* @param {string} name
|
|
435
|
+
* @param {any} content
|
|
436
|
+
* @param {{ scope?: any, root?: string, library?: string, templates?: Record<string, string>, revision?: string | null, policy?: string, strict?: boolean }} [options]
|
|
437
|
+
* @returns {Promise<{ revision: string | null, warnings?: string[] }>}
|
|
276
438
|
*/
|
|
277
|
-
export async function saveEntry(kind, name, content, { scope, root, library, templates, revision } = {}) {
|
|
439
|
+
export async function saveEntry(kind, name, content, { scope, root, library, templates, revision, policy, strict = false } = {}) {
|
|
278
440
|
kindOf(kind); nameOf(name);
|
|
441
|
+
// A new skill made by the CLI (strict) meets the skill format; existing skills are saved as before.
|
|
442
|
+
const warnings = [];
|
|
443
|
+
if (strict && kind === 'skills' && revision === null && typeof content?.body === 'string') {
|
|
444
|
+
const errors = checkFrontmatter(splitSkill(content.body).frontmatter, name, { strict: true }).findings.filter(finding => finding.level === 'error');
|
|
445
|
+
if (errors.length) fail('INVALID_ENTRY', `skills '${name}' does not meet the skill format: ${errors.map(finding => finding.message).join('; ')}`);
|
|
446
|
+
const links = skillReferences(splitSkill(content.body).body);
|
|
447
|
+
if (links.length) warnings.push(`SKILL.md points to ${links.join(', ')}: add ${links.length > 1 ? 'those files' : 'that file'} beside it, in the skill's directory`);
|
|
448
|
+
}
|
|
449
|
+
if (policy === 'project-data') {
|
|
450
|
+
assertProjectDataContent(kind, content);
|
|
451
|
+
await projectDataEntry(kind, name, { scope, root, library, templates });
|
|
452
|
+
}
|
|
279
453
|
const directory = base(scope, { root, library }, kind);
|
|
280
454
|
await safeEntryPaths(directory, kind, name);
|
|
281
455
|
await check(kind, name, content, { scope, root, library, templates });
|
|
@@ -292,7 +466,7 @@ export async function saveEntry(kind, name, content, { scope, root, library, tem
|
|
|
292
466
|
if (empty) { await rm(target, { force: true }); continue; }
|
|
293
467
|
await writeAtomic(target, type === 'json' ? JSON.stringify(value, null, 2) + '\n' : value.endsWith('\n') ? value : `${value}\n`);
|
|
294
468
|
}
|
|
295
|
-
return { revision: revisionOf(await readLayer(kind, name, directory)) };
|
|
469
|
+
return { revision: revisionOf(await readLayer(kind, name, directory)), ...(warnings.length ? { warnings } : {}) };
|
|
296
470
|
}
|
|
297
471
|
|
|
298
472
|
/**
|
|
@@ -300,8 +474,9 @@ export async function saveEntry(kind, name, content, { scope, root, library, tem
|
|
|
300
474
|
* entry others refer to stays, and the error lists them.
|
|
301
475
|
* @returns {Promise<{ removed: boolean, now?: 'builtin' | 'library' }>}
|
|
302
476
|
*/
|
|
303
|
-
export async function deleteEntry(kind, name, { scope, root, library, templates, revision } = {}) {
|
|
477
|
+
export async function deleteEntry(kind, name, { scope, root, library, templates, revision, policy } = {}) {
|
|
304
478
|
kindOf(kind); nameOf(name);
|
|
479
|
+
if (policy === 'project-data') await projectDataEntry(kind, name, { scope, root, library, templates });
|
|
305
480
|
const directory = base(scope, { root, library }, kind);
|
|
306
481
|
const current = await readLayer(kind, name, directory);
|
|
307
482
|
if (current === undefined) fail('NOT_FOUND', `No ${kind} entry '${name}' in the ${scope}`);
|
|
@@ -320,14 +495,52 @@ export async function deleteEntry(kind, name, { scope, root, library, templates,
|
|
|
320
495
|
}
|
|
321
496
|
|
|
322
497
|
/** Copies the entry that applies under `from` to a new entry `to` in a scope; built-ins are copied this way. */
|
|
323
|
-
export async function duplicateEntry(kind, from, to, { scope, root, library, templates } = {}) {
|
|
324
|
-
|
|
325
|
-
|
|
498
|
+
export async function duplicateEntry(kind, from, to, { scope, root, library, templates, policy } = {}) {
|
|
499
|
+
kindOf(kind); nameOf(from); nameOf(to);
|
|
500
|
+
if (policy === 'project-data') {
|
|
501
|
+
await projectDataEntry(kind, from, { scope, root, library, templates });
|
|
502
|
+
await projectDataEntry(kind, to, { scope, root, library, templates });
|
|
503
|
+
}
|
|
504
|
+
const entry = await getEntry(kind, from, { root, library, templates });
|
|
505
|
+
if (kind === 'skills') { skillTarget(entry.content.body, to); entry.content.body = withSkillName(entry.content.body, to); }
|
|
506
|
+
// A skill is its directory: its references, scripts and assets go with SKILL.md, bytes and modes kept.
|
|
507
|
+
const resources = kind === 'skills' && policy !== 'project-data' ? await skillResources(entry.source === 'project' ? path.join(path.resolve(root), '.alp', 'skills', from) : path.join(library, 'skills', from)) : [];
|
|
508
|
+
const saved = await saveEntry(kind, to, structuredClone(entry.content), { scope, root, library, templates, revision: null, policy });
|
|
509
|
+
if (resources.length) {
|
|
510
|
+
const target = path.join(base(scope, { root, library }, kind), kind, to);
|
|
511
|
+
try { for (const [source, relative] of resources) await cp(source, path.join(target, relative), { recursive: true, errorOnExist: true, force: false }); }
|
|
512
|
+
catch (error) {
|
|
513
|
+
// Half a copy is no skill: the new entry (made just above, so nobody else's) goes again.
|
|
514
|
+
await rm(target, { recursive: true, force: true });
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return saved;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** A skill directory's entries besides SKILL.md, as [absolute, relative]; refused when it holds a link. */
|
|
522
|
+
async function skillResources(directory) {
|
|
523
|
+
const found = [];
|
|
524
|
+
const walk = async relative => {
|
|
525
|
+
for (const item of await readdir(path.join(directory, relative), { withFileTypes: true }).catch(error => { if (error.code === 'ENOENT') return []; throw error; })) {
|
|
526
|
+
const rel = path.join(relative, item.name);
|
|
527
|
+
if (item.name === '.git' || item.name === 'node_modules') continue;
|
|
528
|
+
if (item.isSymbolicLink()) fail('UNSAFE_LIBRARY_WRITE', `${path.join(directory, rel)} is a symbolic link; copy the skill by hand`);
|
|
529
|
+
if (item.isDirectory()) await walk(rel);
|
|
530
|
+
else if (item.isFile() && rel !== 'SKILL.md') found.push([path.join(directory, rel), rel]);
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
await walk('');
|
|
534
|
+
return found;
|
|
326
535
|
}
|
|
327
536
|
|
|
328
537
|
/** Renames an entry within a scope; refused while others refer to it by its old name. */
|
|
329
|
-
export async function renameEntry(kind, from, to, { scope, root, library, templates } = {}) {
|
|
538
|
+
export async function renameEntry(kind, from, to, { scope, root, library, templates, policy } = {}) {
|
|
330
539
|
kindOf(kind); nameOf(from); nameOf(to);
|
|
540
|
+
if (policy === 'project-data') {
|
|
541
|
+
await projectDataEntry(kind, from, { scope, root, library, templates });
|
|
542
|
+
await projectDataEntry(kind, to, { scope, root, library, templates });
|
|
543
|
+
}
|
|
331
544
|
const directory = base(scope, { root, library }, kind);
|
|
332
545
|
const content = await readLayer(kind, from, directory);
|
|
333
546
|
if (content === undefined) fail('NOT_FOUND', `No ${kind} entry '${from}' in the ${scope}`);
|
|
@@ -335,12 +548,14 @@ export async function renameEntry(kind, from, to, { scope, root, library, templa
|
|
|
335
548
|
const users = await usersOf(kind, from, { root, library, templates });
|
|
336
549
|
if (users.length) fail('IN_USE', `${kind} '${from}' is used by ${users.join(', ')}; change them first`);
|
|
337
550
|
await check(kind, to, content, { scope, root, library, templates });
|
|
551
|
+
if (kind === 'skills') skillTarget(content.body, to);
|
|
338
552
|
if (ownDirectory(kind)) {
|
|
339
553
|
if (await exists(path.join(directory, kind, to))) fail('REVISION_CONFLICT', `${path.join(directory, kind, to)} already exists`);
|
|
340
554
|
await rename(path.join(directory, kind, from), path.join(directory, kind, to));
|
|
555
|
+
// The moved skill's frontmatter names its new directory.
|
|
556
|
+
if (kind === 'skills' && withSkillName(content.body, to) !== content.body) await writeAtomic(path.join(directory, kind, to, 'SKILL.md'), withSkillName(content.body, to));
|
|
341
557
|
} else {
|
|
342
558
|
await rename(path.join(directory, kind, `${from}.json`), path.join(directory, kind, `${to}.json`));
|
|
343
559
|
}
|
|
344
560
|
return { revision: revisionOf(await readLayer(kind, to, directory)) };
|
|
345
561
|
}
|
|
346
|
-
|