agjan 0.0.10 → 0.0.12

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 (119) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +105 -0
  4. package/dist/adapters/copilot.js +80 -0
  5. package/dist/auto.js +24 -0
  6. package/dist/baseline.js +66 -0
  7. package/dist/browser.js +46 -0
  8. package/dist/cli.js +164 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +420 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +462 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +72 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/new.js +65 -0
  17. package/dist/commands/pr-summary.js +168 -0
  18. package/dist/commands/progress.js +42 -0
  19. package/dist/commands/report.js +105 -0
  20. package/dist/commands/review.js +146 -0
  21. package/dist/commands/setup.js +393 -0
  22. package/dist/commands/status.js +303 -0
  23. package/dist/commands/ui-test.js +39 -0
  24. package/dist/config.js +110 -0
  25. package/dist/context.js +56 -0
  26. package/dist/copilot-mcp.js +56 -0
  27. package/dist/documents.js +207 -0
  28. package/dist/errors.js +15 -0
  29. package/dist/feature.js +221 -0
  30. package/dist/fix.js +117 -0
  31. package/dist/git.js +88 -0
  32. package/{src/hash.mjs → dist/hash.js} +11 -14
  33. package/dist/hook.js +47 -0
  34. package/dist/json-file.js +26 -0
  35. package/dist/log.js +50 -0
  36. package/dist/managed.js +182 -0
  37. package/dist/mcp-config.js +76 -0
  38. package/dist/mcp.js +142 -0
  39. package/dist/plan.js +40 -0
  40. package/dist/progress-view.js +494 -0
  41. package/dist/progress.js +106 -0
  42. package/{src/review-policy.mjs → dist/review-policy.js} +39 -47
  43. package/dist/review.js +435 -0
  44. package/dist/scope.js +30 -0
  45. package/dist/terminal.js +127 -0
  46. package/dist/test-results.js +101 -0
  47. package/dist/tests-map.js +29 -0
  48. package/dist/types.js +5 -0
  49. package/dist/ui.js +136 -0
  50. package/dist/usage.js +116 -0
  51. package/dist/validate.js +46 -0
  52. package/docs/guide.md +98 -37
  53. package/kit/domains/btp/domain.json +4 -4
  54. package/kit/hooks/guard.mjs +48 -119
  55. package/kit/skills/agjan-build/SKILL.md +14 -8
  56. package/kit/skills/agjan-design/SKILL.md +42 -6
  57. package/kit/skills/agjan-fix/SKILL.md +9 -10
  58. package/kit/skills/agjan-map/SKILL.md +9 -10
  59. package/kit/skills/agjan-spec/SKILL.md +22 -11
  60. package/kit/skills/agjan-verify/SKILL.md +46 -19
  61. package/kit/skills/cap-developer/SKILL.md +10 -2
  62. package/kit/skills/cap-developer/references/handlers.md +11 -9
  63. package/kit/skills/cap-developer/references/project-setup.md +21 -8
  64. package/kit/skills/cap-developer/references/testing.md +38 -14
  65. package/kit/skills/cap-developer/references/typescript.md +143 -0
  66. package/kit/skills/cap-developer/references/validation-security.md +26 -8
  67. package/kit/skills/fiori-developer/SKILL.md +20 -5
  68. package/kit/skills/fiori-developer/references/app-setup.md +91 -16
  69. package/kit/skills/fiori-developer/references/elements.md +19 -5
  70. package/kit/skills/fiori-developer/references/freestyle-ts.md +5 -1
  71. package/kit/skills/fiori-developer/references/testing.md +109 -15
  72. package/kit/templates/agents-block.md +7 -3
  73. package/package.json +11 -3
  74. package/schemas/approvals.schema.json +23 -2
  75. package/schemas/config.schema.json +0 -5
  76. package/schemas/log.schema.json +1 -1
  77. package/src/adapters/claude-code.mjs +0 -121
  78. package/src/adapters/copilot.mjs +0 -89
  79. package/src/baseline.mjs +0 -66
  80. package/src/cli.mjs +0 -155
  81. package/src/commands/branch.mjs +0 -60
  82. package/src/commands/check.mjs +0 -365
  83. package/src/commands/fix.mjs +0 -116
  84. package/src/commands/gates.mjs +0 -264
  85. package/src/commands/lint.mjs +0 -74
  86. package/src/commands/log.mjs +0 -60
  87. package/src/commands/map.mjs +0 -47
  88. package/src/commands/new.mjs +0 -53
  89. package/src/commands/pr-summary.mjs +0 -137
  90. package/src/commands/progress.mjs +0 -40
  91. package/src/commands/report.mjs +0 -115
  92. package/src/commands/review.mjs +0 -76
  93. package/src/commands/setup.mjs +0 -383
  94. package/src/commands/status.mjs +0 -248
  95. package/src/config.mjs +0 -122
  96. package/src/context.mjs +0 -67
  97. package/src/copilot-mcp.mjs +0 -56
  98. package/src/documents.mjs +0 -188
  99. package/src/errors.mjs +0 -16
  100. package/src/feature.mjs +0 -225
  101. package/src/fix.mjs +0 -108
  102. package/src/git.mjs +0 -83
  103. package/src/hook.mjs +0 -48
  104. package/src/json-file.mjs +0 -24
  105. package/src/log.mjs +0 -51
  106. package/src/managed.mjs +0 -178
  107. package/src/mcp-config.mjs +0 -83
  108. package/src/mcp.mjs +0 -147
  109. package/src/plan.mjs +0 -45
  110. package/src/progress-view.mjs +0 -466
  111. package/src/progress.mjs +0 -85
  112. package/src/review.mjs +0 -413
  113. package/src/scope.mjs +0 -30
  114. package/src/terminal.mjs +0 -118
  115. package/src/test-results.mjs +0 -111
  116. package/src/tests-map.mjs +0 -29
  117. package/src/ui.mjs +0 -136
  118. package/src/usage.mjs +0 -118
  119. package/src/validate.mjs +0 -41
@@ -0,0 +1,207 @@
1
+ import { parse as parseYaml } from 'yaml';
2
+ /** Required `##` headings per document (design 8). Keys stay English in every language. */
3
+ export const SPEC_HEADINGS = [
4
+ 'Summary',
5
+ 'Why',
6
+ 'Users and roles',
7
+ 'Scope',
8
+ 'Acceptance criteria',
9
+ 'Non-functional requirements',
10
+ 'Authorization',
11
+ 'Business constraints',
12
+ 'Open technical questions',
13
+ ];
14
+ export const DESIGN_HEADINGS_LIGHT = ['Impact summary', 'Mode rationale', 'Areas and rationale'];
15
+ export const DESIGN_HEADINGS_FULL = [
16
+ ...DESIGN_HEADINGS_LIGHT,
17
+ 'Decisions',
18
+ 'Answers to open technical questions',
19
+ 'Risks and trade-offs',
20
+ ];
21
+ const TASK_ID = /^T[1-9][0-9]*$/;
22
+ /**
23
+ * Splits a leading YAML frontmatter block from the body. Returns `data: null` when there
24
+ * is none, and an `error` string when the YAML is invalid or not a mapping.
25
+ */
26
+ export function splitFrontmatter(text) {
27
+ const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
28
+ if (!match)
29
+ return { data: null, body: text };
30
+ const body = text.slice(match[0].length);
31
+ try {
32
+ const data = parseYaml(match[1]) ?? {};
33
+ if (typeof data !== 'object' || Array.isArray(data))
34
+ return { data: null, body, error: 'frontmatter must be a mapping' };
35
+ return { data, body };
36
+ }
37
+ catch (error) {
38
+ return { data: null, body, error: `invalid frontmatter: ${error.message.split('\n')[0]}` };
39
+ }
40
+ }
41
+ /** Splits the body into lines, skipping fenced code blocks so their content is not parsed. */
42
+ function outsideFences(body) {
43
+ const out = [];
44
+ let fence = null;
45
+ body.split(/\r?\n/).forEach((line, index) => {
46
+ const marker = /^(```|~~~)/.exec(line);
47
+ if (marker) {
48
+ if (fence === null)
49
+ fence = marker[1];
50
+ else if (line.startsWith(fence))
51
+ fence = null;
52
+ return;
53
+ }
54
+ if (fence === null)
55
+ out.push({ line, number: index + 1 });
56
+ });
57
+ return out;
58
+ }
59
+ export function headings(body, level = 2) {
60
+ const prefix = `${'#'.repeat(level)} `;
61
+ return outsideFences(body)
62
+ .filter(({ line }) => line.startsWith(prefix) && !line.startsWith(`${prefix}#`))
63
+ .map(({ line }) => line.slice(prefix.length).trim());
64
+ }
65
+ function missingHeadings(body, required) {
66
+ const present = new Set(headings(body));
67
+ return required.filter((h) => !present.has(h)).map((h) => `missing heading '## ${h}'`);
68
+ }
69
+ /** The lines of one `##` section (without its heading), or null when absent. */
70
+ function section(body, title) {
71
+ const lines = outsideFences(body);
72
+ const start = lines.findIndex(({ line }) => line.trim() === `## ${title}`);
73
+ if (start === -1)
74
+ return null;
75
+ const end = lines.findIndex(({ line }, i) => i > start && /^## /.test(line));
76
+ return lines.slice(start + 1, end === -1 ? undefined : end);
77
+ }
78
+ /**
79
+ * Parses `spec.md`. Returns the authored frontmatter, the acceptance criteria and the
80
+ * list of problems. `key` is the feature key; AC ids must be `<key>-AC<n>`.
81
+ */
82
+ export function parseSpec(text, key) {
83
+ const problems = [];
84
+ const { data, body, error } = splitFrontmatter(text);
85
+ if (error)
86
+ problems.push(error);
87
+ const kind = data?.kind;
88
+ if (kind !== 'business' && kind !== 'technical')
89
+ problems.push("frontmatter 'kind' must be 'business' or 'technical'");
90
+ problems.push(...missingHeadings(body, kind === 'technical' ? [...SPEC_HEADINGS, 'Technical constraints'] : SPEC_HEADINGS));
91
+ const acs = [];
92
+ const lines = section(body, 'Acceptance criteria') ?? [];
93
+ const idPattern = new RegExp(`^${key}-AC[1-9][0-9]*$`);
94
+ let current = null;
95
+ for (const { line, number } of lines) {
96
+ const heading = /^### (.+?)\s*$/.exec(line);
97
+ if (heading) {
98
+ const ac = { id: heading[1], line: number, given: false, when: false, then: false, verification: 'automated' };
99
+ current = ac;
100
+ acs.push(ac);
101
+ if (!idPattern.test(ac.id))
102
+ problems.push(`line ${number}: AC id '${ac.id}' must look like ${key}-AC1`);
103
+ continue;
104
+ }
105
+ if (!current)
106
+ continue;
107
+ const field = /^\s*(Given|When|Then|And|Verification:)\s*(.*)$/.exec(line);
108
+ if (!field)
109
+ continue;
110
+ if (field[1] === 'Given')
111
+ current.given = true;
112
+ if (field[1] === 'When')
113
+ current.when = true;
114
+ if (field[1] === 'Then')
115
+ current.then = true;
116
+ if (field[1] === 'Verification:') {
117
+ const value = field[2].trim();
118
+ if (value === 'automated' || value === 'manual')
119
+ current.verification = value;
120
+ else
121
+ problems.push(`line ${number}: ${current.id} verification must be 'automated' or 'manual'`);
122
+ }
123
+ }
124
+ if (acs.length === 0)
125
+ problems.push("no acceptance criteria ('### <KEY>-AC<n>' under '## Acceptance criteria')");
126
+ const seen = new Set();
127
+ for (const ac of acs) {
128
+ if (seen.has(ac.id))
129
+ problems.push(`duplicate AC id ${ac.id}`);
130
+ seen.add(ac.id);
131
+ for (const part of ['given', 'when', 'then']) {
132
+ if (!ac[part])
133
+ problems.push(`${ac.id} has no '${part[0].toUpperCase()}${part.slice(1)}' line`);
134
+ }
135
+ }
136
+ return { kind, acs, problems };
137
+ }
138
+ /** Parses `design.md`: mode, areas and the required headings for the mode. */
139
+ export function parseDesign(text) {
140
+ const problems = [];
141
+ const { data, body, error } = splitFrontmatter(text);
142
+ if (error)
143
+ problems.push(error);
144
+ const mode = data?.mode;
145
+ if (mode !== 'light' && mode !== 'full')
146
+ problems.push("frontmatter 'mode' must be 'light' or 'full'");
147
+ const areas = data?.areas;
148
+ if (!Array.isArray(areas) || areas.length === 0 || !areas.every((a) => typeof a === 'string')) {
149
+ problems.push("frontmatter 'areas' must be a non-empty list of area ids");
150
+ }
151
+ problems.push(...missingHeadings(body, mode === 'full' ? DESIGN_HEADINGS_FULL : DESIGN_HEADINGS_LIGHT));
152
+ return { mode, areas: Array.isArray(areas) ? areas : [], problems };
153
+ }
154
+ function isRepoPath(value) {
155
+ return typeof value === 'string' && value.length > 0 && !value.includes('\\') &&
156
+ !value.startsWith('/') && !/^[A-Za-z]:/.test(value) && !value.split('/').includes('..');
157
+ }
158
+ /** Parses `tasks.md`: exactly one fenced YAML block with a `tasks` list (design 8.3). */
159
+ export function parseTasks(text) {
160
+ const problems = [];
161
+ const blocks = [...text.matchAll(/^```ya?ml[ \t]*\r?\n([\s\S]*?)^```[ \t]*$/gm)];
162
+ if (blocks.length !== 1) {
163
+ return { tasks: [], problems: [`tasks.md must contain exactly one fenced yaml block (found ${blocks.length})`] };
164
+ }
165
+ let data;
166
+ try {
167
+ data = parseYaml(blocks[0][1]);
168
+ }
169
+ catch (error) {
170
+ return { tasks: [], problems: [`invalid tasks yaml: ${error.message.split('\n')[0]}`] };
171
+ }
172
+ if (!Array.isArray(data?.tasks) || data.tasks.length === 0) {
173
+ return { tasks: [], problems: ["the yaml block must have a non-empty 'tasks' list"] };
174
+ }
175
+ const tasks = [];
176
+ const ids = new Set();
177
+ data.tasks.forEach((task, index) => {
178
+ const where = typeof task?.id === 'string' ? task.id : `task #${index + 1}`;
179
+ if (typeof task !== 'object' || task === null) {
180
+ problems.push(`${where}: must be a mapping`);
181
+ return;
182
+ }
183
+ if (!TASK_ID.test(task.id ?? ''))
184
+ problems.push(`${where}: id must look like T1`);
185
+ else if (ids.has(task.id))
186
+ problems.push(`${where}: duplicate task id`);
187
+ ids.add(task.id);
188
+ if (typeof task.area !== 'string')
189
+ problems.push(`${where}: 'area' is required`);
190
+ if (typeof task.title !== 'string' || task.title.trim() === '')
191
+ problems.push(`${where}: 'title' is required`);
192
+ const covers = Array.isArray(task.covers) ? task.covers : [];
193
+ if (covers.length === 0)
194
+ problems.push(`${where}: 'covers' must list at least one AC id`);
195
+ const paths = Array.isArray(task.paths) ? task.paths : [];
196
+ if (paths.length === 0)
197
+ problems.push(`${where}: 'paths' must list at least one path or glob`);
198
+ for (const p of paths) {
199
+ if (!isRepoPath(p))
200
+ problems.push(`${where}: path '${p}' must be relative, POSIX, without '..'`);
201
+ }
202
+ if (task.verify !== undefined && typeof task.verify !== 'string')
203
+ problems.push(`${where}: 'verify' must be a string`);
204
+ tasks.push({ id: task.id, area: task.area, title: task.title, covers, paths, verify: task.verify });
205
+ });
206
+ return { tasks, problems };
207
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,15 @@
1
+ /** An expected failure: printed without a stack trace, with its own exit code. */
2
+ export class AgjanError extends Error {
3
+ constructor(message, { exitCode = 1 } = {}) {
4
+ super(message);
5
+ this.name = 'AgjanError';
6
+ this.exitCode = exitCode;
7
+ }
8
+ }
9
+ /** Wrong command line: exit code 2. */
10
+ export class UsageError extends AgjanError {
11
+ constructor(message) {
12
+ super(message, { exitCode: 2 });
13
+ this.name = 'UsageError';
14
+ }
15
+ }
@@ -0,0 +1,221 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { hashText, hashParts } from './hash.js';
4
+ import { readJson } from './json-file.js';
5
+ import { parseSpec, parseDesign, parseTasks } from './documents.js';
6
+ import { changedFiles, resolveBase } from './git.js';
7
+ import { AgjanError, UsageError } from './errors.js';
8
+ export const FEATURES_DIR = 'docs/agjan';
9
+ export const APPROVALS_FILE = 'approvals.json';
10
+ export const REVIEWS_FILE = 'reviews.json';
11
+ /**
12
+ * Record folders under docs/agjan (decision 57). A unit's id is its path below
13
+ * docs/agjan: a feature `order-filter`, a fix `fixes/2026-10-17-order-label`, a map run
14
+ * `maps/2026-10-17`. All have approvals.json (key, accepted findings), reviews.json and
15
+ * log.jsonl; only features have spec, design and tasks.
16
+ */
17
+ export const CONTAINERS = { fixes: 'fix', maps: 'map' };
18
+ const RESERVED = new Set(Object.keys(CONTAINERS));
19
+ export const SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/;
20
+ export const KEY = /^[A-Z][A-Z0-9]{1,5}$/;
21
+ /** Review steps whose passing record allows each gate (design 7.3). */
22
+ const GATE_STEPS = {
23
+ spec: ['spec', 'design:light'],
24
+ design: ['design', 'design:light'],
25
+ };
26
+ export function featureDir(root, slug) {
27
+ return join(root, FEATURES_DIR, slug);
28
+ }
29
+ function unitFolders(dir) {
30
+ if (!existsSync(dir))
31
+ return [];
32
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && existsSync(join(dir, e.name, APPROVALS_FILE)));
33
+ }
34
+ /** All unit ids in the repository: features, then fixes and map runs. */
35
+ export function listFeatures(root) {
36
+ const dir = join(root, FEATURES_DIR);
37
+ const features = unitFolders(dir).filter((e) => !RESERVED.has(e.name)).map((e) => e.name).sort();
38
+ const others = Object.keys(CONTAINERS).flatMap((c) => unitFolders(join(dir, c)).map((e) => `${c}/${e.name}`).sort());
39
+ return [...features, ...others];
40
+ }
41
+ /** The unit id a repository path belongs to, or null (docs/agjan/project.md, ...). */
42
+ export function unitOf(file) {
43
+ const prefix = `${FEATURES_DIR}/`;
44
+ if (!file.startsWith(prefix))
45
+ return null;
46
+ const parts = file.slice(prefix.length).split('/');
47
+ if (parts.length < 2)
48
+ return null;
49
+ if (RESERVED.has(parts[0]))
50
+ return parts.length >= 3 ? `${parts[0]}/${parts[1]}` : null;
51
+ return parts[0];
52
+ }
53
+ /** Ids of the units whose folder changed relative to the merge-base (design 6.8). */
54
+ export function changedFeatures(root, config, options = {}) {
55
+ const ids = new Set();
56
+ for (const file of changedFiles(root, resolveBase(root, config.git?.base), options)) {
57
+ const id = unitOf(file);
58
+ if (id && existsSync(join(root, FEATURES_DIR, id, APPROVALS_FILE)))
59
+ ids.add(id);
60
+ }
61
+ return [...ids].sort();
62
+ }
63
+ /** The one feature a command acts on: the explicit one, or the single changed one. */
64
+ export function selectFeature(root, config, explicit) {
65
+ if (explicit) {
66
+ if (!existsSync(join(featureDir(root, explicit), APPROVALS_FILE)))
67
+ throw new AgjanError(`no feature '${explicit}' in ${FEATURES_DIR}`);
68
+ return explicit;
69
+ }
70
+ const changed = changedFeatures(root, config);
71
+ if (changed.length === 1)
72
+ return changed[0];
73
+ if (changed.length === 0)
74
+ throw new UsageError('no changed feature on this branch; pass --feature <slug>');
75
+ throw new UsageError(`several features changed (${changed.join(', ')}); pass --feature <slug>`);
76
+ }
77
+ function readDoc(dir, name) {
78
+ const file = join(dir, name);
79
+ if (!existsSync(file))
80
+ return null;
81
+ const text = readFileSync(file, 'utf8');
82
+ return { file, text, hash: hashText(text) };
83
+ }
84
+ export function emptyApprovals(slug, key, kit, now, kind = 'feature') {
85
+ return {
86
+ schema: 1,
87
+ feature: { slug, key, kit, created_at_utc: now, ...(kind === 'feature' ? {} : { kind }) },
88
+ approvals: {},
89
+ amendments: [],
90
+ accepted: [],
91
+ rejections: [],
92
+ };
93
+ }
94
+ function validateApprovals(data, slug) {
95
+ if (data?.schema !== 1 || typeof data.feature !== 'object' || data.feature === null) {
96
+ throw new AgjanError(`${FEATURES_DIR}/${slug}/${APPROVALS_FILE}: unsupported or damaged content`);
97
+ }
98
+ if (!KEY.test(data.feature.key ?? ''))
99
+ throw new AgjanError(`${FEATURES_DIR}/${slug}/${APPROVALS_FILE}: invalid feature key`);
100
+ if (data.feature.kind !== undefined && !['fix', 'map'].includes(data.feature.kind)) {
101
+ throw new AgjanError(`${FEATURES_DIR}/${slug}/${APPROVALS_FILE}: unknown kind '${data.feature.kind}'`);
102
+ }
103
+ for (const list of ['amendments', 'accepted', 'rejections']) {
104
+ if (!Array.isArray(data[list]))
105
+ throw new AgjanError(`${FEATURES_DIR}/${slug}/${APPROVALS_FILE}: '${list}' must be a list`);
106
+ }
107
+ if (typeof data.approvals !== 'object' || data.approvals === null) {
108
+ throw new AgjanError(`${FEATURES_DIR}/${slug}/${APPROVALS_FILE}: 'approvals' must be an object`);
109
+ }
110
+ return data;
111
+ }
112
+ /**
113
+ * Whether a review still blocks: its verdict is blocked and the human has not accepted
114
+ * every blocker it raised (design 7.4: no open blocker, unless accepted). An accepted
115
+ * blocker leaves the correction loop, so the step needs no further round for it.
116
+ */
117
+ export function stillBlocked(feature, record) {
118
+ if (record?.verdict !== 'blocked')
119
+ return false;
120
+ const status = new Map(feature.findings.map((f) => [f.id, f.status]));
121
+ return (record.findings ?? []).some((f) => f.severity === 'blocker' && status.get(f.id) !== 'accepted');
122
+ }
123
+ /**
124
+ * Findings with their current status. A finding is resolved when a later record lists
125
+ * it in `resolves`, accepted when the human accepted it, and open otherwise.
126
+ */
127
+ export function findingStatus(reviews, approvals) {
128
+ const accepted = new Set(approvals.accepted.map((a) => a.finding));
129
+ const resolved = new Set(reviews.records.flatMap((r) => r.resolves ?? []));
130
+ return reviews.records.flatMap((record) => (record.findings ?? []).map((f) => ({
131
+ ...f,
132
+ step: record.step,
133
+ record: record.id,
134
+ status: accepted.has(f.id) ? 'accepted' : resolved.has(f.id) ? 'resolved' : 'open',
135
+ })));
136
+ }
137
+ /** The latest review record for any of the given steps, or null. */
138
+ export function latestReview(reviews, steps) {
139
+ const matching = reviews.records.filter((r) => steps.includes(r.step));
140
+ return matching.length === 0 ? null : matching[matching.length - 1];
141
+ }
142
+ function docState(doc, approval, hash, extraOk = true) {
143
+ if (!doc)
144
+ return 'missing';
145
+ if (!approval)
146
+ return 'draft';
147
+ return approval.hash === hash && extraOk ? 'approved' : 'stale';
148
+ }
149
+ /** Loads a feature and derives its state; nothing derived is stored (design 8.4). */
150
+ export function loadFeature(root, slug) {
151
+ const dir = featureDir(root, slug);
152
+ const approvals = validateApprovals(readJson(join(dir, APPROVALS_FILE)), slug);
153
+ const reviews = readJson(join(dir, REVIEWS_FILE)) ?? { schema: 1, records: [] };
154
+ if (!Array.isArray(reviews.records))
155
+ throw new AgjanError(`${FEATURES_DIR}/${slug}/${REVIEWS_FILE}: 'records' must be a list`);
156
+ const key = approvals.feature.key;
157
+ // Fixes and map runs have no documents of their own; their stage is their kind.
158
+ const kind = approvals.feature.kind ?? 'feature';
159
+ const isFeature = kind === 'feature';
160
+ const read = (name, parse) => {
161
+ const doc = isFeature ? readDoc(dir, name) : null;
162
+ return doc ? { ...doc, parsed: parse(doc.text) } : null;
163
+ };
164
+ const spec = read('spec.md', (text) => parseSpec(text, key));
165
+ const design = read('design.md', parseDesign);
166
+ const tasks = read('tasks.md', parseTasks);
167
+ const designHash = design && tasks ? hashParts([['design.md', design.text], ['tasks.md', tasks.text]]) : null;
168
+ const specApproval = approvals.approvals.spec;
169
+ const designApproval = approvals.approvals.design;
170
+ const specState = docState(spec, specApproval, spec?.hash);
171
+ const designState = design && tasks
172
+ ? docState(design, designApproval, designHash, designApproval?.spec_hash === spec?.hash && specState === 'approved')
173
+ : 'missing';
174
+ const stage = !isFeature ? kind : specState !== 'approved' ? 'spec' : designState !== 'approved' ? 'design' : 'build';
175
+ const amendments = approvals.amendments.map((a) => ({
176
+ ...a,
177
+ status: (!a.approved_at_utc ? 'pending' : a.design_hash === designApproval?.hash ? 'approved' : 'lapsed'),
178
+ }));
179
+ return {
180
+ slug,
181
+ key,
182
+ kind,
183
+ dir,
184
+ approvals,
185
+ reviews,
186
+ spec,
187
+ design,
188
+ tasks,
189
+ designHash,
190
+ state: { spec: specState, design: designState },
191
+ stage,
192
+ amendments,
193
+ findings: findingStatus(reviews, approvals),
194
+ };
195
+ }
196
+ /**
197
+ * Whether a gate has a passing, fresh review: the latest record for the gate's steps
198
+ * reviewed exactly the current documents and is not blocked (design 7.4).
199
+ */
200
+ export function gateReview(feature, gate) {
201
+ const steps = GATE_STEPS[gate];
202
+ const record = latestReview(feature.reviews, steps);
203
+ const problems = [];
204
+ if (!record) {
205
+ problems.push(`no ${steps.join(' or ')} review recorded`);
206
+ }
207
+ else {
208
+ const docs = record.documents ?? {};
209
+ if (docs.spec !== feature.spec?.hash)
210
+ problems.push(`the latest ${record.step} review (${record.id}) did not review the current spec.md`);
211
+ if (gate === 'design' && docs.design !== feature.designHash) {
212
+ problems.push(`the latest ${record.step} review (${record.id}) did not review the current design.md and tasks.md`);
213
+ }
214
+ if (stillBlocked(feature, record))
215
+ problems.push(`the latest ${record.step} review (${record.id}) is blocked`);
216
+ }
217
+ const blockers = feature.findings.filter((f) => f.status === 'open' && f.severity === 'blocker' && steps.includes(f.step));
218
+ for (const f of blockers)
219
+ problems.push(`open blocker ${f.id}: ${f.issue}`);
220
+ return { record, problems };
221
+ }
package/dist/fix.js ADDED
@@ -0,0 +1,117 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { git, mergeBase, resolveBase } from './git.js';
4
+ import { FEATURES_DIR, latestReview, stillBlocked } from './feature.js';
5
+ import { treeHash } from './review.js';
6
+ import { matcher } from './scope.js';
7
+ export const FIX_FILE = 'fix.json';
8
+ export const FIX_MD = 'fix.md';
9
+ export const PROJECT_MD = `${FEATURES_DIR}/project.md`;
10
+ /**
11
+ * Paths named in the baseline's "Do-not-touch list": every `code span` in its bullets
12
+ * (design 8.6; writers often list several paths in one bullet). They are protected for
13
+ * fixes like `fix.protected`.
14
+ */
15
+ export function doNotTouch(root) {
16
+ const file = join(root, PROJECT_MD);
17
+ if (!existsSync(file))
18
+ return [];
19
+ const lines = readFileSync(file, 'utf8').split(/\r?\n/);
20
+ const start = lines.findIndex((l) => l.trim() === '## Do-not-touch list');
21
+ if (start === -1)
22
+ return [];
23
+ const out = [];
24
+ for (const line of lines.slice(start + 1)) {
25
+ if (/^## /.test(line))
26
+ break;
27
+ if (!/^\s*[-*]\s/.test(line))
28
+ continue;
29
+ for (const match of line.matchAll(/`([^`]+)`/g))
30
+ out.push(match[1]);
31
+ }
32
+ return out;
33
+ }
34
+ function lineCount(root, file) {
35
+ try {
36
+ const text = readFileSync(join(root, file), 'utf8');
37
+ return text.length === 0 ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
38
+ }
39
+ catch {
40
+ return 0;
41
+ }
42
+ }
43
+ /**
44
+ * The fast-path rules (design 6.7) on the change relative to the merge-base: changed
45
+ * lines per file and in total within limits (ignored paths not counted), new files
46
+ * only under the configured test paths, and no protected or risk path touched.
47
+ */
48
+ export function fixRules(root, config) {
49
+ const from = mergeBase(root, resolveBase(root, config.git?.base)) ?? 'HEAD';
50
+ const fix = config.fix;
51
+ const ignored = matcher(fix.ignored ?? []);
52
+ const own = (f) => f.startsWith(`${FEATURES_DIR}/`) || f.startsWith('.agjan/');
53
+ const newAllowed = matcher(fix.new_file_paths ?? Object.values(config.tests ?? {}).flat());
54
+ const protectedPaths = [...(fix.protected ?? []), ...(config.risk_paths ?? []), ...doNotTouch(root)];
55
+ const isProtected = matcher(protectedPaths);
56
+ const added = new Set();
57
+ for (const line of (git(root, ['diff', '--name-status', '--no-renames', from], { allowFail: true }) ?? '').split('\n')) {
58
+ const [status, file] = line.split('\t');
59
+ if (status === 'A')
60
+ added.add(file);
61
+ }
62
+ const files = [];
63
+ for (const line of (git(root, ['diff', '--numstat', '--no-renames', from], { allowFail: true }) ?? '').split('\n').filter(Boolean)) {
64
+ const [a, d, file] = line.split('\t');
65
+ if (own(file))
66
+ continue;
67
+ // Binary files show '-': they count as one changed line each way, never as zero.
68
+ files.push({ path: file, added: a === '-' ? 1 : Number(a), deleted: d === '-' ? 1 : Number(d), isNew: added.has(file) });
69
+ }
70
+ for (const file of git(root, ['ls-files', '--others', '--exclude-standard']).split('\n').filter(Boolean)) {
71
+ if (own(file))
72
+ continue;
73
+ files.push({ path: file, added: lineCount(root, file), deleted: 0, isNew: true });
74
+ }
75
+ files.sort((x, y) => x.path.localeCompare(y.path));
76
+ const problems = [];
77
+ const counted = files.filter((f) => !ignored(f.path));
78
+ const total = counted.reduce((n, f) => n + f.added + f.deleted, 0);
79
+ if (files.length === 0)
80
+ problems.push('nothing changed');
81
+ // Ignored paths (lockfiles, generated output) are outside every rule, not only the count.
82
+ for (const f of counted) {
83
+ if (f.isNew && !newAllowed(f.path))
84
+ problems.push(`${f.path} is a new file; a fix may only add files under the test paths`);
85
+ if (isProtected(f.path))
86
+ problems.push(`${f.path} is protected or a risk path; this needs /agjan-spec`);
87
+ }
88
+ for (const f of counted) {
89
+ const size = f.added + f.deleted;
90
+ if (size > fix.max_per_file)
91
+ problems.push(`${f.path}: ${size} changed lines (limit per file ${fix.max_per_file})`);
92
+ }
93
+ if (total > fix.max_total)
94
+ problems.push(`${total} changed lines in total (limit ${fix.max_total})`);
95
+ return {
96
+ files,
97
+ ignored: files.filter((f) => ignored(f.path)).map((f) => f.path),
98
+ total,
99
+ limits: { max_total: fix.max_total, max_per_file: fix.max_per_file },
100
+ problems,
101
+ };
102
+ }
103
+ /**
104
+ * The latest review of a fix or map run, if it passed and saw exactly the current
105
+ * change; otherwise the reason why not.
106
+ */
107
+ export function freshReview(root, config, unit, step) {
108
+ const record = latestReview(unit.reviews, [step]);
109
+ if (!record)
110
+ return { problem: `no ${step} review recorded` };
111
+ if (stillBlocked(unit, record))
112
+ return { record, problem: `the latest ${step} review ${record.id} is blocked` };
113
+ if (record.tree_hash !== treeHash(root, config, unit.slug)) {
114
+ return { record, problem: `the latest ${step} review ${record.id} is stale: files changed after it` };
115
+ }
116
+ return { record };
117
+ }
package/dist/git.js ADDED
@@ -0,0 +1,88 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { AgjanError } from './errors.js';
3
+ export function git(cwd, args, { allowFail = false } = {}) {
4
+ try {
5
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
6
+ }
7
+ catch (error) {
8
+ if (allowFail)
9
+ return null;
10
+ const failure = error;
11
+ const detail = failure.stderr?.toString().trim() || failure.message;
12
+ throw new AgjanError(`git ${args.join(' ')} failed: ${detail}`);
13
+ }
14
+ }
15
+ export function repoRoot(cwd) {
16
+ const out = git(cwd, ['rev-parse', '--show-toplevel'], { allowFail: true });
17
+ if (out === null)
18
+ throw new AgjanError('not inside a git repository');
19
+ return out.trim();
20
+ }
21
+ export function userEmail(root) {
22
+ return git(root, ['config', 'user.email'], { allowFail: true })?.trim() || 'unknown';
23
+ }
24
+ /**
25
+ * The base branch to compare against: the configured one, else the remote's default
26
+ * branch, else a local main or master.
27
+ */
28
+ export function resolveBase(root, configured) {
29
+ if (configured)
30
+ return configured;
31
+ const remoteHead = git(root, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], { allowFail: true });
32
+ if (remoteHead)
33
+ return remoteHead.trim();
34
+ for (const name of ['main', 'master']) {
35
+ if (git(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${name}`], { allowFail: true }))
36
+ return name;
37
+ }
38
+ return null;
39
+ }
40
+ /**
41
+ * The checked-out branch: the local branch name, or in a pull request job (detached HEAD)
42
+ * the PR's head branch from the CI environment. Null when there is none.
43
+ */
44
+ export function currentBranch(root, env = process.env) {
45
+ const name = git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD'], { allowFail: true })?.trim();
46
+ return name || env.GITHUB_HEAD_REF || env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME || null;
47
+ }
48
+ /** The merge-base commit with the base branch, or null when there is none yet. */
49
+ export function mergeBase(root, base) {
50
+ if (!base)
51
+ return null;
52
+ return git(root, ['merge-base', 'HEAD', base], { allowFail: true })?.trim() || null;
53
+ }
54
+ function lines(out) {
55
+ return out ? out.split('\n').filter(Boolean) : [];
56
+ }
57
+ /**
58
+ * Files the operating system writes on its own (macOS Finder, Windows Explorer). They are
59
+ * never part of a change: neither in scope checks nor in a review's working-tree hash,
60
+ * even when someone committed them.
61
+ */
62
+ const OS_FILES = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini']);
63
+ const osFile = (path) => OS_FILES.has(path.slice(path.lastIndexOf('/') + 1));
64
+ /**
65
+ * Files changed relative to the merge-base: committed, staged, unstaged and untracked.
66
+ * With `staged`, only the files in the index. Paths are POSIX (git always uses '/').
67
+ */
68
+ export function changedFiles(root, base, { staged = false } = {}) {
69
+ if (staged)
70
+ return lines(git(root, ['diff', '--cached', '--name-only', '--no-renames'])).filter((f) => !osFile(f));
71
+ const from = mergeBase(root, base);
72
+ const files = new Set();
73
+ if (from) {
74
+ for (const f of lines(git(root, ['diff', '--name-only', '--no-renames', from])))
75
+ files.add(f);
76
+ }
77
+ else if (git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })) {
78
+ for (const f of lines(git(root, ['diff', '--name-only', '--no-renames', 'HEAD'])))
79
+ files.add(f);
80
+ }
81
+ else {
82
+ for (const f of lines(git(root, ['diff', '--cached', '--name-only', '--no-renames'])))
83
+ files.add(f);
84
+ }
85
+ for (const f of lines(git(root, ['ls-files', '--others', '--exclude-standard'])))
86
+ files.add(f);
87
+ return [...files].filter((f) => !osFile(f)).sort();
88
+ }