@anhlp/alp-core 0.0.0-beta.2 → 0.0.1-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/dist/backup.js +106 -4
  2. package/dist/bridges.d.ts +26 -0
  3. package/dist/bridges.js +96 -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/library-edit.d.ts +57 -5
  9. package/dist/library-edit.js +216 -11
  10. package/dist/library.d.ts +14 -1
  11. package/dist/library.js +73 -5
  12. package/dist/migrations.js +1 -1
  13. package/dist/models.d.ts +74 -0
  14. package/dist/models.js +67 -1
  15. package/dist/packaged.d.ts +122 -0
  16. package/dist/packaged.js +125 -0
  17. package/dist/packs.d.ts +57 -0
  18. package/dist/packs.js +247 -0
  19. package/dist/permissions.d.ts +3 -2
  20. package/dist/permissions.js +6 -3
  21. package/dist/profiles.js +6 -6
  22. package/dist/providers.d.ts +4 -5
  23. package/dist/providers.js +26 -5
  24. package/dist/skill-validate.d.ts +85 -0
  25. package/dist/skill-validate.js +298 -0
  26. package/dist/task-rows.d.ts +5 -0
  27. package/dist/task-rows.js +1 -1
  28. package/dist/tasks.d.ts +23 -4
  29. package/dist/tasks.js +103 -9
  30. package/dist/types.d.ts +3 -0
  31. package/dist/upgrade.d.ts +10 -0
  32. package/dist/upgrade.js +112 -6
  33. package/dist/user-settings.d.ts +2 -0
  34. package/dist/user-settings.js +40 -1
  35. package/dist/user-worktree.d.ts +29 -0
  36. package/dist/user-worktree.js +242 -0
  37. package/dist/validation.d.ts +1 -0
  38. package/dist/validation.js +35 -13
  39. package/package.json +34 -2
  40. package/src/backup.js +106 -5
  41. package/src/bridges.js +113 -0
  42. package/src/gate-ledger.js +125 -0
  43. package/src/index.js +1 -0
  44. package/src/library-edit.js +227 -12
  45. package/src/library.js +96 -6
  46. package/src/migrations.js +1 -1
  47. package/src/models.js +87 -1
  48. package/src/packaged.js +207 -0
  49. package/src/packs.js +246 -0
  50. package/src/permissions.d.ts +3 -2
  51. package/src/permissions.js +13 -3
  52. package/src/profiles.js +7 -7
  53. package/src/providers.js +23 -7
  54. package/src/resolver.js +1 -1
  55. package/src/skill-validate.js +287 -0
  56. package/src/task-rows.js +1 -1
  57. package/src/tasks.d.ts +23 -4
  58. package/src/tasks.js +137 -10
  59. package/src/types.d.ts +3 -0
  60. package/src/upgrade.js +54 -6
  61. package/src/user-settings.d.ts +2 -0
  62. package/src/user-settings.js +51 -1
  63. package/src/user-worktree.js +259 -0
  64. package/src/validation.d.ts +1 -0
  65. package/src/validation.js +43 -14
  66. package/templates/ALP.md +52 -52
  67. package/templates/agents/lead/AGENT.md +77 -74
  68. package/templates/agents/main/AGENT.md +153 -141
  69. package/templates/agents/oracle/AGENT.md +38 -37
  70. package/templates/agents/peer/AGENT.md +56 -52
  71. package/templates/agents/reviewer/AGENT.md +63 -65
  72. package/templates/agents/supervisor/AGENT.md +63 -63
  73. package/templates/packs/architecture/agents/architect/AGENT.md +41 -0
  74. package/templates/packs/architecture/agents/architect/agent.json +5 -0
  75. package/templates/packs/architecture/agents/docs-maintainer/AGENT.md +33 -0
  76. package/templates/packs/architecture/agents/docs-maintainer/agent.json +4 -0
  77. package/templates/packs/architecture/pack.json +7 -0
  78. package/templates/packs/architecture/teams/blueprint/HOUSE_RULES.md +12 -0
  79. package/templates/packs/architecture/teams/blueprint/team.json +19 -0
  80. package/templates/packs/backend/pack.json +6 -0
  81. package/templates/packs/backend/skills/backend-development/SKILL.md +102 -0
  82. package/templates/packs/backend/skills/backend-development/references/api-design.md +96 -0
  83. package/templates/packs/backend/skills/backend-development/references/authentication.md +78 -0
  84. package/templates/packs/backend/skills/backend-development/references/error-handling.md +86 -0
  85. package/templates/packs/backend/skills/backend-development/references/testing.md +81 -0
  86. package/templates/packs/backend/skills/databases/SKILL.md +103 -0
  87. package/templates/packs/backend/skills/databases/references/query-performance.md +87 -0
  88. package/templates/packs/backend/skills/databases/references/schema-and-migrations.md +87 -0
  89. package/templates/packs/design/pack.json +6 -0
  90. package/templates/packs/design/skills/ui-design/SKILL.md +86 -0
  91. package/templates/packs/design/skills/ui-design/references/design-tokens.md +67 -0
  92. package/templates/packs/design/skills/ui-design/references/interaction-states.md +73 -0
  93. package/templates/packs/design/skills/ui-design/references/layout-and-typography.md +71 -0
  94. package/templates/packs/design/skills/ui-design/references/ui-review.md +83 -0
  95. package/templates/packs/frontend/pack.json +6 -0
  96. package/templates/packs/frontend/skills/frontend-development/SKILL.md +105 -0
  97. package/templates/packs/frontend/skills/frontend-development/references/accessibility.md +86 -0
  98. package/templates/packs/frontend/skills/frontend-development/references/components-and-state.md +79 -0
  99. package/templates/packs/frontend/skills/frontend-development/references/data-fetching.md +86 -0
  100. package/templates/packs/frontend/skills/frontend-development/references/frameworks.md +77 -0
  101. package/templates/packs/frontend/skills/frontend-development/references/performance.md +78 -0
  102. package/templates/packs/integration/pack.json +6 -0
  103. package/templates/packs/integration/skills/mcp-integration/SKILL.md +100 -0
  104. package/templates/packs/integration/skills/mcp-integration/references/server-implementation.md +95 -0
  105. package/templates/packs/integration/skills/mcp-integration/references/testing.md +78 -0
  106. package/templates/packs/integration/skills/mcp-integration/references/tool-design.md +97 -0
  107. package/templates/packs/operations/pack.json +6 -0
  108. package/templates/packs/operations/skills/devops/SKILL.md +85 -0
  109. package/templates/packs/operations/skills/devops/references/ci-cd.md +84 -0
  110. package/templates/packs/operations/skills/devops/references/containers.md +85 -0
  111. package/templates/packs/operations/skills/devops/references/deployment-and-rollback.md +85 -0
  112. package/templates/packs/operations/skills/devops/references/observability.md +86 -0
  113. package/templates/packs/quality/pack.json +6 -0
  114. package/templates/packs/quality/skills/web-testing/SKILL.md +102 -0
  115. package/templates/packs/quality/skills/web-testing/references/e2e.md +85 -0
  116. package/templates/packs/quality/skills/web-testing/references/performance-testing.md +85 -0
  117. package/templates/packs/quality/skills/web-testing/references/security-testing.md +78 -0
  118. package/templates/packs/quality/skills/web-testing/references/unit-and-component.md +78 -0
  119. package/templates/role-skills.json +4 -4
  120. package/templates/skills/architecture-docs/SKILL.md +81 -0
  121. package/templates/skills/architecture-docs/references/adr.md +62 -0
  122. package/templates/skills/architecture-docs/references/diagrams.md +60 -0
  123. package/templates/skills/architecture-docs/references/evidence-rules.md +49 -0
  124. package/templates/skills/bug-loop/SKILL.md +41 -40
  125. package/templates/skills/bug-loop/references/test-proof.md +21 -19
  126. package/templates/skills/compact/SKILL.md +34 -0
  127. package/templates/skills/curate/SKILL.md +36 -0
  128. package/templates/skills/feature-architecture/SKILL.md +90 -0
  129. package/templates/skills/feature-architecture/references/architecture-contract.md +95 -0
  130. package/templates/skills/feature-architecture/references/feature-design.md +69 -0
  131. package/templates/skills/feature-architecture/scripts/check-boundaries.mjs +270 -0
  132. package/templates/skills/goal-griller/SKILL.md +27 -27
  133. package/templates/skills/prompt-leverage/SKILL.md +29 -27
  134. package/templates/skills/prompt-leverage/references/brief-template.md +9 -9
  135. package/templates/skills/release-readiness/SKILL.md +83 -0
  136. package/templates/skills/release-readiness/references/checklist.md +40 -0
  137. package/templates/skills/release-readiness/references/verdict-template.md +53 -0
  138. package/templates/skills/safe-refactor/SKILL.md +84 -0
  139. package/templates/skills/safe-refactor/references/characterization-tests.md +57 -0
  140. package/templates/skills/safe-refactor/references/compatibility-checklist.md +56 -0
  141. package/templates/skills/security-review/SKILL.md +87 -0
  142. package/templates/skills/security-review/references/checklist.md +74 -0
  143. package/templates/skills/security-review/references/severity.md +61 -0
  144. package/templates/skills/sequence-execution-plan/SKILL.md +41 -38
  145. package/templates/skills/sequence-execution-plan/references/plan-template.md +5 -5
  146. package/templates/skills/skill-authoring/SKILL.md +84 -0
  147. package/templates/skills/skill-authoring/references/evaluation.md +45 -0
  148. package/templates/skills/skill-authoring/references/skill-anatomy.md +74 -0
  149. package/templates/skills/skill-authoring/references/trigger-design.md +52 -0
  150. package/templates/skills/smart-commits/SKILL.md +37 -36
  151. package/templates/skills/test-strategy/SKILL.md +83 -0
  152. package/templates/skills/test-strategy/references/contract-tests.md +46 -0
  153. package/templates/skills/test-strategy/references/risk-matrix.md +53 -0
  154. package/templates/skills/xia/SKILL.md +40 -38
  155. package/templates/teams/cafe/HOUSE_RULES.md +1 -1
  156. package/templates/teams/cafe/team.json +1 -1
  157. package/templates/teams/pho/HOUSE_RULES.md +1 -1
  158. package/templates/teams/pho/team.json +1 -1
@@ -0,0 +1,287 @@
1
+ import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Skill validation (Agent Skills format, https://agentskills.io/specification): a skill is a
6
+ * directory holding SKILL.md, whose YAML frontmatter names it and says what it is for, and the
7
+ * references, scripts and assets SKILL.md points to.
8
+ *
9
+ * Two modes. `strict` is for skills ALP ships, packs and new skills: format problems are errors.
10
+ * `legacy` (the default) is for skills already in a user's library or project: format problems
11
+ * are warnings with a migration hint, since ALP never rewrites them and the runtime keeps loading
12
+ * them. A symlink leaving the skill, a broken symlink or an unreadable file is an error in both
13
+ * modes; a plain path leaving the skill is an error in strict mode and a warning in legacy mode. Validation only reads; it never runs a script or follows a link outside the skill.
14
+ */
15
+
16
+ /** Frontmatter keys of the Agent Skills specification. */
17
+ export const SPEC_KEYS = ['name', 'description', 'license', 'compatibility', 'metadata', 'allowed-tools'];
18
+ /** Keys other runtimes add (Claude Code); kept, reported as runtime-specific in strict mode. */
19
+ const RUNTIME_KEYS = ['argument-hint', 'disable-model-invocation', 'user-invocable', 'model', 'version', 'when_to_use', 'mode'];
20
+ export const NAME_MAX = 64;
21
+ export const DESCRIPTION_MAX = 1024;
22
+ /** How much of a description ALP's skill index shows (resolve.ts SKILL_DESCRIPTION_CHARS). */
23
+ export const INDEX_DESCRIPTION_CHARS = 400;
24
+ const COMPATIBILITY_MAX = 500;
25
+ const BODY_LINES_RECOMMENDED = 500;
26
+ const MAX_FILES = 2000;
27
+
28
+
29
+ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
30
+ /** A trigger cue: the description says when to use the skill. */
31
+ const TRIGGER_RE = /\b(use|when|before|after|whenever|for)\b|dùng|khi/i;
32
+
33
+ /** Whether `name` follows the specification's name rules. */
34
+ export const specName = name => typeof name === 'string' && name.length >= 1 && name.length <= NAME_MAX && NAME_RE.test(name);
35
+
36
+ /** A YAML double-quoted scalar's escapes (the JSON subset plus \/ and \e not needed here). */
37
+ function doubleQuoted(raw) {
38
+ try { return JSON.parse(`"${raw.replace(/\\'/g, "'")}"`); } catch { return undefined; }
39
+ }
40
+
41
+ /**
42
+ * Parses the YAML subset skills use: `key: scalar`, quoted scalars, block scalars (`|`, `>`),
43
+ * multi-line plain scalars, comments, and one level of `key:` + indented `sub: value` (metadata).
44
+ * Anything else (sequences, flow collections, anchors, tags) is reported as unsupported.
45
+ * @returns {{ data: Record<string, unknown>, problems: string[] }}
46
+ */
47
+ export function parseFrontmatter(text) {
48
+ const lines = text.split(/\r?\n/);
49
+ const data = {};
50
+ const problems = [];
51
+ const indent = line => /^ */.exec(line)[0].length;
52
+ let i = 0;
53
+ const scalar = (raw, key, baseIndent) => {
54
+ const value = raw.trim();
55
+ if (!value) {
56
+ // A nested mapping, or an empty value.
57
+ const nested = {};
58
+ let found = false;
59
+ while (i < lines.length && (lines[i].trim() === '' || lines[i].trimStart().startsWith('#') || indent(lines[i]) > baseIndent)) {
60
+ const line = lines[i++];
61
+ if (!line.trim() || line.trimStart().startsWith('#')) continue;
62
+ const match = /^\s+([^:#\s][^:]*?):(?:\s+(.*)|\s*)$/.exec(line);
63
+ if (!match) { problems.push(`${key}: unsupported YAML in '${line.trim()}' (use "key: value" lines)`); continue; }
64
+ found = true;
65
+ nested[match[1].trim()] = scalar(match[2] ?? '', `${key}.${match[1].trim()}`, indent(line));
66
+ }
67
+ return found ? nested : '';
68
+ }
69
+ if (value.startsWith('"')) {
70
+ const end = /^"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$/.exec(value);
71
+ if (!end) { problems.push(`${key}: unterminated or multi-line double-quoted value`); return undefined; }
72
+ const parsed = doubleQuoted(end[1]);
73
+ if (parsed === undefined) problems.push(`${key}: invalid escape in double-quoted value`);
74
+ return parsed;
75
+ }
76
+ if (value.startsWith("'")) {
77
+ const end = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(value);
78
+ if (!end) { problems.push(`${key}: unterminated or multi-line single-quoted value`); return undefined; }
79
+ return end[1].replaceAll("''", "'");
80
+ }
81
+ const block = /^([|>])([+-]?)([1-9]?)([+-]?)\s*(?:#.*)?$/.exec(value);
82
+ if (block?.[3]) problems.push(`${key}: block scalar indentation indicators are not supported; indent the text instead`);
83
+ if (block) {
84
+ const body = [];
85
+ while (i < lines.length && (lines[i].trim() === '' || indent(lines[i]) > baseIndent)) body.push(lines[i++]);
86
+ while (body.length && !body[body.length - 1].trim()) body.pop();
87
+ const width = Math.min(...body.filter(line => line.trim()).map(indent));
88
+ const content = body.map(line => line.slice(Number.isFinite(width) ? width : 0));
89
+ const joined = block[1] === '|' ? content.join('\n') : content.join('\n').replace(/([^\n])\n(?=[^\n])/g, '$1 ');
90
+ return (block[2] || block[4]) === '-' ? joined : `${joined}\n`;
91
+ }
92
+ if (/^[[{&*!%@`]/.test(value) || value.startsWith('- ')) {
93
+ problems.push(`${key}: unsupported YAML value '${value.slice(0, 40)}' (use a plain or quoted string)`);
94
+ return undefined;
95
+ }
96
+ let plain = value.replace(/\s+#.*$/, '');
97
+ // A plain scalar may continue on more-indented lines.
98
+ while (i < lines.length && lines[i].trim() && indent(lines[i]) > baseIndent && !lines[i].trimStart().startsWith('#')) plain += ` ${lines[i++].trim()}`;
99
+ if (/:\s/.test(plain) || plain.endsWith(':')) problems.push(`${key}: plain value contains ": " which YAML rejects; quote the value`);
100
+ return plain;
101
+ };
102
+ while (i < lines.length) {
103
+ const line = lines[i++];
104
+ if (!line.trim() || line.trimStart().startsWith('#')) continue;
105
+ if (indent(line) > 0) { problems.push(`unexpected indentation: '${line.trim().slice(0, 40)}'`); continue; }
106
+ const match = /^([^:#\s][^:]*?):(?:\s+(.*)|\s*)$/.exec(line);
107
+ if (!match) { problems.push(`not a "key: value" line: '${line.trim().slice(0, 40)}'`); continue; }
108
+ const key = match[1].trim();
109
+ if (Object.hasOwn(data, key)) problems.push(`${key}: duplicate key`);
110
+ data[key] = scalar(match[2] ?? '', key, 0);
111
+ }
112
+ return { data, problems };
113
+ }
114
+
115
+ /** The frontmatter block and body of a SKILL.md, or undefined frontmatter when it has none. */
116
+ export function splitSkill(text) {
117
+ const match = /^?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
118
+ return match ? { frontmatter: match[1], body: text.slice(match[0].length) } : { frontmatter: undefined, body: text };
119
+ }
120
+
121
+ /**
122
+ * The relative files a Markdown text points to: link targets and code spans naming a resource
123
+ * directory (`references/x.md`). URLs, anchors and template placeholders are skipped.
124
+ */
125
+ export function skillReferences(markdown) {
126
+ const found = new Set();
127
+ const withoutFences = markdown.replace(/^(```|~~~)[\s\S]*?^\1/gm, '');
128
+ for (const match of withoutFences.matchAll(/\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g)) found.add(match[1]);
129
+ // A code span is a reference only under references/: `scripts/x` or `templates/` in prose often
130
+ // names a directory of the project the skill works on, so those need a link to be checked.
131
+ for (const match of withoutFences.matchAll(/`([^`\s]+)`/g)) {
132
+ if (/^(?:\.\/)?references\/[^*<>{}$]+\.[a-z0-9]+$/i.test(match[1])) found.add(match[1]);
133
+ }
134
+ return [...found].filter(target => !/^[a-z][\w+.-]*:/i.test(target) && !target.startsWith('#') && !target.startsWith('//'))
135
+ .map(target => { const plain = target.split('#')[0]; try { return decodeURI(plain); } catch { return plain; } }).filter(Boolean);
136
+ }
137
+
138
+ const inside = (root, target) => { const relative = path.relative(root, target); return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); };
139
+
140
+ /**
141
+ * Checks frontmatter text against the specification. `directory` is the skill directory's name.
142
+ * @returns {{ data: Record<string, unknown>, findings: Array<{ level: 'error' | 'warning', code: string, message: string }> }}
143
+ */
144
+ export function checkFrontmatter(frontmatter, directory, { strict = false } = {}) {
145
+ const findings = [];
146
+ const format = (code, message) => findings.push({ level: strict ? 'error' : 'warning', code, message });
147
+ const error = (code, message) => findings.push({ level: 'error', code, message });
148
+ const warn = (code, message) => findings.push({ level: 'warning', code, message });
149
+ if (frontmatter === undefined) {
150
+ format('NO_FRONTMATTER', 'SKILL.md has no YAML frontmatter; add "---\\nname: ...\\ndescription: ...\\n---" so agents see what the skill is for');
151
+ return { data: {}, findings };
152
+ }
153
+ const { data, problems } = parseFrontmatter(frontmatter);
154
+ for (const problem of problems) format('YAML', `frontmatter: ${problem}`);
155
+ const { name, description } = data;
156
+ if (name === undefined) format('NAME_MISSING', 'frontmatter has no name');
157
+ else if (typeof name !== 'string' || !specName(name)) format('NAME_FORMAT', `name '${name}' must be 1-${NAME_MAX} lowercase letters, digits and single hyphens, not starting or ending with one`);
158
+ if (typeof name === 'string' && directory !== undefined && name !== directory) format('NAME_DIRECTORY', `name '${name}' differs from its directory '${directory}'; agents find it by the directory name`);
159
+ if (directory !== undefined && !specName(directory)) format('DIRECTORY_NAME', `directory '${directory}' is not a valid skill name; rename it to lowercase letters, digits and hyphens`);
160
+ if (description === undefined || (typeof description === 'string' && !description.trim())) format('DESCRIPTION_MISSING', 'frontmatter has no description: it is all an agent sees before opening the skill');
161
+ else if (typeof description !== 'string') format('DESCRIPTION_FORMAT', 'description must be text');
162
+ else {
163
+ const flat = description.replace(/\s+/g, ' ').trim();
164
+ if (flat.length > DESCRIPTION_MAX) format('DESCRIPTION_LENGTH', `description has ${flat.length} characters; the limit is ${DESCRIPTION_MAX}`);
165
+ else if (flat.length > INDEX_DESCRIPTION_CHARS) warn('DESCRIPTION_CLIPPED', `description has ${flat.length} characters; ALP's skill index shows the first ${INDEX_DESCRIPTION_CHARS}`);
166
+ if (flat.length < 40) warn('DESCRIPTION_SHORT', 'description is under 40 characters; say what the skill does and when to use it');
167
+ if (!TRIGGER_RE.test(flat)) warn('DESCRIPTION_TRIGGER', 'description does not say when to use the skill (for example "Use when ...")');
168
+ if (/[<>]/.test(flat)) format('DESCRIPTION_ANGLE', 'description contains < or >, which some runtimes reject');
169
+ }
170
+ if (data.compatibility !== undefined && (typeof data.compatibility !== 'string' || data.compatibility.length > COMPATIBILITY_MAX)) format('COMPATIBILITY', `compatibility must be text of at most ${COMPATIBILITY_MAX} characters`);
171
+ if (data.license !== undefined && typeof data.license !== 'string') format('LICENSE', 'license must be text');
172
+ if (data['allowed-tools'] !== undefined && typeof data['allowed-tools'] !== 'string') format('ALLOWED_TOOLS', 'allowed-tools must be a space-separated string');
173
+ if (data['allowed-tools'] !== undefined) warn('ALLOWED_TOOLS_ADVISORY', 'allowed-tools is advisory: ALP permissions come from the session mode and permission profiles, never from a skill');
174
+ if (data.metadata !== undefined && (typeof data.metadata !== 'object' || data.metadata === null || Object.values(data.metadata).some(value => typeof value !== 'string'))) format('METADATA', 'metadata must map names to text values');
175
+ for (const key of Object.keys(data)) {
176
+ if (SPEC_KEYS.includes(key)) continue;
177
+ if (RUNTIME_KEYS.includes(key)) format('RUNTIME_KEY', `'${key}' is specific to one runtime; other runtimes ignore it`);
178
+ else format('UNKNOWN_KEY', `unknown frontmatter key '${key}'; the specification allows ${SPEC_KEYS.join(', ')}`);
179
+ }
180
+ return { data, findings };
181
+ }
182
+
183
+ /** Whether a buffer is UTF-8 text without NUL bytes. */
184
+ const isText = buffer => !buffer.includes(0) && Buffer.from(buffer.toString('utf8'), 'utf8').equals(buffer);
185
+
186
+ /**
187
+ * Validates one skill directory.
188
+ * @param {string} directory absolute or relative path of the skill directory
189
+ * @param {{ mode?: 'strict' | 'legacy', shipped?: boolean }} [options] `shipped`: the skill ships in
190
+ * ALP's templates, which bundles carry as UTF-8 text, so every file must be text
191
+ * @returns {Promise<{ name: string, directory: string, mode: 'strict' | 'legacy', ok: boolean, errors: Finding[], warnings: Finding[], files: number }>}
192
+ * @typedef {{ code: string, message: string, file?: string }} Finding
193
+ */
194
+ export async function validateSkill(directory, { mode = 'legacy', shipped = false } = {}) {
195
+ const root = path.resolve(directory);
196
+ const strict = mode === 'strict';
197
+ /** @type {Array<Finding & { level: 'error' | 'warning' }>} */
198
+ const findings = [];
199
+ const add = (level, code, message, file) => findings.push({ level, code, message, ...(file ? { file } : {}) });
200
+ const format = (code, message, file) => add(strict ? 'error' : 'warning', code, message, file);
201
+ const result = () => {
202
+ const errors = findings.filter(f => f.level === 'error').map(({ level, ...f }) => f);
203
+ const warnings = findings.filter(f => f.level === 'warning').map(({ level, ...f }) => f);
204
+ return { name: path.basename(root), directory: root, mode, ok: errors.length === 0, errors, warnings, files };
205
+ };
206
+ let files = 0;
207
+ const info = await lstat(root).catch(() => undefined);
208
+ if (!info) { add('error', 'NOT_FOUND', `no skill directory at ${root}`); return result(); }
209
+ if (info.isSymbolicLink()) add('warning', 'DIRECTORY_LINK', 'the skill directory is a symbolic link; its contents are checked where it points');
210
+ const real = await realpath(root).catch(() => root);
211
+ if (!(await stat(real).then(s => s.isDirectory(), () => false))) { add('error', 'NOT_DIRECTORY', `${root} is not a directory`); return result(); }
212
+
213
+ // Every file under the skill: symlinks must stay inside it; shipped skills must be text.
214
+ const markdown = [];
215
+ let stopped = false;
216
+ const walk = async relative => {
217
+ let entries;
218
+ try { entries = await readdir(path.join(real, relative), { withFileTypes: true }); }
219
+ catch (error) { add('error', 'UNREADABLE', `${relative || '.'} cannot be read: ${error.code ?? error.message}`, relative || undefined); return; }
220
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
221
+ if (stopped) return;
222
+ const rel = path.join(relative, entry.name);
223
+ const full = path.join(real, rel);
224
+ if (++files > MAX_FILES) { stopped = true; add('error', 'TOO_MANY_FILES', `more than ${MAX_FILES} files; a skill should hold instructions and small resources`); return; }
225
+ if (entry.name === 'node_modules' || entry.name === '.git') { add('warning', 'BUNDLED_DEPENDENCIES', `${rel} is bundled; skills must not carry installed dependencies or repositories`, rel); continue; }
226
+ if (entry.isSymbolicLink()) {
227
+ const target = await realpath(full).catch(() => undefined);
228
+ if (target === undefined) add('error', 'BROKEN_SYMLINK', `${rel} is a symbolic link to nothing`, rel);
229
+ else if (!inside(real, target)) add('error', 'UNSAFE_SYMLINK', `${rel} links outside the skill (${target})`, rel);
230
+ else if (shipped) add('error', 'SHIPPED_SYMLINK', `${rel} is a symbolic link; shipped skills hold plain files`, rel);
231
+ continue;
232
+ }
233
+ if (entry.isDirectory()) { await walk(rel); continue; }
234
+ if (!entry.isFile()) { add('error', 'SPECIAL_FILE', `${rel} is not a regular file`, rel); continue; }
235
+ const posix = rel.split(path.sep).join('/');
236
+ if (shipped || posix.endsWith('.md') || posix.startsWith('scripts/')) {
237
+ let buffer;
238
+ try { buffer = await readFile(full); }
239
+ catch (error) { add('error', 'UNREADABLE', `${rel} cannot be read: ${error.code ?? error.message}`, rel); continue; }
240
+ if (shipped && !isText(buffer)) add('error', 'SHIPPED_BINARY', `${rel} is not UTF-8 text; ALP bundles carry shipped skills as text`, rel);
241
+ if (posix.endsWith('.md')) markdown.push([posix, buffer.toString('utf8')]);
242
+ if (posix.startsWith('scripts/') && !shipped && process.platform !== 'win32' && buffer.subarray(0, 2).toString() === '#!' && !((await stat(full)).mode & 0o111)) {
243
+ add('warning', 'SCRIPT_NOT_EXECUTABLE', `${rel} has a #! line but is not executable; run it with its interpreter or chmod +x it`, rel);
244
+ }
245
+ }
246
+ }
247
+ };
248
+ await walk('');
249
+
250
+ const skillFile = markdown.find(([file]) => file === 'SKILL.md');
251
+ if (!skillFile) {
252
+ const other = await readdir(real).then(list => list.find(name => name.toLowerCase() === 'skill.md'), () => undefined);
253
+ add('error', 'SKILL_MD_MISSING', other ? `found ${other}; the file must be named SKILL.md` : 'no SKILL.md');
254
+ return result();
255
+ }
256
+ const { frontmatter, body } = splitSkill(skillFile[1]);
257
+ for (const finding of checkFrontmatter(frontmatter, path.basename(root), { strict }).findings) add(finding.level, finding.code, finding.message, 'SKILL.md');
258
+ if (!body.trim()) format('BODY_EMPTY', 'SKILL.md has no instructions after its frontmatter', 'SKILL.md');
259
+ const lines = body.split('\n').length;
260
+ if (lines > BODY_LINES_RECOMMENDED) add('warning', 'BODY_LONG', `SKILL.md body has ${lines} lines; move detail into references/ (recommended under ${BODY_LINES_RECOMMENDED})`, 'SKILL.md');
261
+
262
+ // References from every Markdown file in the skill, resolved against that file.
263
+ for (const [file, text] of markdown) {
264
+ const content = file === 'SKILL.md' ? body : text;
265
+ for (const target of skillReferences(content)) {
266
+ // A path leaving the skill does not travel with it: an error for new skills, a warning for existing
267
+ // ones (a link to a sibling skill still works where it is). A symlink leaving it is always an error.
268
+ if (path.isAbsolute(target) || /^[a-z]:[\\/]/i.test(target) || target.startsWith('~')) { format('ABSOLUTE_REFERENCE', `${file} names the absolute path ${target}; use a path relative to the skill`, file); continue; }
269
+ const resolved = path.resolve(real, path.dirname(file), target);
270
+ if (!inside(real, resolved)) { format('REFERENCE_OUTSIDE', `${file} points outside the skill: ${target}`, file); continue; }
271
+ const linked = await lstat(resolved).catch(() => undefined);
272
+ if (!linked) { format('BROKEN_REFERENCE', `${file} points to ${target}, which does not exist`, file); continue; }
273
+ if (linked.isSymbolicLink()) {
274
+ const target2 = await realpath(resolved).catch(() => undefined);
275
+ if (!target2 || !inside(real, target2)) add('error', 'REFERENCE_OUTSIDE', `${file} points through a link outside the skill: ${target}`, file);
276
+ }
277
+ }
278
+ }
279
+ return result();
280
+ }
281
+
282
+ /** One line per finding, for a terminal. */
283
+ export function formatValidation(report) {
284
+ const head = `${report.ok ? 'ok ' : 'FAIL'} ${report.name} (${report.mode}) ${report.directory}`;
285
+ const rows = [...report.errors.map(f => ` error ${f.code}: ${f.message}`), ...report.warnings.map(f => ` warning ${f.code}: ${f.message}`)];
286
+ return [head, ...rows].join('\n');
287
+ }
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
  }
package/src/types.d.ts CHANGED
@@ -4,6 +4,8 @@ export type AgentProfilesConfig = {
4
4
  /** "provider:model", "provider:*" for any model of that provider, or the earlier object form. */
5
5
  profiles?: Array<string | AgentModelConfig>;
6
6
  autocompact?: AutoCompact;
7
+ /** The runtime's own commands and skills the "/" list offers besides the agent's ALP skills; none by default (t-efa3). */
8
+ commands?: string[];
7
9
  claude?: AgentModelConfig;
8
10
  codex?: AgentModelConfig;
9
11
  } & AgentModelConfig;
@@ -17,6 +19,7 @@ export interface RawSettings {
17
19
  workflow?: { mode?: 'pho' | 'cafe' | 'smart' | 'supervised'; maxPeers?: number; supervisor?: boolean };
18
20
  delegation?: Record<string, string[]>;
19
21
  runtime?: { provider?: string; model?: string; reasoning?: string };
22
+ compact?: { auto?: boolean; threshold?: number };
20
23
  }
21
24
  export interface RawMcpServer {
22
25
  command?: string;