@anhlp/alp-core 0.0.1-beta.4 → 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.
@@ -0,0 +1,198 @@
1
+ // packages/core/src/packaged.js
2
+ import { createHash } from "node:crypto";
3
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ var KEY = Symbol.for("alp.packaged");
7
+ var ROLE_ARGS = Object.freeze({
8
+ daemon: Object.freeze(["daemon", "run"]),
9
+ web: Object.freeze(["web", "serve"]),
10
+ "bridge-acp": Object.freeze(["bridge", "acp"]),
11
+ "bridge-antigravity": Object.freeze(["bridge", "antigravity"])
12
+ });
13
+ function registerPackaged(registration) {
14
+ if (!registration || typeof registration.version !== "string") throw new TypeError("registerPackaged needs a version");
15
+ Object.defineProperty(globalThis, KEY, { value: Object.freeze({ ...registration, assetDir: () => assetDir() }), configurable: true, enumerable: false, writable: false });
16
+ }
17
+ function packagedInfo() {
18
+ return (
19
+ /** @type {any} */
20
+ globalThis[KEY]
21
+ );
22
+ }
23
+ function isPackaged() {
24
+ return packagedInfo() !== void 0;
25
+ }
26
+ var EXECUTABLE_MARKER = "alp-standalone-executable:v1:2b6f0c1e";
27
+ var isExecutableName = (file) => /^alp(\.exe)?$/i.test(file.split(/[\\/]/).pop() ?? "");
28
+ var isSelf = (file) => isPackaged() && typeof file === "string" && samePath(file, process.execPath);
29
+ var canonical = (file) => {
30
+ let resolved = path.resolve(file);
31
+ try {
32
+ resolved = realpathSync.native(resolved);
33
+ } catch {
34
+ }
35
+ return process.platform === "darwin" || process.platform === "win32" ? resolved.toLowerCase() : resolved;
36
+ };
37
+ var samePath = (a, b) => canonical(a) === canonical(b);
38
+ var isScript = (file) => /\.[cm]?js$/i.test(file);
39
+ function roleArgs(role) {
40
+ const args = ROLE_ARGS[role];
41
+ if (!args) throw new TypeError(`Unknown ALP role: ${role}`);
42
+ return [...args];
43
+ }
44
+ function selfCommand(role, { script, args = [] }) {
45
+ if (isPackaged()) return { command: process.execPath, args: [...roleArgs(role), ...args] };
46
+ return { command: process.execPath, args: [script, ...args] };
47
+ }
48
+ function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
49
+ if (scriptOnly || isScript(entry) || !(isExecutableName(entry) || isSelf(entry))) {
50
+ if (isPackaged() && execPath === process.execPath) return { command: "node", args: [entry, ...args] };
51
+ return { command: execPath, args: [entry, ...args] };
52
+ }
53
+ return { command: entry, args: [...roleArgs(role), ...args] };
54
+ }
55
+ function scriptCommand(script, args = []) {
56
+ if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: "1" } };
57
+ return { command: process.execPath, args: [script, ...args] };
58
+ }
59
+ function executablePath() {
60
+ return isPackaged() ? process.execPath : void 0;
61
+ }
62
+ function selfEntry(script) {
63
+ return isPackaged() ? process.execPath : script;
64
+ }
65
+ var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
66
+ var MARKER = ".alp-assets.json";
67
+ function assetCacheDir(version, env = process.env) {
68
+ if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) throw new TypeError(`Invalid ALP version for the asset cache: ${JSON.stringify(version)}`);
69
+ const home = env.ALP_HOME ? path.resolve(env.ALP_HOME) : path.join(os.homedir(), ".alp");
70
+ return path.join(home, "cache", version);
71
+ }
72
+ var manifestDigest = (assets) => sha256(Buffer.from(JSON.stringify(Object.keys(assets).sort().map((name) => [name, assets[name].sha256, assets[name].size]))));
73
+ function assertAssetName(name) {
74
+ if (!name || path.isAbsolute(name) || name.split(/[\\/]/).some((part) => part === ".." || part === "" || part === ".") || name === MARKER) throw new Error(`Invalid packaged asset name: ${JSON.stringify(name)}`);
75
+ }
76
+ function assertPrivate(directory) {
77
+ const info = lstatSync(directory);
78
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache is not a directory: ${directory}`);
79
+ if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 63) !== 0)) throw new Error(`ALP asset cache must be private to the current user (0700): ${directory}`);
80
+ }
81
+ function assertParent(directory) {
82
+ const info = lstatSync(directory);
83
+ if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache parent is not a directory: ${directory}`);
84
+ if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 18) !== 0)) throw new Error(`ALP asset cache parent must belong to the current user and not be group- or world-writable: ${directory}`);
85
+ }
86
+ function extracted(directory, digest, assets) {
87
+ try {
88
+ if (JSON.parse(readFileSync(path.join(directory, MARKER), "utf8")).digest !== digest) return false;
89
+ return Object.entries(assets).every(([name, asset]) => {
90
+ const file = path.join(directory, name);
91
+ const info = lstatSync(file);
92
+ return info.isFile() && info.size === asset.size && sha256(readFileSync(file)) === asset.sha256;
93
+ });
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+ var STAGING = /^(.+)\.tmp-(\d+)-(\d+)$/;
99
+ var STALE_MS = 60 * 60 * 1e3;
100
+ var SWEEP_MIN_MS = 10 * 60 * 1e3;
101
+ function sweepStaging(parent) {
102
+ let names;
103
+ try {
104
+ names = readdirSync(parent);
105
+ } catch {
106
+ return;
107
+ }
108
+ for (const name of names) {
109
+ const match = STAGING.exec(name);
110
+ if (!match) continue;
111
+ const pid = Number(match[2]);
112
+ if (pid === process.pid) continue;
113
+ const age = Date.now() - Number(match[3]);
114
+ if (age < SWEEP_MIN_MS) continue;
115
+ let alive = false;
116
+ try {
117
+ process.kill(pid, 0);
118
+ alive = true;
119
+ } catch (error) {
120
+ alive = /** @type {any} */
121
+ error?.code === "EPERM";
122
+ }
123
+ if (alive && age < STALE_MS) continue;
124
+ try {
125
+ rmSync(path.join(parent, name), { recursive: true, force: true });
126
+ } catch {
127
+ }
128
+ }
129
+ }
130
+ function assetDir({ env = process.env, info = packagedInfo() } = {}) {
131
+ if (!info) return void 0;
132
+ const assets = info.assets ?? {};
133
+ const directory = assetCacheDir(info.version, env);
134
+ const digest = manifestDigest(assets);
135
+ const key = `${directory}\0${digest}`;
136
+ if (verified.has(key) && existsSync(path.join(directory, MARKER))) return directory;
137
+ const result = extract(directory, digest, assets, info.version);
138
+ verified.add(key);
139
+ return result;
140
+ }
141
+ var verified = /* @__PURE__ */ new Set();
142
+ function extract(directory, digest, assets, version) {
143
+ const parent = path.dirname(directory);
144
+ mkdirSync(parent, { recursive: true, mode: 448 });
145
+ assertParent(parent);
146
+ sweepStaging(parent);
147
+ if (existsSync(directory)) {
148
+ assertPrivate(directory);
149
+ if (extracted(directory, digest, assets)) return directory;
150
+ }
151
+ const staging = `${directory}.tmp-${process.pid}-${Date.now()}`;
152
+ mkdirSync(staging, { mode: 448 });
153
+ try {
154
+ for (const [name, asset] of Object.entries(assets)) {
155
+ assertAssetName(name);
156
+ const bytes = readFileSync(asset.path);
157
+ if (bytes.length !== asset.size || sha256(bytes) !== asset.sha256) throw new Error(`Packaged asset ${name} does not match its manifest`);
158
+ const target = path.join(staging, name);
159
+ mkdirSync(path.dirname(target), { recursive: true, mode: 448 });
160
+ writeFileSync(target, bytes, { mode: 384 });
161
+ if (/(^|\/)terminal-owner(\.exe)?$/.test(name)) chmodSync(target, 448);
162
+ }
163
+ writeFileSync(path.join(staging, MARKER), JSON.stringify({ version, digest }), { mode: 384 });
164
+ if (existsSync(directory)) {
165
+ assertPrivate(directory);
166
+ if (extracted(directory, digest, assets)) {
167
+ rmSync(staging, { recursive: true, force: true });
168
+ return directory;
169
+ }
170
+ rmSync(directory, { recursive: true, force: true });
171
+ }
172
+ renameSync(staging, directory);
173
+ if (!extracted(directory, digest, assets)) throw new Error(`ALP asset cache ${directory} is incomplete after extraction`);
174
+ } catch (error) {
175
+ rmSync(staging, { recursive: true, force: true });
176
+ if (existsSync(directory) && extracted(directory, digest, assets)) return directory;
177
+ throw error;
178
+ }
179
+ return directory;
180
+ }
181
+ export {
182
+ EXECUTABLE_MARKER,
183
+ ROLE_ARGS,
184
+ assetCacheDir,
185
+ assetDir,
186
+ entryCommand,
187
+ executablePath,
188
+ isExecutableName,
189
+ isPackaged,
190
+ isScript,
191
+ isSelf,
192
+ packagedInfo,
193
+ registerPackaged,
194
+ samePath,
195
+ scriptCommand,
196
+ selfCommand,
197
+ selfEntry
198
+ };
@@ -63,11 +63,13 @@ export function acpModel(model: any): {
63
63
  * native executable it calls, or the Node script, under this Node. A bare name with an .exe or
64
64
  * .com on PATH, any other command, and every command elsewhere are returned as they are.
65
65
  * @param {string} command @param {string[]} [args] @param {Record<string, string | undefined>} [env]
66
- * @returns {{ command: string, args: string[] }}
66
+ * In the ALP executable a Node script runs with the executable as its Bun runtime, via `env` to add.
67
+ * @returns {{ command: string, args: string[], env?: Record<string, string> }}
67
68
  */
68
69
  export function launchCommand(command: string, args?: string[], env?: Record<string, string | undefined>): {
69
70
  command: string;
70
71
  args: string[];
72
+ env?: Record<string, string>;
71
73
  };
72
74
  /**
73
75
  * ACP providers (ALPD §46): agents that speak the Agent Client Protocol, such as Gemini
package/dist/providers.js CHANGED
@@ -4,6 +4,7 @@ import { readdir, readFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { AlpError } from "./errors.js";
6
6
  import { settingsKeys, unknownMessage } from "./validation.js";
7
+ import { isPackaged, scriptCommand } from "./packaged.js";
7
8
  var PROVIDER_SETTINGS = ["$schema", "kind", "label", "description", "command", "args", "env", "models", "additionalModels", "enabled", "params", "readOnlyMode"];
8
9
  var BUILTIN_RUNTIMES = ["codex", "claude", "acp", "antigravity"];
9
10
  var RESERVED_PROVIDERS = [...BUILTIN_RUNTIMES, "alp"];
@@ -82,7 +83,11 @@ function launchCommand(command, args = [], env = process.env) {
82
83
  if (!existsSync(shim)) continue;
83
84
  const text = readFileSync(shim, "utf8");
84
85
  const script = /"%_prog%"((?:\s+[^\s"]+)*)\s+"%~?dp0%\\?([^"]+)"\s+%\*/i.exec(text);
85
- if (script) return { command: process.execPath, args: [...script[1].split(/\s+/).filter(Boolean), path.join(directory, script[2]), ...args] };
86
+ if (script) {
87
+ const flags = script[1].split(/\s+/).filter(Boolean);
88
+ const run = scriptCommand(path.join(directory, script[2]), args);
89
+ return { command: run.command, args: isPackaged() ? run.args : [...flags, ...run.args], ...run.env ? { env: run.env } : {} };
90
+ }
86
91
  const native = /^\s*"%~?dp0%\\?([^"]+\.(?:exe|com))"\s+%\*/im.exec(text);
87
92
  if (native) return { command: path.join(directory, native[1]), args };
88
93
  break;
@@ -25,6 +25,11 @@ export function taskRows(projectRoot: string): Promise<{
25
25
  summary: string;
26
26
  } | undefined;
27
27
  approvals?: {
28
+ rejected?: {
29
+ reason?: string | undefined;
30
+ at: string;
31
+ } | undefined;
32
+ options?: string[] | undefined;
28
33
  gate: string;
29
34
  note: string;
30
35
  }[] | undefined;
package/dist/task-rows.js CHANGED
@@ -13,7 +13,7 @@ async function taskRows(projectRoot) {
13
13
  }
14
14
  const rows = tasks.map((task) => {
15
15
  const row = summarize(task, tasks);
16
- const approvals = task.status === "closed" ? [] : task.gates.filter((gate) => gate.kind === "human" && !gate.resolved).map((gate) => ({ gate: gate.id, note: gate.note ?? "" }));
16
+ 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 } : {} } } : {} }));
17
17
  const waits = task.status === "closed" ? [] : gatesOf(task, tasks);
18
18
  return {
19
19
  id: task.id,
package/dist/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;
package/dist/tasks.js CHANGED
@@ -6,6 +6,9 @@ import path from "node:path";
6
6
  import { AlpError } from "./errors.js";
7
7
  import { assertNoSymlinks } from "./safe-path.js";
8
8
  import { describeVerification } from "./verify.js";
9
+ import { applyLedger, ledgerAdopt, ledgerPrune, ledgerResolve, readLedger } from "./gate-ledger.js";
10
+ var AGENT_MARKER = "ALP_AGENT_SESSION";
11
+ var isAgentProcess = (env = process.env) => typeof env[AGENT_MARKER] === "string" && env[AGENT_MARKER] !== "";
9
12
  var TASKS_DIR = ".alp/tasks";
10
13
  var TASK_TYPES = ["task", "bug", "feature", "chore", "epic"];
11
14
  var TASK_STATUSES = ["open", "in_progress", "review", "closed"];
@@ -66,6 +69,7 @@ async function loadTasks(projectRoot) {
66
69
  errors.push({ file: path.relative(path.resolve(projectRoot), file), error: error.message });
67
70
  }
68
71
  }
72
+ applyLedger(tasks, await readLedger(projectRoot));
69
73
  return { tasks, errors };
70
74
  }
71
75
  function normalize(task) {
@@ -265,6 +269,8 @@ async function save(projectRoot, task) {
265
269
  const temporary = `${file}.${randomUUID().slice(0, 8)}.tmp`;
266
270
  await writeFile(temporary, JSON.stringify(task, null, 2) + "\n");
267
271
  await moveFile(temporary, file);
272
+ await ledgerAdopt(projectRoot, task).catch(() => {
273
+ });
268
274
  return task;
269
275
  }
270
276
  function newId(tasks, title, parent) {
@@ -419,8 +425,8 @@ function startTask(projectRoot, id, assignee, by, options) {
419
425
  addLog(task, by, rework ? "reworked" : "started", { to: assignee.agent, ...assignee.assignment ? { assignment: assignee.assignment } : {} });
420
426
  }, options);
421
427
  }
422
- function closeTask(projectRoot, id, { reason = "done", summary, unverified } = {}, by, options) {
423
- return mutate(projectRoot, id, (task, tasks) => {
428
+ function closeTask(projectRoot, id, { reason = "done", summary, unverified, agent = false, channel } = {}, by, options) {
429
+ return mutate(projectRoot, id, async (task, tasks) => {
424
430
  if (!CLOSE_REASONS.includes(reason)) fail("INVALID_TASK", `reason must be one of ${CLOSE_REASONS.join(", ")}`);
425
431
  const closing = checkText(summary, "summary", NOTE_CHARS);
426
432
  let excuse = checkText(unverified, "unverified", NOTE_CHARS);
@@ -431,6 +437,15 @@ function closeTask(projectRoot, id, { reason = "done", summary, unverified } = {
431
437
  if (by !== "user") fail("TASK_UNVERIFIED", `${id}'s last ${describeVerification(task.verified)}; fix it and verify again, or close it with unverified saying why it is done anyway`);
432
438
  excuse = `the user closed it after ${describeVerification(task.verified)}`;
433
439
  }
440
+ const held = (task.gates ?? []).filter((gate) => gate.kind === "human" && !gate.resolved);
441
+ if (held.length || task.step?.human) {
442
+ if (agent || by !== "user") fail("GATE_USER_ONLY", `Only the user closes ${id}: ${held.length ? `it waits on ${held.map(describeGate).join("; ")}` : "it is a step for the user"}. Ask the user to decide it`);
443
+ checkChannel(channel);
444
+ for (const gate of held) await ledgerResolve(projectRoot, task.id, gate, { by, channel });
445
+ const note = `overridden: the user closed ${id} (${reason})`;
446
+ task.gates = task.gates.map((gate) => held.includes(gate) ? { ...gate, resolved: { at: now(), by, note, overridden: true, ...channel ? { channel } : {} } } : gate);
447
+ for (const gate of held) addLog(task, by, "gate overridden", { gate: describeGate(gate), ...channel ? { channel } : {} });
448
+ }
434
449
  task.status = "closed";
435
450
  task.closed = { at: now(), by, reason, ...closing ? { summary: closing } : {}, ...excuse ? { unverified: excuse } : {} };
436
451
  task.assignee = null;
@@ -604,7 +619,7 @@ function taskDigest(tasks, errors = []) {
604
619
  }
605
620
  var DURATION = /^\+(\d+)([mhd])$/;
606
621
  var GH_REF = /^(?:([\w.-]+\/[\w.-]+)#)?(\d+)$/;
607
- function addGate(projectRoot, id, { kind, note, until, ref } = {}, by) {
622
+ function addGate(projectRoot, id, { kind, note, until, ref, options } = {}, by) {
608
623
  return mutate(projectRoot, id, (task) => {
609
624
  if (!GATE_KINDS.includes(kind)) fail("INVALID_TASK", `kind must be one of ${GATE_KINDS.join(", ")}`);
610
625
  if (task.status === "closed") fail("INVALID_TASK", `${id} is closed`);
@@ -612,6 +627,11 @@ function addGate(projectRoot, id, { kind, note, until, ref } = {}, by) {
612
627
  const gate = { id: `g${Math.max(0, ...(task.gates ?? []).map((entry) => Number(entry.id.slice(1)) || 0)) + 1}`, kind };
613
628
  if (kind === "human") gate.note = checkText(note, "note", NOTE_CHARS, { required: true });
614
629
  else if (note !== void 0) gate.note = checkText(note, "note", NOTE_CHARS);
630
+ if (options !== void 0) {
631
+ if (kind !== "human") fail("INVALID_TASK", "Only a human gate has options");
632
+ const choices = gateOptions(options);
633
+ if (choices.length) gate.options = choices;
634
+ }
615
635
  if (kind === "timer") {
616
636
  const relative = typeof until === "string" ? DURATION.exec(until.trim()) : null;
617
637
  const time = relative ? Date.now() + Number(relative[1]) * { m: 6e4, h: 36e5, d: 864e5 }[relative[2]] : Date.parse(until);
@@ -630,20 +650,44 @@ function addGate(projectRoot, id, { kind, note, until, ref } = {}, by) {
630
650
  addLog(task, by, "gated", { gate: describeGate(gate) });
631
651
  });
632
652
  }
633
- function resolveGate(projectRoot, id, gateId, { by, note, remove = false, ifRev } = {}) {
634
- return mutate(projectRoot, id, (task) => {
653
+ var GATE_OPTIONS = 10;
654
+ var GATE_OPTION_CHARS = 200;
655
+ var GATE_CHANNELS = ["paseo", "web", "cli"];
656
+ function gateOptions(value) {
657
+ if (!Array.isArray(value) || value.length > GATE_OPTIONS || !value.every((item) => typeof item === "string" && !!item.trim() && item.trim().length <= GATE_OPTION_CHARS)) {
658
+ fail("INVALID_TASK", `options must list at most ${GATE_OPTIONS} nonempty answers of at most ${GATE_OPTION_CHARS} characters`);
659
+ }
660
+ return [...new Set(value.map((item) => item.trim()))];
661
+ }
662
+ var checkChannel = (channel) => {
663
+ if (channel !== void 0 && !GATE_CHANNELS.includes(channel)) fail("INVALID_TASK", `channel must be one of ${GATE_CHANNELS.join(", ")}`);
664
+ return channel;
665
+ };
666
+ function resolveGate(projectRoot, id, gateId, { by, note, remove = false, ifRev, choice, channel } = {}) {
667
+ return mutate(projectRoot, id, async (task) => {
635
668
  const gate = (task.gates ?? []).find((entry) => entry.id === gateId) ?? fail("INVALID_TASK", `${id} has no gate ${gateId}`);
669
+ const record = () => gate.kind === "human" ? ledgerResolve(projectRoot, task.id, gate, { by, channel, removed: remove }) : void 0;
636
670
  if (remove) {
671
+ await record();
637
672
  task.gates = task.gates.filter((entry) => entry !== gate);
638
673
  addLog(task, by, "ungated", { gate: describeGate(gate) });
639
674
  return;
640
675
  }
641
676
  if (!gateOpen(gate)) fail("INVALID_TASK", `Gate ${gateId} of ${id} is already clear`);
642
677
  const text = checkText(note, "note", NOTE_CHARS);
643
- task.gates = task.gates.map((entry) => entry === gate ? { ...entry, resolved: { at: now(), by, ...text ? { note: text } : {} } } : entry);
644
- addLog(task, by, "gate cleared", { gate: describeGate(gate), ...text ? { note: text } : {} });
678
+ checkChannel(channel);
679
+ if (choice !== void 0) {
680
+ if (gate.kind !== "human") fail("INVALID_TASK", "Only a human gate takes a choice");
681
+ if (typeof choice !== "string" || !choice.trim() || (gate.options ? !gate.options.includes(choice.trim()) : choice.trim().length > GATE_OPTION_CHARS)) {
682
+ fail("INVALID_TASK", gate.options ? `choice must be one of: ${gate.options.join(", ")}` : `choice must be nonempty text of at most ${GATE_OPTION_CHARS} characters`);
683
+ }
684
+ }
685
+ const picked = choice?.trim();
686
+ await record();
687
+ task.gates = task.gates.map((entry) => entry === gate ? { ...entry, resolved: { at: now(), by, ...text ? { note: text } : {}, ...picked ? { choice: picked } : {}, ...channel ? { channel } : {} } } : entry);
688
+ addLog(task, by, "gate cleared", { gate: describeGate(gate), ...picked ? { choice: picked } : {}, ...channel ? { channel } : {}, ...text ? { note: text } : {} });
645
689
  if (task.step?.human && task.status !== "closed" && !task.gates.some((entry) => gateOpen(entry))) {
646
- const summary = `Approved by ${by}${text ? `: ${text}` : ""}`;
690
+ const summary = `Approved by ${by}${picked ? ` (${picked})` : ""}${text ? `: ${text}` : ""}`;
647
691
  task.status = "closed";
648
692
  task.assignee = null;
649
693
  task.closed = { at: now(), by, reason: "done", summary };
@@ -651,6 +695,39 @@ function resolveGate(projectRoot, id, gateId, { by, note, remove = false, ifRev
651
695
  }
652
696
  }, { ifRev });
653
697
  }
698
+ function rejectGate(projectRoot, id, gateId, { by, reason, ifRev, channel } = {}) {
699
+ return mutate(projectRoot, id, (task) => {
700
+ const gate = (task.gates ?? []).find((entry) => entry.id === gateId) ?? fail("INVALID_TASK", `${id} has no gate ${gateId}`);
701
+ if (gate.kind !== "human") fail("INVALID_TASK", "Only a human gate is rejected; remove another gate instead");
702
+ if (!gateOpen(gate)) fail("INVALID_TASK", `Gate ${gateId} of ${id} is already clear`);
703
+ const text = checkText(reason, "reason", NOTE_CHARS);
704
+ checkChannel(channel);
705
+ task.gates = task.gates.map((entry) => entry === gate ? { ...entry, rejected: { at: now(), by, ...text ? { reason: text } : {}, ...channel ? { channel } : {} } } : entry);
706
+ addLog(task, by, "gate rejected", { gate: describeGate(gate), ...channel ? { channel } : {}, ...text ? { note: text } : {} });
707
+ }, { ifRev });
708
+ }
709
+ function gateDecisions(tasks) {
710
+ const found = [];
711
+ for (const task of tasks) for (const gate of task.gates ?? []) {
712
+ if (gate.kind !== "human") continue;
713
+ if (gate.resolved?.overridden) continue;
714
+ if (gate.resolved?.channel && !gate.resolved.notified) found.push({ task, gate, decision: "approved", record: gate.resolved });
715
+ else if (!gate.resolved && gate.rejected?.channel && !gate.rejected.notified) found.push({ task, gate, decision: "rejected", record: gate.rejected });
716
+ }
717
+ return found;
718
+ }
719
+ function markGateNotified(projectRoot, id, gateId, decision) {
720
+ return locked(projectRoot, async () => {
721
+ const { tasks } = await loadTasks(projectRoot);
722
+ const task = tasks.find((entry) => entry.id === id);
723
+ const gate = task?.gates?.find((entry) => entry.id === gateId);
724
+ const record = decision === "approved" ? gate?.resolved : gate?.rejected;
725
+ if (!task || !record?.channel || record.notified) return false;
726
+ record.notified = now();
727
+ await save(projectRoot, task);
728
+ return true;
729
+ });
730
+ }
654
731
  async function checkGates(projectRoot, gh) {
655
732
  const { tasks } = await loadTasks(projectRoot);
656
733
  const cleared = [];
@@ -695,7 +772,8 @@ async function compactTasks(projectRoot, { days = 30, dryRun = false } = {}, by)
695
772
  ...task,
696
773
  description: clipText(task.description, COMPACT_TEXT),
697
774
  handoff: task.handoff ? { outcome: task.handoff.outcome, summary: clipText(String(task.handoff.summary ?? ""), COMPACT_TEXT), agent: task.handoff.agent, at: task.handoff.at } : null,
698
- gates: task.gates.map(({ id, kind, resolved }) => ({ id, kind, ...resolved ? { resolved: { at: resolved.at, by: resolved.by } } : {} })),
775
+ // `at` stays: it names the gate in the gate ledger (t-ca1f); an open human gate keeps its note too.
776
+ gates: task.gates.map(({ id, kind, at, note, resolved }) => ({ id, kind, ...at ? { at } : {}, ...kind === "human" && !resolved && note ? { note } : {}, ...resolved ? { resolved: { at: resolved.at, by: resolved.by } } : {} })),
699
777
  log: [created, closed].filter(Boolean),
700
778
  rev: task.rev + 1,
701
779
  updatedAt: now()
@@ -706,6 +784,8 @@ async function compactTasks(projectRoot, { days = 30, dryRun = false } = {}, by)
706
784
  compacted.push({ id: task.id, before, after });
707
785
  if (!dryRun) await save(projectRoot, next);
708
786
  }
787
+ if (!dryRun) await ledgerPrune(projectRoot).catch(() => {
788
+ });
709
789
  return compacted;
710
790
  });
711
791
  }
@@ -785,9 +865,13 @@ function batch(projectRoot, work, { dryRun = false } = {}) {
785
865
  });
786
866
  }
787
867
  export {
868
+ AGENT_MARKER,
788
869
  CLOSE_REASONS,
789
870
  DESCRIPTION_CHARS,
871
+ GATE_CHANNELS,
790
872
  GATE_KINDS,
873
+ GATE_OPTIONS,
874
+ GATE_OPTION_CHARS,
791
875
  MAX_GATES,
792
876
  MAX_LABELS,
793
877
  MAX_LINKS,
@@ -807,17 +891,21 @@ export {
807
891
  createTask,
808
892
  describeGate,
809
893
  epicReport,
894
+ gateDecisions,
810
895
  gateOpen,
811
896
  gatesOf,
812
897
  getTask,
898
+ isAgentProcess,
813
899
  isTaskId,
814
900
  landedParents,
815
901
  linkTask,
816
902
  listTasks,
817
903
  loadTasks,
904
+ markGateNotified,
818
905
  orphanedEntry,
819
906
  readyTasks,
820
907
  recordVerification,
908
+ rejectGate,
821
909
  releaseOrphans,
822
910
  releaseTask,
823
911
  reopenTask,
@@ -1,2 +1,2 @@
1
- /** Source packages carry templates beside src; legacy bundles live one directory deeper. */
2
- export function shippedTemplateRoot(): URL;
1
+ /** Source packages carry templates beside src; legacy bundles live one directory deeper; the ALP executable extracts its embedded copy. */
2
+ export function shippedTemplateRoot(): import("url").URL;
@@ -1,6 +1,11 @@
1
1
  // packages/core/src/template-path.js
2
2
  import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { assetDir } from "./packaged.js";
3
6
  function shippedTemplateRoot() {
7
+ const assets = assetDir();
8
+ if (assets) return pathToFileURL(path.join(assets, "templates") + path.sep);
4
9
  const packaged = new URL("../templates/", import.meta.url);
5
10
  const candidates = [packaged, new URL("../../templates/", import.meta.url), new URL("../../../templates/", import.meta.url), new URL("../../../../templates/", import.meta.url), new URL("../../../../../templates/", import.meta.url)];
6
11
  return candidates.find((candidate) => existsSync(candidate)) ?? packaged;
package/dist/types.d.ts CHANGED
@@ -17,6 +17,7 @@ export interface RawSettings {
17
17
  workflow?: { mode?: 'pho' | 'cafe' | 'smart' | 'supervised'; maxPeers?: number; supervisor?: boolean };
18
18
  delegation?: Record<string, string[]>;
19
19
  runtime?: { provider?: string; model?: string; reasoning?: string };
20
+ compact?: { auto?: boolean; threshold?: number };
20
21
  }
21
22
  export interface RawMcpServer {
22
23
  command?: string;
@@ -11,8 +11,8 @@ function requireValue(condition, code, source, message) {
11
11
  if (!condition) throw new AlpError(code, `${source}: ${message}`);
12
12
  }
13
13
  var EFFORTS = ["none", "off", "low", "medium", "high", "xhigh", "max", "ultra", "ultracode"];
14
- var PROJECT_SETTINGS = ["$schema", "defaultAgent", "workflow", "runtime", "permissions", "verify", "delegation", "team", "profile", "templateDefaults"];
15
- var USER_SETTINGS = ["$schema", "language", "permissions", "limits", "recovery", "web"];
14
+ var PROJECT_SETTINGS = ["$schema", "defaultAgent", "workflow", "runtime", "permissions", "verify", "delegation", "team", "profile", "templateDefaults", "compact", "curate"];
15
+ var USER_SETTINGS = ["$schema", "language", "permissions", "limits", "recovery", "web", "curate"];
16
16
  var RETIRED_SETTINGS = { project: {}, user: {} };
17
17
  function distance(a, b) {
18
18
  const row = Array.from({ length: b.length + 1 }, (_, index) => index);
@@ -45,11 +45,18 @@ var unknownMessage = (unknown, known) => `unknown setting '${unknown.key}'${unkn
45
45
  function settingsWarnings(settings, scope) {
46
46
  return settingsKeys(settings, scope === "user" ? USER_SETTINGS : PROJECT_SETTINGS, RETIRED_SETTINGS[scope]).retired.map(({ key, instead }) => `setting '${key}' is no longer read; ${instead}`);
47
47
  }
48
+ function checkCurate(settings, check) {
49
+ if (settings.curate === void 0) return;
50
+ check(object(settings.curate), "curate must be an object");
51
+ check(Object.keys(settings.curate).every((key) => key === "monthly"), "unsupported curate field; use monthly");
52
+ if (settings.curate.monthly !== void 0) check(typeof settings.curate.monthly === "boolean", "curate.monthly must be true or false");
53
+ }
48
54
  function validateSettings(settings, source) {
49
55
  const check = (ok, message) => requireValue(ok, "INVALID_SETTINGS", source, message);
50
56
  check(object(settings), "expected an object");
51
57
  const { unknown } = settingsKeys(settings, PROJECT_SETTINGS, RETIRED_SETTINGS.project);
52
58
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], PROJECT_SETTINGS) : "");
59
+ checkCurate(settings, check);
53
60
  if (settings.defaultAgent !== void 0) check(nonempty(settings.defaultAgent), "defaultAgent must be a nonempty string");
54
61
  if (settings.workflow !== void 0) {
55
62
  check(object(settings.workflow), "workflow must be an object");
@@ -58,6 +65,12 @@ function validateSettings(settings, source) {
58
65
  if (settings.workflow.maxPeers !== void 0) check(Number.isSafeInteger(settings.workflow.maxPeers) && settings.workflow.maxPeers > 0, "workflow.maxPeers must be a positive integer");
59
66
  if (settings.workflow.supervisor !== void 0) check(typeof settings.workflow.supervisor === "boolean", "workflow.supervisor must be true or false");
60
67
  }
68
+ if (settings.compact !== void 0) {
69
+ check(object(settings.compact), "compact must be an object");
70
+ check(Object.keys(settings.compact).every((key) => ["auto", "threshold"].includes(key)), "compact takes auto and threshold");
71
+ if (settings.compact.auto !== void 0) check(typeof settings.compact.auto === "boolean", "compact.auto must be true or false");
72
+ if (settings.compact.threshold !== void 0) check(typeof settings.compact.threshold === "number" && settings.compact.threshold > 0 && settings.compact.threshold < 1, "compact.threshold must be a number between 0 and 1");
73
+ }
61
74
  if (settings.templateDefaults !== void 0) {
62
75
  check(object(settings.templateDefaults), "templateDefaults must map teams to profile fingerprints");
63
76
  for (const [team, agents] of Object.entries(settings.templateDefaults)) {
@@ -138,6 +151,7 @@ function validateUserSettings(settings, source) {
138
151
  check(object(settings), "expected an object");
139
152
  const { unknown } = settingsKeys(settings, USER_SETTINGS, RETIRED_SETTINGS.user);
140
153
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], USER_SETTINGS) : "");
154
+ checkCurate(settings, check);
141
155
  for (const key of ["limits", "recovery"]) {
142
156
  if (settings[key] === void 0) continue;
143
157
  check(object(settings[key]), `${key} must be an object`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-core",
3
- "version": "0.0.1-beta.4",
3
+ "version": "0.0.1-beta.5",
4
4
  "type": "module",
5
5
  "description": "ALP core module",
6
6
  "files": [
@@ -278,13 +278,29 @@
278
278
  },
279
279
  "types": "./dist/template-path.d.ts",
280
280
  "default": "./src/template-path.js"
281
+ },
282
+ "./bridges": {
283
+ "alp-source": {
284
+ "types": "./src/bridges.js",
285
+ "default": "./src/bridges.js"
286
+ },
287
+ "types": "./dist/bridges.d.ts",
288
+ "default": "./src/bridges.js"
289
+ },
290
+ "./packaged": {
291
+ "alp-source": {
292
+ "types": "./src/packaged.js",
293
+ "default": "./src/packaged.js"
294
+ },
295
+ "types": "./dist/packaged.d.ts",
296
+ "default": "./src/packaged.js"
281
297
  }
282
298
  },
283
299
  "engines": {
284
300
  "node": ">=22.12"
285
301
  },
286
302
  "dependencies": {
287
- "@anhlp/alp-protocol": "0.0.1-beta.4"
303
+ "@anhlp/alp-protocol": "0.0.1-beta.5"
288
304
  },
289
305
  "scripts": {
290
306
  "build": "node ../../scripts/build-workspace.mjs core",