@anhlp/alp-core 0.0.1-beta.4 → 0.0.1-beta.6

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/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,16 @@ 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 const GATE_REJECT_LABELS: string[];
121
+ export function addGate(projectRoot: string, id: string, gate: { kind: GateKind; note?: string; until?: string; ref?: string | number; options?: string[] }, by: string): Promise<Task>;
122
+ export function resolveGate(projectRoot: string, id: string, gateId: string, resolve: { by: string; note?: string; remove?: boolean; ifRev?: number; choice?: string; channel?: GateChannel }): Promise<Task>;
123
+ export function rejectGate(projectRoot: string, id: string, gateId: string, reject: { by: string; reason?: string; ifRev?: number; channel?: GateChannel }): Promise<Task>;
124
+ export type GateDecision = { task: Task; gate: TaskGate; decision: 'approved' | 'rejected'; record: NonNullable<TaskGate['resolved'] | TaskGate['rejected']> };
125
+ export function gateDecisions(tasks: Task[]): GateDecision[];
126
+ export function markGateNotified(projectRoot: string, id: string, gateId: string, decision: 'approved' | 'rejected', at?: string): Promise<boolean>;
112
127
  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
128
  export function compactTasks(projectRoot: string, options: { days?: number; dryRun?: boolean }, by: string): Promise<Array<{ id: string; before: number; after: number }>>;
114
129
  export type TaskBatch = {
@@ -126,3 +141,7 @@ export type EpicReport = { id: string; title: string; status: TaskStatus; tasks:
126
141
  export function epicReport(id: string, tasks: Task[]): EpicReport;
127
142
  export function landedParents(tasks: Task[]): Array<{ task: Task; children: number }>;
128
143
  export function withTaskLock<T>(projectRoot: string, work: () => Promise<T>): Promise<T>;
144
+
145
+ /** Set in every agent process ALP starts (t-ca1f). */
146
+ export const AGENT_MARKER: 'ALP_AGENT_SESSION';
147
+ export function isAgentProcess(env?: NodeJS.ProcessEnv): boolean;
package/src/tasks.js CHANGED
@@ -5,6 +5,15 @@ import path from 'node:path';
5
5
  import { AlpError } from './errors.js';
6
6
  import { assertNoSymlinks } from './safe-path.js';
7
7
  import { describeVerification } from './verify.js';
8
+ import { applyLedger, ledgerAdopt, ledgerPrune, ledgerResolve, readLedger } from './gate-ledger.js';
9
+
10
+ /**
11
+ * ALP sets this in the environment of every agent process it starts (t-ca1f). The CLI and
12
+ * alpd refuse to clear, reject or remove a human gate, or answer a question for the user, from a
13
+ * process that carries it. A same-user agent can unset it: it raises the bar, it is no boundary.
14
+ */
15
+ export const AGENT_MARKER = 'ALP_AGENT_SESSION';
16
+ export const isAgentProcess = (env = process.env) => typeof env[AGENT_MARKER] === 'string' && env[AGENT_MARKER] !== '';
8
17
 
9
18
  /**
10
19
  * The project's task graph (plans/reference/ALPD.md §20), modelled on beads:
@@ -73,6 +82,8 @@ export async function loadTasks(projectRoot) {
73
82
  errors.push({ file: path.relative(path.resolve(projectRoot), file), error: error.message });
74
83
  }
75
84
  }
85
+ // A ledgered human gate a task file edit cleared or removed opens again (t-ca1f).
86
+ applyLedger(tasks, await readLedger(projectRoot));
76
87
  return { tasks, errors };
77
88
  }
78
89
 
@@ -282,6 +293,10 @@ async function save(projectRoot, task) {
282
293
  const temporary = `${file}.${randomUUID().slice(0, 8)}.tmp`;
283
294
  await writeFile(temporary, JSON.stringify(task, null, 2) + '\n');
284
295
  await moveFile(temporary, file);
296
+ // Every writer saves here, under the task lock: an open human gate it wrote enters the gate
297
+ // ledger (t-ca1f). Detection is best-effort: an unwritable ledger leaves the gate unprotected
298
+ // rather than failing a write that already happened.
299
+ await ledgerAdopt(projectRoot, task).catch(() => {});
285
300
  return task;
286
301
  }
287
302
 
@@ -447,8 +462,8 @@ export function startTask(projectRoot, id, assignee, by, options) {
447
462
  * needs the last verification to have passed, or `unverified`: why it is done
448
463
  * anyway. The user may always close; the failed verification is noted.
449
464
  */
450
- export function closeTask(projectRoot, id, { reason = 'done', summary, unverified } = {}, by, options) {
451
- return mutate(projectRoot, id, (task, tasks) => {
465
+ export function closeTask(projectRoot, id, { reason = 'done', summary, unverified, agent = false, channel } = {}, by, options) {
466
+ return mutate(projectRoot, id, async (task, tasks) => {
452
467
  if (!CLOSE_REASONS.includes(reason)) fail('INVALID_TASK', `reason must be one of ${CLOSE_REASONS.join(', ')}`);
453
468
  const closing = checkText(summary, 'summary', NOTE_CHARS);
454
469
  let excuse = checkText(unverified, 'unverified', NOTE_CHARS);
@@ -459,6 +474,18 @@ export function closeTask(projectRoot, id, { reason = 'done', summary, unverifie
459
474
  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`);
460
475
  excuse = `the user closed it after ${describeVerification(task.verified)}`;
461
476
  }
477
+ // Only the user decides a human gate, and a formula's human step is the user's to do (t-f438):
478
+ // no agent closes such a task, for any reason. The user may; the open human gates are then
479
+ // recorded as overridden by the user, in the gate ledger first, so no edit is taken for tampering.
480
+ const held = (task.gates ?? []).filter(gate => gate.kind === 'human' && !gate.resolved);
481
+ if (held.length || task.step?.human) {
482
+ 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`);
483
+ checkChannel(channel);
484
+ for (const gate of held) await ledgerResolve(projectRoot, task.id, gate, { by, channel });
485
+ const note = `overridden: the user closed ${id} (${reason})`;
486
+ task.gates = task.gates.map(gate => held.includes(gate) ? { ...gate, resolved: { at: now(), by, note, overridden: true, ...(channel ? { channel } : {}) } } : gate);
487
+ for (const gate of held) addLog(task, by, 'gate overridden', { gate: describeGate(gate), ...(channel ? { channel } : {}) });
488
+ }
462
489
  task.status = 'closed';
463
490
  task.closed = { at: now(), by, reason, ...(closing ? { summary: closing } : {}), ...(excuse ? { unverified: excuse } : {}) };
464
491
  task.assignee = null;
@@ -681,7 +708,7 @@ const GH_REF = /^(?:([\w.-]+\/[\w.-]+)#)?(\d+)$/;
681
708
  * timer (until a time: ISO, or +30m, +2h, +3d), gh:pr (a pull request is merged)
682
709
  * or gh:run (a workflow run succeeds); refs are 123 or owner/repo#123.
683
710
  */
684
- export function addGate(projectRoot, id, { kind, note, until, ref } = {}, by) {
711
+ export function addGate(projectRoot, id, { kind, note, until, ref, options } = {}, by) {
685
712
  return mutate(projectRoot, id, task => {
686
713
  if (!GATE_KINDS.includes(kind)) fail('INVALID_TASK', `kind must be one of ${GATE_KINDS.join(', ')}`);
687
714
  if (task.status === 'closed') fail('INVALID_TASK', `${id} is closed`);
@@ -689,6 +716,11 @@ export function addGate(projectRoot, id, { kind, note, until, ref } = {}, by) {
689
716
  const gate = { id: `g${Math.max(0, ...(task.gates ?? []).map(entry => Number(entry.id.slice(1)) || 0)) + 1}`, kind };
690
717
  if (kind === 'human') gate.note = checkText(note, 'note', NOTE_CHARS, { required: true });
691
718
  else if (note !== undefined) gate.note = checkText(note, 'note', NOTE_CHARS);
719
+ if (options !== undefined) {
720
+ if (kind !== 'human') fail('INVALID_TASK', 'Only a human gate has options');
721
+ const choices = gateOptions(options);
722
+ if (choices.length) gate.options = choices;
723
+ }
692
724
  if (kind === 'timer') {
693
725
  const relative = typeof until === 'string' ? DURATION.exec(until.trim()) : null;
694
726
  const time = relative ? Date.now() + Number(relative[1]) * { m: 60_000, h: 3_600_000, d: 86_400_000 }[relative[2]] : Date.parse(until);
@@ -708,22 +740,64 @@ export function addGate(projectRoot, id, { kind, note, until, ref } = {}, by) {
708
740
  });
709
741
  }
710
742
 
711
- /** Clears a gate by hand, or removes it with `remove`. Only the user clears a human gate; the caller enforces who `by` is. */
712
- export function resolveGate(projectRoot, id, gateId, { by, note, remove = false, ifRev } = {}) {
713
- return mutate(projectRoot, id, task => {
743
+ export const GATE_OPTIONS = 10;
744
+ export const GATE_OPTION_CHARS = 200;
745
+ export const GATE_CHANNELS = ['paseo', 'web', 'cli'];
746
+ /**
747
+ * The Reject answer a gate card adds after its options, in every language ALP writes it
748
+ * (packages/runtime/src/language.ts, `reject`). An option that is one would hide that Reject
749
+ * and approve the gate instead, so no option may be one (t-595d).
750
+ */
751
+ export const GATE_REJECT_LABELS = ['Reject', 'Từ chối'];
752
+ const labelKey = text => text.normalize('NFC').trim().toLowerCase();
753
+ const REJECT_KEYS = new Set(GATE_REJECT_LABELS.map(labelKey));
754
+
755
+ /** The answers a human gate offers its approver: at most 10 distinct, nonempty, each at most 200 characters, none of them Reject. */
756
+ function gateOptions(value) {
757
+ if (!Array.isArray(value) || value.length > GATE_OPTIONS || !value.every(item => typeof item === 'string' && !!item.trim() && item.trim().length <= GATE_OPTION_CHARS)) {
758
+ fail('INVALID_TASK', `options must list at most ${GATE_OPTIONS} nonempty answers of at most ${GATE_OPTION_CHARS} characters`);
759
+ }
760
+ const reserved = value.find(item => REJECT_KEYS.has(labelKey(item)));
761
+ if (reserved !== undefined) fail('INVALID_TASK', `"${reserved.trim()}" is the Reject answer every gate card already offers; name the options for approving only`);
762
+ return [...new Set(value.map(item => item.trim()))];
763
+ }
764
+
765
+ const checkChannel = channel => {
766
+ if (channel !== undefined && !GATE_CHANNELS.includes(channel)) fail('INVALID_TASK', `channel must be one of ${GATE_CHANNELS.join(', ')}`);
767
+ return channel;
768
+ };
769
+
770
+ /**
771
+ * Clears a gate by hand, or removes it with `remove`. Only the user clears a human gate; the caller enforces who `by` is.
772
+ * `choice` records which of a human gate's options the user picked; `channel` (paseo, web or cli) where they decided.
773
+ */
774
+ export function resolveGate(projectRoot, id, gateId, { by, note, remove = false, ifRev, choice, channel } = {}) {
775
+ return mutate(projectRoot, id, async task => {
714
776
  const gate = (task.gates ?? []).find(entry => entry.id === gateId) ?? fail('INVALID_TASK', `${id} has no gate ${gateId}`);
777
+ // Recorded once every check passed and before the task file is written (t-ca1f).
778
+ const record = () => gate.kind === 'human' ? ledgerResolve(projectRoot, task.id, gate, { by, channel, removed: remove }) : undefined;
715
779
  if (remove) {
780
+ await record();
716
781
  task.gates = task.gates.filter(entry => entry !== gate);
717
782
  addLog(task, by, 'ungated', { gate: describeGate(gate) });
718
783
  return;
719
784
  }
720
785
  if (!gateOpen(gate)) fail('INVALID_TASK', `Gate ${gateId} of ${id} is already clear`);
721
786
  const text = checkText(note, 'note', NOTE_CHARS);
722
- task.gates = task.gates.map(entry => entry === gate ? { ...entry, resolved: { at: now(), by, ...(text ? { note: text } : {}) } } : entry);
723
- addLog(task, by, 'gate cleared', { gate: describeGate(gate), ...(text ? { note: text } : {}) });
787
+ checkChannel(channel);
788
+ if (choice !== undefined) {
789
+ if (gate.kind !== 'human') fail('INVALID_TASK', 'Only a human gate takes a choice');
790
+ if (typeof choice !== 'string' || !choice.trim() || (gate.options ? !gate.options.includes(choice.trim()) : choice.trim().length > GATE_OPTION_CHARS)) {
791
+ 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`);
792
+ }
793
+ }
794
+ const picked = choice?.trim();
795
+ await record();
796
+ task.gates = task.gates.map(entry => entry === gate ? { ...entry, resolved: { at: now(), by, ...(text ? { note: text } : {}), ...(picked ? { choice: picked } : {}), ...(channel ? { channel } : {}) } } : entry);
797
+ addLog(task, by, 'gate cleared', { gate: describeGate(gate), ...(picked ? { choice: picked } : {}), ...(channel ? { channel } : {}), ...(text ? { note: text } : {}) });
724
798
  // A formula's human step is the user's to do: approving its gate completes it.
725
799
  if (task.step?.human && task.status !== 'closed' && !task.gates.some(entry => gateOpen(entry))) {
726
- const summary = `Approved by ${by}${text ? `: ${text}` : ''}`;
800
+ const summary = `Approved by ${by}${picked ? ` (${picked})` : ''}${text ? `: ${text}` : ''}`;
727
801
  task.status = 'closed';
728
802
  task.assignee = null;
729
803
  task.closed = { at: now(), by, reason: 'done', summary };
@@ -732,6 +806,56 @@ export function resolveGate(projectRoot, id, gateId, { by, note, remove = false,
732
806
  }, { ifRev });
733
807
  }
734
808
 
809
+ /**
810
+ * The user rejects an open human gate: it stays open, and the decision is recorded on the gate
811
+ * (the latest one) and in the task's log. Rejecting again replaces the earlier decision.
812
+ */
813
+ export function rejectGate(projectRoot, id, gateId, { by, reason, ifRev, channel } = {}) {
814
+ return mutate(projectRoot, id, task => {
815
+ const gate = (task.gates ?? []).find(entry => entry.id === gateId) ?? fail('INVALID_TASK', `${id} has no gate ${gateId}`);
816
+ if (gate.kind !== 'human') fail('INVALID_TASK', 'Only a human gate is rejected; remove another gate instead');
817
+ if (!gateOpen(gate)) fail('INVALID_TASK', `Gate ${gateId} of ${id} is already clear`);
818
+ const text = checkText(reason, 'reason', NOTE_CHARS);
819
+ checkChannel(channel);
820
+ task.gates = task.gates.map(entry => entry === gate ? { ...entry, rejected: { at: now(), by, ...(text ? { reason: text } : {}), ...(channel ? { channel } : {}) } } : entry);
821
+ addLog(task, by, 'gate rejected', { gate: describeGate(gate), ...(channel ? { channel } : {}), ...(text ? { note: text } : {}) });
822
+ }, { ifRev });
823
+ }
824
+
825
+ /**
826
+ * A user's decision on a human gate that main has not been told of yet: a clear or rejection made
827
+ * with a channel, without `notified`. Older records, without a channel, are never reported.
828
+ */
829
+ export function gateDecisions(tasks) {
830
+ const found = [];
831
+ for (const task of tasks) for (const gate of task.gates ?? []) {
832
+ if (gate.kind !== 'human') continue;
833
+ if (gate.resolved?.overridden) continue;
834
+ if (gate.resolved?.channel && !gate.resolved.notified) found.push({ task, gate, decision: 'approved', record: gate.resolved });
835
+ else if (!gate.resolved && gate.rejected?.channel && !gate.rejected.notified) found.push({ task, gate, decision: 'rejected', record: gate.rejected });
836
+ }
837
+ return found;
838
+ }
839
+
840
+ /**
841
+ * Marks a decision reported, under the lock, and returns whether this call marked it. alpd marks
842
+ * it once main has taken the mail (t-595d), so a decision is reported at least once; with `at`,
843
+ * only the decision made then is marked, never a later one that replaced it.
844
+ * Marking does not change the task's rev, so an open card's ifRev stays valid.
845
+ */
846
+ export function markGateNotified(projectRoot, id, gateId, decision, at) {
847
+ return locked(projectRoot, async () => {
848
+ const { tasks } = await loadTasks(projectRoot);
849
+ const task = tasks.find(entry => entry.id === id);
850
+ const gate = task?.gates?.find(entry => entry.id === gateId);
851
+ const record = decision === 'approved' ? gate?.resolved : gate?.rejected;
852
+ if (!task || !record?.channel || record.notified || (at !== undefined && record.at !== at)) return false;
853
+ record.notified = now();
854
+ await save(projectRoot, task);
855
+ return true;
856
+ });
857
+ }
858
+
735
859
  /**
736
860
  * Asks GitHub about the open gh:pr and gh:run gates of tasks that are not closed,
737
861
  * and clears those whose pull request merged or whose run succeeded.
@@ -791,7 +915,8 @@ export async function compactTasks(projectRoot, { days = 30, dryRun = false } =
791
915
  ...task,
792
916
  description: clipText(task.description, COMPACT_TEXT),
793
917
  handoff: task.handoff ? { outcome: task.handoff.outcome, summary: clipText(String(task.handoff.summary ?? ''), COMPACT_TEXT), agent: task.handoff.agent, at: task.handoff.at } : null,
794
- gates: task.gates.map(({ id, kind, resolved }) => ({ id, kind, ...(resolved ? { resolved: { at: resolved.at, by: resolved.by } } : {}) })),
918
+ // `at` stays: it names the gate in the gate ledger (t-ca1f); an open human gate keeps its note too.
919
+ 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 } } : {}) })),
795
920
  log: [created, closed].filter(Boolean),
796
921
  rev: task.rev + 1,
797
922
  updatedAt: now(),
@@ -802,6 +927,8 @@ export async function compactTasks(projectRoot, { days = 30, dryRun = false } =
802
927
  compacted.push({ id: task.id, before, after });
803
928
  if (!dryRun) await save(projectRoot, next);
804
929
  }
930
+ // The gate ledger sheds what no longer guards anything (t-f438); best-effort, as ledgering is.
931
+ if (!dryRun) await ledgerPrune(projectRoot).catch(() => {});
805
932
  return compacted;
806
933
  });
807
934
  }
@@ -1,7 +1,12 @@
1
1
  import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { assetDir } from './packaged.js';
2
5
 
3
- /** Source packages carry templates beside src; legacy bundles live one directory deeper. */
6
+ /** Source packages carry templates beside src; legacy bundles live one directory deeper; the ALP executable extracts its embedded copy. */
4
7
  export function shippedTemplateRoot() {
8
+ const assets = assetDir();
9
+ if (assets) return pathToFileURL(path.join(assets, 'templates') + path.sep);
5
10
  const packaged = new URL('../templates/', import.meta.url);
6
11
  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)];
7
12
  return candidates.find(candidate => existsSync(candidate)) ?? packaged;
package/src/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;
package/src/validation.js CHANGED
@@ -14,9 +14,9 @@ function requireValue(condition, code, source, message) {
14
14
  /** Efforts a profile may name; a model ALP knows takes only its own (src/core/models.js). */
15
15
  const EFFORTS = ['none', 'off', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'ultracode'];
16
16
  /** Top-level keys of a project's .alp/settings.json. */
17
- export const PROJECT_SETTINGS = ['$schema', 'defaultAgent', 'workflow', 'runtime', 'permissions', 'verify', 'delegation', 'team', 'profile', 'templateDefaults'];
17
+ export const PROJECT_SETTINGS = ['$schema', 'defaultAgent', 'workflow', 'runtime', 'permissions', 'verify', 'delegation', 'team', 'profile', 'templateDefaults', 'compact', 'curate'];
18
18
  /** Top-level keys of the user's $ALP_HOME/settings.json. */
19
- export const USER_SETTINGS = ['$schema', 'language', 'permissions', 'limits', 'recovery', 'web'];
19
+ export const USER_SETTINGS = ['$schema', 'language', 'permissions', 'limits', 'recovery', 'web', 'curate'];
20
20
  /**
21
21
  * Top-level keys ALP no longer reads, with what to use instead. They warn rather than
22
22
  * fail, so settings written for an older ALP keep working.
@@ -62,11 +62,20 @@ export function settingsWarnings(settings, scope) {
62
62
  .map(({ key, instead }) => `setting '${key}' is no longer read; ${instead}`);
63
63
  }
64
64
 
65
+ /** curate: { monthly: boolean } turns the monthly lessons-and-skills review on or off. */
66
+ function checkCurate(settings, check) {
67
+ if (settings.curate === undefined) return;
68
+ check(object(settings.curate), 'curate must be an object');
69
+ check(Object.keys(settings.curate).every(key => key === 'monthly'), 'unsupported curate field; use monthly');
70
+ if (settings.curate.monthly !== undefined) check(typeof settings.curate.monthly === 'boolean', 'curate.monthly must be true or false');
71
+ }
72
+
65
73
  export function validateSettings(settings, source) {
66
74
  const check = (ok, message) => requireValue(ok, 'INVALID_SETTINGS', source, message);
67
75
  check(object(settings), 'expected an object');
68
76
  const { unknown } = settingsKeys(settings, PROJECT_SETTINGS, RETIRED_SETTINGS.project);
69
77
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], PROJECT_SETTINGS) : '');
78
+ checkCurate(settings, check);
70
79
  if (settings.defaultAgent !== undefined) check(nonempty(settings.defaultAgent), 'defaultAgent must be a nonempty string');
71
80
  if (settings.workflow !== undefined) {
72
81
  check(object(settings.workflow), 'workflow must be an object');
@@ -76,6 +85,12 @@ export function validateSettings(settings, source) {
76
85
  if (settings.workflow.maxPeers !== undefined) check(Number.isSafeInteger(settings.workflow.maxPeers) && settings.workflow.maxPeers > 0, 'workflow.maxPeers must be a positive integer');
77
86
  if (settings.workflow.supervisor !== undefined) check(typeof settings.workflow.supervisor === 'boolean', 'workflow.supervisor must be true or false');
78
87
  }
88
+ if (settings.compact !== undefined) {
89
+ check(object(settings.compact), 'compact must be an object');
90
+ check(Object.keys(settings.compact).every(key => ['auto', 'threshold'].includes(key)), 'compact takes auto and threshold');
91
+ if (settings.compact.auto !== undefined) check(typeof settings.compact.auto === 'boolean', 'compact.auto must be true or false');
92
+ if (settings.compact.threshold !== undefined) check(typeof settings.compact.threshold === 'number' && settings.compact.threshold > 0 && settings.compact.threshold < 1, 'compact.threshold must be a number between 0 and 1');
93
+ }
79
94
  if (settings.templateDefaults !== undefined) {
80
95
  check(object(settings.templateDefaults), 'templateDefaults must map teams to profile fingerprints');
81
96
  for (const [team, agents] of Object.entries(settings.templateDefaults)) {
@@ -158,6 +173,7 @@ export function validateUserSettings(settings, source) {
158
173
  check(object(settings), 'expected an object');
159
174
  const { unknown } = settingsKeys(settings, USER_SETTINGS, RETIRED_SETTINGS.user);
160
175
  check(!unknown.length, unknown.length ? unknownMessage(unknown[0], USER_SETTINGS) : '');
176
+ checkCurate(settings, check);
161
177
  for (const key of ['limits', 'recovery']) {
162
178
  if (settings[key] === undefined) continue;
163
179
  check(object(settings[key]), `${key} must be an object`);
@@ -131,6 +131,9 @@ Scope it to the roles whose work it guides: yourself, lead, peer, oracle,
131
131
  reviewer, supervisor, or a custom agent. List the lessons it replaces. The user
132
132
  sees the whole skill and approves it before it is saved.
133
133
 
134
+ To merge, shorten or remove lessons, use the curate skill and alp_lesson_curate;
135
+ never edit lesson files directly. The user approves every change first.
136
+
134
137
  ## Issues
135
138
 
136
139
  When you find a problem outside the task that is worth tracking, in this project
@@ -147,4 +150,5 @@ For material gaps in user intent use goal-griller; for unfamiliar implementation
147
150
  xia; for dependent work use sequence-execution-plan. Before assigning work, use
148
151
  prompt-leverage to prepare a proportional, self-contained brief. When implementing
149
152
  a correction use bug-loop; when local commits are requested use smart-commits.
153
+ When ALP asks for a checkpoint before compacting, or the user asks to compact, use compact.
150
154
  Clear requests need no repeated interview, and skills grant no additional authority.
@@ -1,5 +1,5 @@
1
1
  {
2
- "main": ["goal-griller", "xia", "sequence-execution-plan", "prompt-leverage", "bug-loop", "smart-commits"],
2
+ "main": ["goal-griller", "xia", "sequence-execution-plan", "prompt-leverage", "bug-loop", "smart-commits", "compact", "curate"],
3
3
  "lead": ["xia", "sequence-execution-plan", "prompt-leverage", "bug-loop", "smart-commits"],
4
4
  "peer": ["xia", "bug-loop", "smart-commits"],
5
5
  "oracle": [],
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: compact
3
+ description: "Viết checkpoint có cấu trúc trước khi compact context của main, để sau khi nén vẫn tiếp tục đúng việc. Dùng khi runtime báo context gần đầy (khoảng 70%), khi người dùng yêu cầu compact, hoặc trước khi chuyển phiên."
4
+ ---
5
+
6
+ # Compact
7
+
8
+ ## Khi dùng
9
+ - Runtime báo context dùng khoảng 70% hoặc hơn, hay yêu cầu viết checkpoint.
10
+ - Người dùng yêu cầu compact.
11
+ - Trước khi kết thúc hoặc chuyển phiên.
12
+
13
+ Không compact khi đang giữ lượt (alp_wait, alp_ask, delegate wait), hoặc khi đang viết dở câu trả lời. Phải trả lời người dùng trước.
14
+
15
+ ## Phương pháp
16
+ 1. **Kiểm thực tế, không chép trí nhớ.** Đọc alp_task ready/list và alp_board. Với PR/CI liên quan, chạy gh pr view/checks ngay trong lượt.
17
+ 2. **Viết checkpoint theo đúng các mục sau** (ngắn, có ID, có giờ):
18
+ - **Người dùng và ngôn ngữ:** profile (Phở/Cafe), ngôn ngữ trả lời.
19
+ - **Assignment đang chạy:** assignmentId, agent, taskId, worktree hoặc nhánh, ETA, note cuối kèm giờ.
20
+ - **Task và gate:** task đang làm hoặc chờ review; gate đang mở kèm nội dung; gate đã có quyết định nhưng chưa gỡ.
21
+ - **Quyết định của người dùng:** trích nguyên văn, kèm giờ và task nhận quyết định đó.
22
+ - **Câu hỏi đang chờ người dùng:** câu hỏi nào, ở gate nào.
23
+ - **PR/CI:** số PR, head SHA, trạng thái check đã kiểm lúc nào, watcher nền (job id) nếu có.
24
+ - **Rủi ro và giới hạn còn mở:** từng mục, kèm task theo dõi.
25
+ - **Bước tiếp theo:** theo thứ tự, ai làm.
26
+ 3. **Không đưa vào checkpoint:** bài học, skill, nội dung task đầy đủ (đã lưu ngoài context), log dài, secret.
27
+ 4. Gửi checkpoint cho runtime theo yêu cầu, hoặc ghi alp_pin/task note nếu compact thủ công. Sau đó báo người dùng một dòng: "Em đã compact context; checkpoint giữ X assignment, Y gate, Z quyết định."
28
+
29
+ ## Kiểm tra
30
+ - Mọi assignment đang chạy đều có ID.
31
+ - Mọi gate mở và mọi câu hỏi đang chờ đều có trong checkpoint.
32
+ - Quyết định của người dùng được trích nguyên văn, không diễn giải.
33
+ - Trạng thái PR/CI ghi rõ thời điểm đã kiểm.
34
+ - Sau compact, lượt đầu tiên đọc lại alp_task và gh trước khi báo trạng thái.
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: curate
3
+ description: "Rà soát toàn bộ bài học (lesson) và skill: gộp lesson trùng, rút gọn lesson dài, bỏ lesson đã có skill thay, đánh dấu skill không còn cần, và đề xuất issue cho ALP. Dùng khi người dùng yêu cầu rà soát, hoặc khi lịch curate hằng tháng đánh thức main."
4
+ ---
5
+
6
+ # Curate
7
+
8
+ ## Khi dùng
9
+ - Người dùng yêu cầu rà soát, dọn dẹp hay rút gọn lesson và skill.
10
+ - Main được đánh thức bởi lịch curate hằng tháng (prompt có `[alp-curate]`).
11
+
12
+ Không làm khi đang giữ một gate hay câu hỏi khác với người dùng; trả lời việc đó trước.
13
+
14
+ ## Phương pháp
15
+ 1. **Đọc hết, không nhớ lại.** Đọc `.alp/lessons.md` của project và `~/.alp/lessons.md` của người dùng; đọc mọi SKILL.md trong `~/.alp/skills`, `.alp/skills` và danh sách skill của từng role (`role-skills.json`).
16
+ 2. **Lập đề xuất, mỗi mục một dòng lý do:**
17
+ - **Gộp:** các lesson cùng ý thành một rule.
18
+ - **Rút gọn:** lesson dài hoặc lan man thành một rule ngắn: làm gì, khi nào.
19
+ - **Xóa:** lesson đã được một skill bao trọn (nêu tên skill), hoặc đã lỗi thời.
20
+ - **Thành skill:** 3 lesson trở lên cùng chủ đề thì gom thành skill qua `alp_skill` (truyền `lessons` để bỏ chúng).
21
+ - **Skill không còn cần:** trùng skill khác, không role nào dùng, hay đã lỗi thời. Chỉ đánh dấu và nêu lý do; ALP chưa có thao tác xóa skill nên người dùng tự xóa.
22
+ - **Đề xuất cho ALP:** lesson hay skill hữu ích cho mọi người dùng, hoặc chỗ ALP còn thiếu.
23
+ 3. **Gửi qua cổng duyệt, không hỏi trước trong chat.** Tóm tắt đề xuất trong một tin, rồi gọi ngay các tool bên dưới. Lần duyệt trong tool là lần duyệt duy nhất; người dùng từ chối hay góp ý thì sửa và đề xuất lại.
24
+ 4. **Các tool:**
25
+ - Lesson: một lần gọi `alp_lesson_curate` với mọi thay đổi (remove là văn bản đúng nguyên văn; add là rule thay thế khi gộp hoặc rút gọn). ALP hiện toàn bộ thay đổi trong một lần duyệt.
26
+ - Skill mới: `alp_skill`.
27
+ - Issue: `alp_issue` action search target alp trước; chưa có thì create, đã có thì comment. Người dùng duyệt từng bản nháp.
28
+ 5. Báo kết quả một đoạn ngắn: đã gộp, rút gọn, xóa bao nhiêu; skill nào được đánh dấu; issue nào đã tạo.
29
+
30
+ ## Kiểm tra
31
+ - Không sửa hay xóa lesson nào ngoài `alp_lesson_curate`; không sửa file lesson trực tiếp.
32
+ - Mỗi rule sau gộp vẫn giữ đủ ý của các lesson gốc.
33
+ - Mỗi lesson bị xóa vì skill đều nêu đúng tên skill thay nó.
34
+ - Issue không chứa secret, đường dẫn riêng hay nội dung project của người dùng.
35
+ - Không có thay đổi nào khi người dùng chưa duyệt; lesson không tìm thấy được báo lại, không đoán.