@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
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,54 @@ 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 answers a human gate offers its approver: at most 10 distinct, nonempty, each at most 200 characters. */
748
+ function gateOptions(value) {
749
+ if (!Array.isArray(value) || value.length > GATE_OPTIONS || !value.every(item => typeof item === 'string' && !!item.trim() && item.trim().length <= GATE_OPTION_CHARS)) {
750
+ fail('INVALID_TASK', `options must list at most ${GATE_OPTIONS} nonempty answers of at most ${GATE_OPTION_CHARS} characters`);
751
+ }
752
+ return [...new Set(value.map(item => item.trim()))];
753
+ }
754
+
755
+ const checkChannel = channel => {
756
+ if (channel !== undefined && !GATE_CHANNELS.includes(channel)) fail('INVALID_TASK', `channel must be one of ${GATE_CHANNELS.join(', ')}`);
757
+ return channel;
758
+ };
759
+
760
+ /**
761
+ * Clears a gate by hand, or removes it with `remove`. Only the user clears a human gate; the caller enforces who `by` is.
762
+ * `choice` records which of a human gate's options the user picked; `channel` (paseo, web or cli) where they decided.
763
+ */
764
+ export function resolveGate(projectRoot, id, gateId, { by, note, remove = false, ifRev, choice, channel } = {}) {
765
+ return mutate(projectRoot, id, async task => {
714
766
  const gate = (task.gates ?? []).find(entry => entry.id === gateId) ?? fail('INVALID_TASK', `${id} has no gate ${gateId}`);
767
+ // Recorded once every check passed and before the task file is written (t-ca1f).
768
+ const record = () => gate.kind === 'human' ? ledgerResolve(projectRoot, task.id, gate, { by, channel, removed: remove }) : undefined;
715
769
  if (remove) {
770
+ await record();
716
771
  task.gates = task.gates.filter(entry => entry !== gate);
717
772
  addLog(task, by, 'ungated', { gate: describeGate(gate) });
718
773
  return;
719
774
  }
720
775
  if (!gateOpen(gate)) fail('INVALID_TASK', `Gate ${gateId} of ${id} is already clear`);
721
776
  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 } : {}) });
777
+ checkChannel(channel);
778
+ if (choice !== undefined) {
779
+ if (gate.kind !== 'human') fail('INVALID_TASK', 'Only a human gate takes a choice');
780
+ if (typeof choice !== 'string' || !choice.trim() || (gate.options ? !gate.options.includes(choice.trim()) : choice.trim().length > GATE_OPTION_CHARS)) {
781
+ 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`);
782
+ }
783
+ }
784
+ const picked = choice?.trim();
785
+ await record();
786
+ task.gates = task.gates.map(entry => entry === gate ? { ...entry, resolved: { at: now(), by, ...(text ? { note: text } : {}), ...(picked ? { choice: picked } : {}), ...(channel ? { channel } : {}) } } : entry);
787
+ addLog(task, by, 'gate cleared', { gate: describeGate(gate), ...(picked ? { choice: picked } : {}), ...(channel ? { channel } : {}), ...(text ? { note: text } : {}) });
724
788
  // A formula's human step is the user's to do: approving its gate completes it.
725
789
  if (task.step?.human && task.status !== 'closed' && !task.gates.some(entry => gateOpen(entry))) {
726
- const summary = `Approved by ${by}${text ? `: ${text}` : ''}`;
790
+ const summary = `Approved by ${by}${picked ? ` (${picked})` : ''}${text ? `: ${text}` : ''}`;
727
791
  task.status = 'closed';
728
792
  task.assignee = null;
729
793
  task.closed = { at: now(), by, reason: 'done', summary };
@@ -732,6 +796,55 @@ export function resolveGate(projectRoot, id, gateId, { by, note, remove = false,
732
796
  }, { ifRev });
733
797
  }
734
798
 
799
+ /**
800
+ * The user rejects an open human gate: it stays open, and the decision is recorded on the gate
801
+ * (the latest one) and in the task's log. Rejecting again replaces the earlier decision.
802
+ */
803
+ export function rejectGate(projectRoot, id, gateId, { by, reason, ifRev, channel } = {}) {
804
+ return mutate(projectRoot, id, task => {
805
+ const gate = (task.gates ?? []).find(entry => entry.id === gateId) ?? fail('INVALID_TASK', `${id} has no gate ${gateId}`);
806
+ if (gate.kind !== 'human') fail('INVALID_TASK', 'Only a human gate is rejected; remove another gate instead');
807
+ if (!gateOpen(gate)) fail('INVALID_TASK', `Gate ${gateId} of ${id} is already clear`);
808
+ const text = checkText(reason, 'reason', NOTE_CHARS);
809
+ checkChannel(channel);
810
+ task.gates = task.gates.map(entry => entry === gate ? { ...entry, rejected: { at: now(), by, ...(text ? { reason: text } : {}), ...(channel ? { channel } : {}) } } : entry);
811
+ addLog(task, by, 'gate rejected', { gate: describeGate(gate), ...(channel ? { channel } : {}), ...(text ? { note: text } : {}) });
812
+ }, { ifRev });
813
+ }
814
+
815
+ /**
816
+ * A user's decision on a human gate that main has not been told of yet: a clear or rejection made
817
+ * with a channel, without `notified`. Older records, without a channel, are never reported.
818
+ */
819
+ export function gateDecisions(tasks) {
820
+ const found = [];
821
+ for (const task of tasks) for (const gate of task.gates ?? []) {
822
+ if (gate.kind !== 'human') continue;
823
+ if (gate.resolved?.overridden) continue;
824
+ if (gate.resolved?.channel && !gate.resolved.notified) found.push({ task, gate, decision: 'approved', record: gate.resolved });
825
+ else if (!gate.resolved && gate.rejected?.channel && !gate.rejected.notified) found.push({ task, gate, decision: 'rejected', record: gate.rejected });
826
+ }
827
+ return found;
828
+ }
829
+
830
+ /**
831
+ * Marks a decision reported, under the lock, and returns whether this call marked it: the one
832
+ * caller that gets true tells main, so card, panel and CLI never report one decision twice.
833
+ * Marking does not change the task's rev, so an open card's ifRev stays valid.
834
+ */
835
+ export function markGateNotified(projectRoot, id, gateId, decision) {
836
+ return locked(projectRoot, async () => {
837
+ const { tasks } = await loadTasks(projectRoot);
838
+ const task = tasks.find(entry => entry.id === id);
839
+ const gate = task?.gates?.find(entry => entry.id === gateId);
840
+ const record = decision === 'approved' ? gate?.resolved : gate?.rejected;
841
+ if (!task || !record?.channel || record.notified) return false;
842
+ record.notified = now();
843
+ await save(projectRoot, task);
844
+ return true;
845
+ });
846
+ }
847
+
735
848
  /**
736
849
  * Asks GitHub about the open gh:pr and gh:run gates of tasks that are not closed,
737
850
  * and clears those whose pull request merged or whose run succeeded.
@@ -791,7 +904,8 @@ export async function compactTasks(projectRoot, { days = 30, dryRun = false } =
791
904
  ...task,
792
905
  description: clipText(task.description, COMPACT_TEXT),
793
906
  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 } } : {}) })),
907
+ // `at` stays: it names the gate in the gate ledger (t-ca1f); an open human gate keeps its note too.
908
+ 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
909
  log: [created, closed].filter(Boolean),
796
910
  rev: task.rev + 1,
797
911
  updatedAt: now(),
@@ -802,6 +916,8 @@ export async function compactTasks(projectRoot, { days = 30, dryRun = false } =
802
916
  compacted.push({ id: task.id, before, after });
803
917
  if (!dryRun) await save(projectRoot, next);
804
918
  }
919
+ // The gate ledger sheds what no longer guards anything (t-f438); best-effort, as ledgering is.
920
+ if (!dryRun) await ledgerPrune(projectRoot).catch(() => {});
805
921
  return compacted;
806
922
  });
807
923
  }
@@ -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;
@@ -0,0 +1,259 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { lstat, realpath, open } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { constants } from 'node:fs';
5
+
6
+ /** Bounded, no-follow administrative reads; no Git process is needed to re-check a grant. */
7
+ async function control(file) {
8
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
9
+ try {
10
+ const info = await handle.stat();
11
+ if (!info.isFile() || info.nlink !== 1 || info.size > 4096) throw new Error('Invalid Git administrative file');
12
+ const bytes = Buffer.alloc(4097);
13
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
14
+ if (bytesRead > 4096) throw new Error('Git administrative file exceeds limit');
15
+ return bytes
16
+ .subarray(0, bytesRead)
17
+ .toString('utf8')
18
+ .replace(/\r?\n$/, '');
19
+ } finally {
20
+ await handle.close();
21
+ }
22
+ }
23
+ export async function repositoryIdentity(directory) {
24
+ if ((await realpath(directory)) !== directory) throw new Error('Repository root is not canonical');
25
+ const entry = path.join(directory, '.git');
26
+ const info = await lstat(entry);
27
+ let gitDir;
28
+ if (info.isDirectory()) gitDir = await realpath(entry);
29
+ else {
30
+ const value = await control(entry);
31
+ if (!value.startsWith('gitdir: ') || /[\r\n\0]/.test(value)) throw new Error('Invalid Git control link');
32
+ gitDir = await realpath(path.resolve(directory, value.slice(8)));
33
+ }
34
+ const commonEntry = path.join(gitDir, 'commondir');
35
+ const hasCommon = await lstat(commonEntry).catch((error) => {
36
+ if (error.code === 'ENOENT') return undefined;
37
+ throw error;
38
+ });
39
+ const commonDir = hasCommon ? await realpath(path.resolve(gitDir, await control(commonEntry))) : gitDir;
40
+ if (gitDir !== commonDir) {
41
+ if (
42
+ path.dirname(gitDir) !== path.join(commonDir, 'worktrees') ||
43
+ path.resolve(gitDir, await control(path.join(gitDir, 'gitdir'))) !== entry
44
+ )
45
+ throw new Error('Git worktree backlink changed');
46
+ }
47
+ const head = await control(path.join(gitDir, 'HEAD'));
48
+ const branch = head.startsWith('ref: refs/heads/') ? head.slice(16) : null;
49
+ if (branch !== null && (!branch || /[\r\n\0]/.test(branch))) throw new Error('Invalid branch reference');
50
+ return { gitDir, commonDir, branch };
51
+ }
52
+
53
+ /** User workspace primitives. Assignment cleanup's force/rm semantics must never be used here. */
54
+ export function userWorktreeGit({ executable = '/usr/bin/git', timeoutMs = 15_000, maxBytes = 2 * 1024 * 1024 } = {}) {
55
+ if (process.platform === 'win32') throw new Error('User worktree operations are unavailable on this host');
56
+ if (!path.isAbsolute(executable)) throw new Error('Git executable must be host configured and absolute');
57
+ const disabled = [
58
+ '-c',
59
+ 'core.hooksPath=/dev/null',
60
+ '-c',
61
+ 'core.fsmonitor=false',
62
+ '-c',
63
+ 'core.untrackedCache=false',
64
+ '-c',
65
+ 'core.pager=cat',
66
+ '-c',
67
+ 'maintenance.auto=false',
68
+ '-c',
69
+ 'gc.auto=0',
70
+ '-c',
71
+ 'protocol.allow=never',
72
+ '-c',
73
+ 'submodule.recurse=false'
74
+ ];
75
+ // No inherited Git context, PATH or user/system config. Repository config is data, never a program.
76
+ const env = {
77
+ PATH: '/usr/bin:/bin',
78
+ GIT_CONFIG_NOSYSTEM: '1',
79
+ GIT_CONFIG_GLOBAL: '/dev/null',
80
+ GIT_TERMINAL_PROMPT: '0',
81
+ GIT_OPTIONAL_LOCKS: '0',
82
+ LANG: 'C',
83
+ LC_ALL: 'C'
84
+ };
85
+ async function raw(cwd, args, extra = []) {
86
+ return new Promise((resolve, reject) => {
87
+ const child = spawn(executable, [...disabled, ...extra, ...args], {
88
+ cwd,
89
+ env,
90
+ stdio: ['ignore', 'pipe', 'pipe'],
91
+ windowsHide: true,
92
+ detached: true
93
+ });
94
+ let size = 0;
95
+ let overflow = false;
96
+ const stdout = [];
97
+ const stderr = [];
98
+ const kill = () => {
99
+ try {
100
+ process.kill(-child.pid, 'SIGKILL');
101
+ } catch {
102
+ child.kill('SIGKILL');
103
+ }
104
+ };
105
+ const timer = setTimeout(() => {
106
+ overflow = true;
107
+ kill();
108
+ }, timeoutMs);
109
+ const collect = (sink) => (chunk) => {
110
+ size += chunk.length;
111
+ if (size > maxBytes) {
112
+ overflow = true;
113
+ kill();
114
+ } else sink.push(chunk);
115
+ };
116
+ child.stdout.on('data', collect(stdout));
117
+ child.stderr.on('data', collect(stderr));
118
+ child.once('error', (error) => {
119
+ clearTimeout(timer);
120
+ reject(error);
121
+ });
122
+ child.once('close', (code) => {
123
+ clearTimeout(timer);
124
+ if (overflow) reject(new Error('Git operation exceeded its host limit'));
125
+ else
126
+ resolve({
127
+ code,
128
+ stdout: Buffer.concat(stdout).toString('utf8'),
129
+ stderr: Buffer.concat(stderr).toString('utf8')
130
+ });
131
+ });
132
+ });
133
+ }
134
+ async function filterOverrides(cwd) {
135
+ // Status/removal may run clean/process filters as well as creation's smudge filter.
136
+ const filters = await raw(cwd, [
137
+ 'config',
138
+ '--null',
139
+ '--name-only',
140
+ '--get-regexp',
141
+ '^filter\\..*\\.(smudge|clean|process|required)$'
142
+ ]);
143
+ if (filters.code !== 0 && filters.code !== 1) throw new Error('Cannot inspect repository filters');
144
+ const neutral = filters.stdout
145
+ .split('\0')
146
+ .filter(Boolean)
147
+ .flatMap((key) => ['-c', `${key}=${key.endsWith('.required') ? 'false' : ''}`]);
148
+ return neutral;
149
+ }
150
+ async function run(cwd, args, extra = []) {
151
+ return raw(cwd, args, [...(await filterOverrides(cwd)), ...extra]);
152
+ }
153
+ async function checked(cwd, args, extra = []) {
154
+ const result = await run(cwd, args, extra);
155
+ if (result.code !== 0) throw new Error('Git workspace operation refused');
156
+ return result.stdout.trim();
157
+ }
158
+ async function directory(value) {
159
+ const canonical = await realpath(value);
160
+ if (canonical !== value || !(await lstat(value)).isDirectory())
161
+ throw new Error('Workspace paths must be canonical directories');
162
+ return canonical;
163
+ }
164
+ async function facts(source) {
165
+ await directory(source);
166
+ const top = await checked(source, ['rev-parse', '--show-toplevel']);
167
+ if ((await realpath(top)) !== source) throw new Error('Workspace must be a repository top level');
168
+ const commonDir = await realpath(
169
+ await checked(source, ['rev-parse', '--path-format=absolute', '--git-common-dir'])
170
+ );
171
+ const identity = await repositoryIdentity(source);
172
+ if (identity.commonDir !== commonDir) throw new Error('Repository identity changed');
173
+ const head = await checked(source, ['rev-parse', '--verify', 'HEAD']);
174
+ const branch = await run(source, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
175
+ return { commonDir, gitDir: identity.gitDir, head, branch: branch.code === 0 ? branch.stdout.trim() : null };
176
+ }
177
+ async function list(source) {
178
+ const result = await checked(source, ['worktree', 'list', '--porcelain', '-z']);
179
+ return result
180
+ .split('\0\0')
181
+ .filter(Boolean)
182
+ .map((block) =>
183
+ Object.fromEntries(
184
+ block
185
+ .split('\0')
186
+ .filter(Boolean)
187
+ .map((line) => {
188
+ const i = line.indexOf(' ');
189
+ return i < 0 ? [line, true] : [line.slice(0, i), line.slice(i + 1)];
190
+ })
191
+ )
192
+ );
193
+ }
194
+ async function inspect(source, target, branch) {
195
+ const row = (await list(source)).find((row) => row.worktree === target);
196
+ if (!row) return undefined;
197
+ await directory(target);
198
+ if (row.branch !== `refs/heads/${branch}` || row.locked || row.prunable)
199
+ throw new Error('Managed worktree identity changed');
200
+ const origin = await facts(source);
201
+ const destination = await facts(target);
202
+ if (origin.commonDir !== destination.commonDir) throw new Error('Managed worktree repository changed');
203
+ return row;
204
+ }
205
+ async function assertClean(target) {
206
+ const flags = await checked(target, ['ls-files', '-v', '-z']);
207
+ if (flags.split('\0').some((row) => row && (row[0] === 'S' || /[a-z]/.test(row[0]))))
208
+ throw new Error('Worktree has hidden index state');
209
+ if ((await checked(target, ['ls-files', '--stage', '-z'])).split('\0').some((row) => row.startsWith('160000 ')))
210
+ throw new Error('Worktree has submodules');
211
+ // Ignored data is user data too. Never force a delete or fall back to recursive rm.
212
+ if ((await checked(target, ['status', '--porcelain=v1', '--untracked-files=all', '--ignored'])).length)
213
+ throw new Error('Worktree contains uncommitted or ignored files');
214
+ }
215
+ return {
216
+ facts,
217
+ inspect,
218
+ assertClean,
219
+ async checkoutFacts(directory) {
220
+ const canonical = await realpath(directory);
221
+ const repoRoot = await checked(canonical, ['rev-parse', '--show-toplevel']);
222
+ const branch = await run(canonical, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
223
+ const remote = await run(canonical, ['config', '--get', 'remote.origin.url']);
224
+ const status = await checked(canonical, ['status', '--porcelain=v1', '--untracked-files=all']);
225
+ return {
226
+ isGit: /** @type {const} */ (true),
227
+ repoRoot,
228
+ currentBranch: branch.code === 0 ? branch.stdout.trim() : null,
229
+ remoteUrl: remote.code === 0 ? remote.stdout.trim() || null : null,
230
+ isDirty: !!status
231
+ };
232
+ },
233
+ async create(source, parent, name, branch, head) {
234
+ await directory(parent);
235
+ if (!/^wks_[0-9a-f]{16}$/.test(name) || branch !== `alp/workspace/${name}` || !/^[0-9a-f]{40,64}$/.test(head))
236
+ throw new Error('Invalid generated worktree identity');
237
+ const target = path.join(parent, name);
238
+ if (
239
+ await lstat(target).catch((error) => {
240
+ if (error.code === 'ENOENT') return undefined;
241
+ throw error;
242
+ })
243
+ )
244
+ throw new Error('Worktree destination already exists');
245
+ await checked(source, ['worktree', 'add', '--quiet', '--no-checkout', '-b', branch, target, head]);
246
+ // Conditional gitdir/onbranch config is resolved in the new checkout before materialization.
247
+ await checked(target, ['reset', '--hard', '--no-recurse-submodules', head]);
248
+ if (!(await inspect(source, target, branch))) throw new Error('Worktree creation needs reconciliation');
249
+ return target;
250
+ },
251
+ async remove(source, target, branch) {
252
+ if (!(await inspect(source, target, branch))) throw new Error('Managed worktree is missing');
253
+ await assertClean(target);
254
+ await checked(source, ['worktree', 'remove', target], await filterOverrides(target));
255
+ if ((await list(source)).some((row) => row.worktree === target))
256
+ throw new Error('Worktree removal needs reconciliation');
257
+ }
258
+ };
259
+ }
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`);
@@ -167,8 +183,10 @@ export function validateUserSettings(settings, source) {
167
183
  }
168
184
  if (settings.web !== undefined) {
169
185
  check(object(settings.web), 'web must be an object');
170
- const extra = Object.keys(settings.web).find(field => !['enabled', 'port', 'relay'].includes(field));
171
- check(!extra, `unsupported web field '${extra}'; use enabled, port or relay`);
186
+ const extra = Object.keys(settings.web).find(field => !['enabled', 'port', 'relay', 'permissions'].includes(field));
187
+ check(!extra, `unsupported web field '${extra}'; use enabled, port, relay or permissions`);
188
+ // Gateway permissions `alp web` adds to its default grant; alp-web checks each name against the gateway's list.
189
+ if (settings.web.permissions !== undefined) check(Array.isArray(settings.web.permissions) && settings.web.permissions.every(entry => typeof entry === 'string' && /^[a-z][a-z.]*$/.test(entry)), 'web.permissions must be a list of permission names, such as files.read');
172
190
  // The relay that lets Paseo's app reach alpd from another device (ALPD §64).
173
191
  const relay = settings.web.relay;
174
192
  if (relay !== undefined) {
@@ -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.