@anhlp/alp-core 0.0.1-beta.3 → 0.0.1-beta.5

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 (44) hide show
  1. package/dist/backup.js +106 -4
  2. package/dist/bridges.d.ts +27 -0
  3. package/dist/bridges.js +97 -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/migrations.js +1 -1
  9. package/dist/models.d.ts +39 -0
  10. package/dist/models.js +51 -1
  11. package/dist/packaged.d.ts +96 -0
  12. package/dist/packaged.js +198 -0
  13. package/dist/providers.d.ts +3 -1
  14. package/dist/providers.js +6 -1
  15. package/dist/task-rows.d.ts +5 -0
  16. package/dist/task-rows.js +1 -1
  17. package/dist/tasks.d.ts +22 -4
  18. package/dist/tasks.js +97 -9
  19. package/dist/template-path.d.ts +2 -2
  20. package/dist/template-path.js +5 -0
  21. package/dist/types.d.ts +1 -0
  22. package/dist/user-worktree.d.ts +29 -0
  23. package/dist/user-worktree.js +242 -0
  24. package/dist/validation.js +19 -4
  25. package/package.json +18 -2
  26. package/src/backup.js +106 -5
  27. package/src/bridges.js +113 -0
  28. package/src/gate-ledger.js +125 -0
  29. package/src/index.js +1 -0
  30. package/src/migrations.js +1 -1
  31. package/src/models.js +63 -1
  32. package/src/packaged.js +255 -0
  33. package/src/providers.js +4 -2
  34. package/src/task-rows.js +1 -1
  35. package/src/tasks.d.ts +22 -4
  36. package/src/tasks.js +126 -10
  37. package/src/template-path.js +6 -1
  38. package/src/types.d.ts +1 -0
  39. package/src/user-worktree.js +259 -0
  40. package/src/validation.js +22 -4
  41. package/templates/agents/main/AGENT.md +4 -0
  42. package/templates/role-skills.json +1 -1
  43. package/templates/skills/compact/SKILL.md +34 -0
  44. package/templates/skills/curate/SKILL.md +35 -0
@@ -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
@@ -29,3 +29,4 @@ export * as user_settings from './user-settings.js';
29
29
  export * as validation from './validation.js';
30
30
  export * as verify from './verify.js';
31
31
  export * as workflow from './workflow.js';
32
+ export * as user_worktree from './user-worktree.js';
package/src/migrations.js CHANGED
@@ -98,7 +98,7 @@ export async function migrateState(home, { by = 'alp', migrations = MIGRATIONS,
98
98
  throw new AlpError('STATE_MIGRATION_ROLLBACK_FAILED', `state migration ${step.name} failed (${error?.message ?? error}) and putting the state back from ${backup} failed too (${rollback?.message ?? rollback}); the next start tries the migration again. See docs/alp/data-recovery.md`, { cause: error });
99
99
  }
100
100
  await rm(migrationFile(home), { force: true });
101
- throw new AlpError('STATE_MIGRATION_FAILED', `state migration ${step.name} (schema ${step.from} → ${step.to}) failed: ${error?.message ?? error}; the state was put back from ${backup} and is unchanged. See docs/alp/data-recovery.md`, { cause: error });
101
+ throw new AlpError('STATE_MIGRATION_FAILED', `state migration ${step.name} (schema ${step.from} → ${step.to}) failed: ${error?.message ?? error}; data was restored from ${backup} with workspace authority checks. See docs/alp/data-recovery.md`, { cause: error });
102
102
  }
103
103
  await writeStateSchema(home, step.to, by);
104
104
  await rm(migrationFile(home), { force: true });
package/src/models.js CHANGED
@@ -1,4 +1,7 @@
1
- /** Models ALP offers, with the efforts each takes: the runtime's catalog and alp setup read this list. */
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /** Models ALP offers when no provider has answered yet (the live catalog, t-e5ee, merges provider lists over these), with the efforts each takes: the runtime's catalog and alp setup read this list. */
2
5
  const codexFull = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
3
6
  const codexStandard = ['low', 'medium', 'high', 'xhigh', 'max'];
4
7
  const claudeFull = ['low', 'medium', 'high', 'xhigh', 'max', 'ultracode'];
@@ -43,3 +46,62 @@ export const MODELS = [
43
46
  ['antigravity', 'claude-opus-4-6-thinking', 'Claude Opus 4.6 Thinking', 'Opus 4.6 with thinking via Antigravity.', [], undefined],
44
47
  ['antigravity', 'gpt-oss-120b-medium', 'GPT-OSS 120B (Medium)', 'Open weights model via Antigravity.', [], undefined],
45
48
  ].map(([runtime, id, label, description, efforts, effort]) => ({ runtime, id, label, description, efforts, ...(effort ? { effort } : {}) }));
49
+
50
+ /** ALP policy applied over whatever a provider reports. */
51
+ export const MODEL_POLICY = {
52
+ // ALP runs GPT-6 Astra at low effort only.
53
+ 'codex:gpt-6-astra': { efforts: ['low'], effort: 'low' },
54
+ };
55
+ const CATALOG_RUNTIMES = ['codex', 'claude', 'antigravity'];
56
+
57
+ /**
58
+ * Live over static (t-e5ee): a runtime with a live list shows its live models first, in the provider's
59
+ * order, with the provider's label and description; a live model ALP knows keeps ALP's efforts (plus any
60
+ * new ones the provider adds) and ALP's default effort, a new one takes the provider's. Static rows the
61
+ * provider did not report stay as `fallback` (aliases, 1M variants). A runtime without a live list keeps
62
+ * its static rows. MODEL_POLICY applies last.
63
+ * @param {typeof MODELS} base
64
+ * @param {Partial<Record<string, Array<{ id: string, label?: string, description?: string, efforts?: string[], effort?: string }> | undefined>>} live
65
+ * @returns {Array<(typeof MODELS)[number] & { source?: 'live' | 'fallback' | 'static' }>}
66
+ */
67
+ export function mergeCatalog(base, live) {
68
+ const out = [];
69
+ for (const runtime of CATALOG_RUNTIMES) {
70
+ const known = base.filter(entry => entry.runtime === runtime);
71
+ const listed = live?.[runtime];
72
+ const reported = (Array.isArray(listed) ? listed : []).filter(model => typeof model?.id === 'string' && model.id.trim());
73
+ if (!reported.length) { out.push(...known); continue; }
74
+ const seen = new Set();
75
+ for (const model of reported) {
76
+ if (seen.has(model.id)) continue;
77
+ seen.add(model.id);
78
+ const prior = known.find(entry => entry.id === model.id);
79
+ const priorEfforts = prior?.efforts ?? [];
80
+ const efforts = [...priorEfforts, ...(Array.isArray(model.efforts) ? model.efforts : []).filter(effort => typeof effort === 'string' && !priorEfforts.includes(effort))];
81
+ const effort = prior?.effort ?? (typeof model.effort === 'string' && efforts.includes(model.effort) ? model.effort : undefined);
82
+ const text = value => typeof value === 'string' && value ? value : undefined;
83
+ out.push({ runtime, id: model.id, label: text(model.label) ?? prior?.label ?? model.id, description: text(model.description) ?? prior?.description ?? '', efforts, ...(effort ? { effort } : {}), source: 'live' });
84
+ }
85
+ for (const entry of known) if (!seen.has(entry.id)) out.push({ ...entry, source: 'fallback' });
86
+ }
87
+ return out.map(entry => {
88
+ const policy = MODEL_POLICY[`${entry.runtime}:${entry.id}`];
89
+ return policy ? { ...entry, ...policy } : entry;
90
+ });
91
+ }
92
+
93
+ /** Where alpd caches the live catalog: ALP_HOME/cache/models.json. @param {string} home */
94
+ export const catalogCacheFile = home => path.join(home, 'cache', 'models.json');
95
+
96
+ /**
97
+ * The catalog as alpd last saw it, for readers outside alpd (alp setup, the Paseo plugin): static rows
98
+ * when there is no cache or it is unreadable. @param {string | undefined} home
99
+ */
100
+ export function catalogModels(home) {
101
+ if (!home) return MODELS;
102
+ try {
103
+ const cached = JSON.parse(readFileSync(catalogCacheFile(home), 'utf8'));
104
+ const providers = cached?.providers && typeof cached.providers === 'object' ? cached.providers : {};
105
+ return mergeCatalog(MODELS, Object.fromEntries(Object.entries(providers).map(([runtime, state]) => [runtime, Array.isArray(state?.models) ? state.models : undefined])));
106
+ } catch { return MODELS; }
107
+ }
@@ -0,0 +1,255 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ /**
7
+ * ALP runs either as npm scripts under Node (`node cli.js`, `node alpd.js`) or as one self-contained
8
+ * executable (`alp`, built with `bun build --compile`, t-1e02). In the executable, `process.execPath`
9
+ * is ALP itself: it cannot run a script path, and `-e code` is not evaluated. Every place that starts
10
+ * another ALP process asks this module for the command instead of spawning `process.execPath`.
11
+ *
12
+ * The executable's entry registers itself before importing anything else; the registration lives
13
+ * on globalThis because alpd.js and the CLI each inline their own copy of this module.
14
+ */
15
+
16
+ const KEY = Symbol.for('alp.packaged');
17
+
18
+ /** Subcommands of the executable that run each ALP role (the npm CLI understands them too). */
19
+ export const ROLE_ARGS = Object.freeze({
20
+ daemon: Object.freeze(['daemon', 'run']),
21
+ web: Object.freeze(['web', 'serve']),
22
+ 'bridge-acp': Object.freeze(['bridge', 'acp']),
23
+ 'bridge-antigravity': Object.freeze(['bridge', 'antigravity']),
24
+ });
25
+
26
+ /**
27
+ * @typedef {{ path: string, sha256: string, size: number }} PackagedAsset
28
+ * @typedef {{ version: string, assets?: Record<string, PackagedAsset>, roles?: Record<string, () => Promise<unknown>> }} PackagedRegistration
29
+ */
30
+
31
+ /** Called once by the executable's entry. @param {PackagedRegistration} registration */
32
+ export function registerPackaged(registration) {
33
+ if (!registration || typeof registration.version !== 'string') throw new TypeError('registerPackaged needs a version');
34
+ // assetDir rides along so dependency-free adapters (native-terminal.js) can reach the cache via globalThis alone.
35
+ Object.defineProperty(globalThis, KEY, { value: Object.freeze({ ...registration, assetDir: () => assetDir() }), configurable: true, enumerable: false, writable: false });
36
+ }
37
+
38
+ /** The registration when this process is the ALP executable, else undefined. @returns {PackagedRegistration | undefined} */
39
+ export function packagedInfo() { return /** @type {any} */ (globalThis)[KEY]; }
40
+
41
+ /** Whether this process is the self-contained ALP executable. */
42
+ export function isPackaged() { return packagedInfo() !== undefined; }
43
+
44
+ /**
45
+ * A string only ALP's executable carries: its generated entry embeds it, so discovery can tell ALP
46
+ * from an unrelated native program that happens to be called `alp` without running it.
47
+ */
48
+ export const EXECUTABLE_MARKER = 'alp-standalone-executable:v1:2b6f0c1e';
49
+
50
+ /** Whether `file` is named like the ALP executable (alp, alp.exe). @param {string} file */
51
+ export const isExecutableName = file => /^alp(\.exe)?$/i.test(file.split(/[\\/]/).pop() ?? '');
52
+
53
+ /** Whether `file` is this process's own ALP executable, whatever it is called (alp-darwin-arm64, a rename). @param {unknown} file */
54
+ export const isSelf = file => isPackaged() && typeof file === 'string' && samePath(file, process.execPath);
55
+
56
+ /** The canonical form of a path: symlinks resolved when it exists, case-folded where the filesystem usually is. @param {string} file */
57
+ const canonical = file => {
58
+ let resolved = path.resolve(file);
59
+ try { resolved = realpathSync.native(resolved); } catch {}
60
+ return process.platform === 'darwin' || process.platform === 'win32' ? resolved.toLowerCase() : resolved;
61
+ };
62
+
63
+ /** Whether two paths name the same file (a symlink such as ~/.alp/bin/alp, or a differently cased path on macOS/Windows). @param {string} a @param {string} b */
64
+ export const samePath = (a, b) => canonical(a) === canonical(b);
65
+
66
+ /** A file path that names a JavaScript entry rather than an executable. @param {string} file */
67
+ export const isScript = file => /\.[cm]?js$/i.test(file);
68
+
69
+ /** The role's argument prefix. @param {keyof typeof ROLE_ARGS} role */
70
+ function roleArgs(role) {
71
+ const args = ROLE_ARGS[role];
72
+ if (!args) throw new TypeError(`Unknown ALP role: ${role}`);
73
+ return [...args];
74
+ }
75
+
76
+ /**
77
+ * The command that starts ALP's `role` from this process: the executable's subcommand when packaged,
78
+ * else `script` under this Node, exactly as before.
79
+ * @param {keyof typeof ROLE_ARGS} role
80
+ * @param {{ script: string, args?: string[] }} options
81
+ * @returns {{ command: string, args: string[] }}
82
+ */
83
+ export function selfCommand(role, { script, args = [] }) {
84
+ if (isPackaged()) return { command: process.execPath, args: [...roleArgs(role), ...args] };
85
+ return { command: process.execPath, args: [script, ...args] };
86
+ }
87
+
88
+ /**
89
+ * The command that runs an `entry` found on disk (an install record, a service definition, a CLI
90
+ * on PATH): a script runs under `execPath`; an executable runs its own role subcommand.
91
+ * @param {string} entry
92
+ * @param {keyof typeof ROLE_ARGS} role
93
+ * @param {string[]} [args]
94
+ * @param {string} [execPath]
95
+ * @param {{ scriptOnly?: boolean }} [options] scriptOnly: `entry` is always run under execPath (third-party integrations)
96
+ * @returns {{ command: string, args: string[] }}
97
+ */
98
+ export function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
99
+ // Only a file named alp/alp.exe, or this very executable under any name, is native; anything else
100
+ // (alpd.js, alpd.ts, a launcher) is a script.
101
+ if (scriptOnly || isScript(entry) || !(isExecutableName(entry) || isSelf(entry))) {
102
+ // The executable cannot run a script itself; a script entry then needs a real Node.
103
+ if (isPackaged() && execPath === process.execPath) return { command: 'node', args: [entry, ...args] };
104
+ return { command: execPath, args: [entry, ...args] };
105
+ }
106
+ return { command: entry, args: [...roleArgs(role), ...args] };
107
+ }
108
+
109
+ /**
110
+ * The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows)
111
+ * with this process's runtime. The executable runs it as Bun does when BUN_BE_BUN is set.
112
+ * @param {string} script
113
+ * @param {string[]} [args]
114
+ * @returns {{ command: string, args: string[], env?: Record<string, string> }}
115
+ */
116
+ export function scriptCommand(script, args = []) {
117
+ if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: '1' } };
118
+ return { command: process.execPath, args: [script, ...args] };
119
+ }
120
+
121
+ /** The ALP executable's path when this process is it, else undefined. */
122
+ export function executablePath() { return isPackaged() ? process.execPath : undefined; }
123
+
124
+ /** Where this process's own entry lives: the executable when packaged, else `script`. @param {string} script */
125
+ export function selfEntry(script) { return isPackaged() ? process.execPath : script; }
126
+
127
+ const sha256 = (/** @type {Buffer} */ bytes) => createHash('sha256').update(bytes).digest('hex');
128
+ const MARKER = '.alp-assets.json';
129
+
130
+ /** The directory the executable's assets are extracted to. @param {string} version @param {NodeJS.ProcessEnv} [env] */
131
+ export function assetCacheDir(version, env = process.env) {
132
+ if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) throw new TypeError(`Invalid ALP version for the asset cache: ${JSON.stringify(version)}`);
133
+ const home = env.ALP_HOME ? path.resolve(env.ALP_HOME) : path.join(os.homedir(), '.alp');
134
+ return path.join(home, 'cache', version);
135
+ }
136
+
137
+ /** The manifest digest the marker records, so a changed build never reuses an older extraction. @param {Record<string, PackagedAsset>} assets */
138
+ const manifestDigest = assets => sha256(Buffer.from(JSON.stringify(Object.keys(assets).sort().map(name => [name, assets[name].sha256, assets[name].size]))));
139
+
140
+ /** Rejects names that would leave the cache directory. @param {string} name */
141
+ function assertAssetName(name) {
142
+ if (!name || path.isAbsolute(name) || name.split(/[\\/]/).some(part => part === '..' || part === '' || part === '.') || name === MARKER) throw new Error(`Invalid packaged asset name: ${JSON.stringify(name)}`);
143
+ }
144
+
145
+ /** A private directory we own, not a symlink. @param {string} directory */
146
+ function assertPrivate(directory) {
147
+ const info = lstatSync(directory);
148
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache is not a directory: ${directory}`);
149
+ if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)) throw new Error(`ALP asset cache must be private to the current user (0700): ${directory}`);
150
+ }
151
+
152
+ /** The cache parent (<ALP_HOME>/cache): a real directory of ours that nobody else may write into. @param {string} directory */
153
+ function assertParent(directory) {
154
+ const info = lstatSync(directory);
155
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache parent is not a directory: ${directory}`);
156
+ if (process.platform !== 'win32' && (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) throw new Error(`ALP asset cache parent must belong to the current user and not be group- or world-writable: ${directory}`);
157
+ }
158
+
159
+ /** Whether `directory` holds exactly this manifest's extraction: every file's size and sha256 match. */
160
+ function extracted(/** @type {string} */ directory, /** @type {string} */ digest, /** @type {Record<string, PackagedAsset>} */ assets) {
161
+ try {
162
+ if (JSON.parse(readFileSync(path.join(directory, MARKER), 'utf8')).digest !== digest) return false;
163
+ return Object.entries(assets).every(([name, asset]) => {
164
+ const file = path.join(directory, name);
165
+ const info = lstatSync(file);
166
+ return info.isFile() && info.size === asset.size && sha256(readFileSync(file)) === asset.sha256;
167
+ });
168
+ } catch { return false; }
169
+ }
170
+
171
+ const STAGING = /^(.+)\.tmp-(\d+)-(\d+)$/;
172
+ const STALE_MS = 60 * 60 * 1000;
173
+ const SWEEP_MIN_MS = 10 * 60 * 1000;
174
+
175
+ /** Removes staging directories another process left behind (it crashed, or was killed mid-extraction). @param {string} parent */
176
+ function sweepStaging(parent) {
177
+ let names;
178
+ try { names = readdirSync(parent); } catch { return; }
179
+ for (const name of names) {
180
+ const match = STAGING.exec(name);
181
+ if (!match) continue;
182
+ const pid = Number(match[2]);
183
+ if (pid === process.pid) continue;
184
+ const age = Date.now() - Number(match[3]);
185
+ // Another pid namespace (a bind-mounted ALP_HOME) may hold a live extractor this one cannot see,
186
+ // so even a dead-looking pid's staging is kept for a few minutes; past an hour nothing is running.
187
+ if (age < SWEEP_MIN_MS) continue;
188
+ let alive = false;
189
+ try { process.kill(pid, 0); alive = true; } catch (error) { alive = /** @type {any} */ (error)?.code === 'EPERM'; }
190
+ if (alive && age < STALE_MS) continue;
191
+ try { rmSync(path.join(parent, name), { recursive: true, force: true }); } catch {}
192
+ }
193
+ }
194
+
195
+ /**
196
+ * The directory holding the executable's embedded assets (templates, the web app, the native
197
+ * terminal helper), extracted once per version to `<ALP_HOME or ~/.alp>/cache/<version>/` and
198
+ * checked against the build's sha256 manifest. Undefined when not packaged: callers then use the
199
+ * files beside their scripts, as before.
200
+ * @param {{ env?: NodeJS.ProcessEnv, info?: PackagedRegistration }} [options]
201
+ * @returns {string | undefined}
202
+ */
203
+ export function assetDir({ env = process.env, info = packagedInfo() } = {}) {
204
+ if (!info) return undefined;
205
+ const assets = info.assets ?? {};
206
+ const directory = assetCacheDir(info.version, env);
207
+ const digest = manifestDigest(assets);
208
+ // Checked once per process and directory; later calls (every template read) reuse the answer.
209
+ const key = `${directory}\0${digest}`;
210
+ if (verified.has(key) && existsSync(path.join(directory, MARKER))) return directory;
211
+ const result = extract(directory, digest, assets, info.version);
212
+ verified.add(key);
213
+ return result;
214
+ }
215
+
216
+ const verified = new Set();
217
+
218
+ /** @param {string} directory @param {string} digest @param {Record<string, PackagedAsset>} assets @param {string} version */
219
+ function extract(directory, digest, assets, version) {
220
+ const parent = path.dirname(directory);
221
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
222
+ assertParent(parent);
223
+ sweepStaging(parent);
224
+ if (existsSync(directory)) {
225
+ assertPrivate(directory);
226
+ if (extracted(directory, digest, assets)) return directory;
227
+ }
228
+ const staging = `${directory}.tmp-${process.pid}-${Date.now()}`;
229
+ mkdirSync(staging, { mode: 0o700 });
230
+ try {
231
+ for (const [name, asset] of Object.entries(assets)) {
232
+ assertAssetName(name);
233
+ const bytes = readFileSync(asset.path);
234
+ if (bytes.length !== asset.size || sha256(bytes) !== asset.sha256) throw new Error(`Packaged asset ${name} does not match its manifest`);
235
+ const target = path.join(staging, name);
236
+ mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
237
+ writeFileSync(target, bytes, { mode: 0o600 });
238
+ if (/(^|\/)terminal-owner(\.exe)?$/.test(name)) chmodSync(target, 0o700);
239
+ }
240
+ writeFileSync(path.join(staging, MARKER), JSON.stringify({ version, digest }), { mode: 0o600 });
241
+ // Another ALP process may have finished the same extraction first; its copy is equivalent.
242
+ if (existsSync(directory)) {
243
+ assertPrivate(directory);
244
+ if (extracted(directory, digest, assets)) { rmSync(staging, { recursive: true, force: true }); return directory; }
245
+ rmSync(directory, { recursive: true, force: true });
246
+ }
247
+ renameSync(staging, directory);
248
+ if (!extracted(directory, digest, assets)) throw new Error(`ALP asset cache ${directory} is incomplete after extraction`);
249
+ } catch (error) {
250
+ rmSync(staging, { recursive: true, force: true });
251
+ if (existsSync(directory) && extracted(directory, digest, assets)) return directory;
252
+ throw error;
253
+ }
254
+ return directory;
255
+ }
package/src/providers.js CHANGED
@@ -3,6 +3,7 @@ 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 { isPackaged, scriptCommand } from './packaged.js';
6
7
 
7
8
  /**
8
9
  * ACP providers (ALPD §46): agents that speak the Agent Client Protocol, such as Gemini
@@ -100,7 +101,8 @@ export function acpModel(model) {
100
101
  * native executable it calls, or the Node script, under this Node. A bare name with an .exe or
101
102
  * .com on PATH, any other command, and every command elsewhere are returned as they are.
102
103
  * @param {string} command @param {string[]} [args] @param {Record<string, string | undefined>} [env]
103
- * @returns {{ command: string, args: string[] }}
104
+ * In the ALP executable a Node script runs with the executable as its Bun runtime, via `env` to add.
105
+ * @returns {{ command: string, args: string[], env?: Record<string, string> }}
104
106
  */
105
107
  export function launchCommand(command, args = [], env = process.env) {
106
108
  if (process.platform !== 'win32' || /[\\/]/.test(command) || path.extname(command)) return { command, args };
@@ -113,7 +115,7 @@ export function launchCommand(command, args = [], env = process.env) {
113
115
  // for a Node script. Anything else (a hand-written batch file) stays refused by spawn, as before.
114
116
  const text = readFileSync(shim, 'utf8');
115
117
  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] };
118
+ if (script) { const flags = script[1].split(/\s+/).filter(Boolean); const run = scriptCommand(path.join(directory, script[2]), args); return { command: run.command, args: isPackaged() ? run.args : [...flags, ...run.args], ...(run.env ? { env: run.env } : {}) }; }
117
119
  const native = /^\s*"%~?dp0%\\?([^"]+\.(?:exe|com))"\s+%\*/im.exec(text);
118
120
  if (native) return { command: path.join(directory, native[1]), args };
119
121
  break;
package/src/task-rows.js CHANGED
@@ -20,7 +20,7 @@ export async function taskRows(projectRoot) {
20
20
  }
21
21
  const rows = tasks.map(task => {
22
22
  const row = summarize(task, tasks);
23
- const approvals = task.status === 'closed' ? [] : task.gates.filter(gate => gate.kind === 'human' && !gate.resolved).map(gate => ({ gate: gate.id, note: gate.note ?? '' }));
23
+ const approvals = task.status === 'closed' ? [] : task.gates.filter(gate => gate.kind === 'human' && !gate.resolved).map(gate => ({ gate: gate.id, note: gate.note ?? '', ...(gate.options?.length ? { options: gate.options } : {}), ...(gate.rejected ? { rejected: { at: gate.rejected.at, ...(gate.rejected.reason ? { reason: gate.rejected.reason } : {}) } } : {}) }));
24
24
  const waits = task.status === 'closed' ? [] : gatesOf(task, tasks);
25
25
  return {
26
26
  id: task.id, title: task.title, type: task.type, priority: task.priority, status: task.status, rev: task.rev,
package/src/tasks.d.ts CHANGED
@@ -47,8 +47,15 @@ export type TaskGate = {
47
47
  ref?: string;
48
48
  at: string;
49
49
  by: string;
50
- resolved?: { at: string; by: string; note?: string };
50
+ /** A human gate's answers; choosing any of them approves it. */
51
+ options?: string[];
52
+ resolved?: { at: string; by: string; note?: string; choice?: string; channel?: GateChannel; notified?: string; overridden?: true };
53
+ /** A human gate ALP opened that a task file edit showed cleared or removed: reopened (t-ca1f). */
54
+ tampered?: { at?: string | null; by?: string | null; removed?: true };
55
+ /** The user's latest rejection; the gate stays open. */
56
+ rejected?: { at: string; by: string; reason?: string; channel?: GateChannel; notified?: string };
51
57
  };
58
+ export type GateChannel = 'paseo' | 'web' | 'cli';
52
59
 
53
60
  export type TaskInput = {
54
61
  title?: string;
@@ -93,7 +100,7 @@ export function createTask(projectRoot: string, input: TaskInput & { title: stri
93
100
  export function updateTask(projectRoot: string, id: string, input: TaskInput & { note?: string }, by: string, options?: WriteOptions): Promise<Task>;
94
101
  export function linkTask(projectRoot: string, id: string, change: { add?: TaskLinks; remove?: TaskLinks }, by: string, options?: WriteOptions): Promise<Task>;
95
102
  export function startTask(projectRoot: string, id: string, assignee: { agent: string; session?: string; assignment?: string; pid?: number; pidStartedAt?: number; epoch?: string }, by: string, options?: WriteOptions): Promise<Task>;
96
- export function closeTask(projectRoot: string, id: string, close: { reason?: CloseReason; summary?: string; unverified?: string }, by: string, options?: WriteOptions): Promise<Task>;
103
+ export function closeTask(projectRoot: string, id: string, close: { reason?: CloseReason; summary?: string; unverified?: string; agent?: boolean; channel?: GateChannel }, by: string, options?: WriteOptions): Promise<Task>;
97
104
  export function verificationFailed(task: Task): boolean;
98
105
  export function recordVerification(projectRoot: string, id: string, verification: { passed: boolean; where?: string; commands?: Array<{ step: string; command: string; exitCode: number; ms: number; output?: string; timedOut?: boolean }>; skipped?: string }, by: string): Promise<Task>;
99
106
  export function reopenTask(projectRoot: string, id: string, reopen: { note?: string }, by: string, options?: WriteOptions): Promise<Task>;
@@ -107,8 +114,15 @@ export function startRefusal(task: Task, tasks: Task[]): string | undefined;
107
114
  export function gateOpen(gate: TaskGate, now?: number): boolean;
108
115
  export function describeGate(gate: TaskGate): string;
109
116
  export function gatesOf(task: Task, tasks: Task[]): string[];
110
- export function addGate(projectRoot: string, id: string, gate: { kind: GateKind; note?: string; until?: string; ref?: string | number }, by: string): Promise<Task>;
111
- export function resolveGate(projectRoot: string, id: string, gateId: string, resolve: { by: string; note?: string; remove?: boolean; ifRev?: number }): Promise<Task>;
117
+ export const GATE_OPTIONS: number;
118
+ export const GATE_OPTION_CHARS: number;
119
+ export const GATE_CHANNELS: GateChannel[];
120
+ export function addGate(projectRoot: string, id: string, gate: { kind: GateKind; note?: string; until?: string; ref?: string | number; options?: string[] }, by: string): Promise<Task>;
121
+ export function resolveGate(projectRoot: string, id: string, gateId: string, resolve: { by: string; note?: string; remove?: boolean; ifRev?: number; choice?: string; channel?: GateChannel }): Promise<Task>;
122
+ export function rejectGate(projectRoot: string, id: string, gateId: string, reject: { by: string; reason?: string; ifRev?: number; channel?: GateChannel }): Promise<Task>;
123
+ export type GateDecision = { task: Task; gate: TaskGate; decision: 'approved' | 'rejected'; record: NonNullable<TaskGate['resolved'] | TaskGate['rejected']> };
124
+ export function gateDecisions(tasks: Task[]): GateDecision[];
125
+ export function markGateNotified(projectRoot: string, id: string, gateId: string, decision: 'approved' | 'rejected'): Promise<boolean>;
112
126
  export function checkGates(projectRoot: string, gh: (args: string[], options: { cwd: string }) => Promise<string>): Promise<{ cleared: Array<{ task: string; gate: string; detail: string }>; pending: Array<{ task: string; gate: string; detail: string }>; errors: Array<{ task: string; gate: string; error: string }> }>;
113
127
  export function compactTasks(projectRoot: string, options: { days?: number; dryRun?: boolean }, by: string): Promise<Array<{ id: string; before: number; after: number }>>;
114
128
  export type TaskBatch = {
@@ -126,3 +140,7 @@ export type EpicReport = { id: string; title: string; status: TaskStatus; tasks:
126
140
  export function epicReport(id: string, tasks: Task[]): EpicReport;
127
141
  export function landedParents(tasks: Task[]): Array<{ task: Task; children: number }>;
128
142
  export function withTaskLock<T>(projectRoot: string, work: () => Promise<T>): Promise<T>;
143
+
144
+ /** Set in every agent process ALP starts (t-ca1f). */
145
+ export const AGENT_MARKER: 'ALP_AGENT_SESSION';
146
+ export function isAgentProcess(env?: NodeJS.ProcessEnv): boolean;