agjan 0.0.11 → 0.0.13

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 (114) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +136 -0
  4. package/dist/adapters/copilot.js +110 -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 +170 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +424 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +475 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +74 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/models.js +90 -0
  17. package/dist/commands/new.js +65 -0
  18. package/dist/commands/pr-summary.js +176 -0
  19. package/dist/commands/progress.js +42 -0
  20. package/dist/commands/report.js +105 -0
  21. package/dist/commands/review.js +149 -0
  22. package/dist/commands/setup.js +393 -0
  23. package/dist/commands/status.js +323 -0
  24. package/dist/commands/ui-test.js +39 -0
  25. package/dist/config.js +114 -0
  26. package/dist/context.js +56 -0
  27. package/dist/copilot-mcp.js +56 -0
  28. package/dist/documents.js +207 -0
  29. package/dist/errors.js +15 -0
  30. package/dist/feature.js +221 -0
  31. package/dist/fix.js +117 -0
  32. package/dist/git.js +88 -0
  33. package/{src/hash.mjs → dist/hash.js} +11 -14
  34. package/dist/hook.js +47 -0
  35. package/dist/json-file.js +26 -0
  36. package/dist/log.js +50 -0
  37. package/dist/managed.js +182 -0
  38. package/dist/mcp-config.js +76 -0
  39. package/dist/mcp.js +187 -0
  40. package/dist/plan.js +40 -0
  41. package/dist/progress-view.js +494 -0
  42. package/dist/progress.js +106 -0
  43. package/dist/qa.js +77 -0
  44. package/dist/review-policy.js +84 -0
  45. package/dist/review.js +534 -0
  46. package/dist/scope.js +34 -0
  47. package/dist/terminal.js +127 -0
  48. package/dist/test-results.js +101 -0
  49. package/dist/tests-map.js +29 -0
  50. package/dist/types.js +5 -0
  51. package/dist/ui.js +136 -0
  52. package/dist/usage.js +116 -0
  53. package/dist/validate.js +46 -0
  54. package/docs/guide.md +80 -40
  55. package/kit/hooks/guard.mjs +48 -119
  56. package/kit/skills/agjan-build/SKILL.md +6 -2
  57. package/kit/skills/agjan-design/SKILL.md +9 -2
  58. package/kit/skills/agjan-fix/SKILL.md +8 -16
  59. package/kit/skills/agjan-map/SKILL.md +8 -16
  60. package/kit/skills/agjan-spec/SKILL.md +24 -17
  61. package/kit/skills/agjan-verify/SKILL.md +50 -16
  62. package/kit/skills/qa-tester/SKILL.md +74 -0
  63. package/kit/templates/agents-block.md +3 -3
  64. package/package.json +11 -3
  65. package/schemas/approvals.schema.json +23 -2
  66. package/schemas/config.schema.json +3 -7
  67. package/schemas/log.schema.json +1 -1
  68. package/schemas/reviews.schema.json +3 -1
  69. package/src/adapters/claude-code.mjs +0 -121
  70. package/src/adapters/copilot.mjs +0 -89
  71. package/src/baseline.mjs +0 -66
  72. package/src/browser.mjs +0 -49
  73. package/src/cli.mjs +0 -165
  74. package/src/commands/branch.mjs +0 -95
  75. package/src/commands/check.mjs +0 -376
  76. package/src/commands/fix.mjs +0 -116
  77. package/src/commands/gates.mjs +0 -267
  78. package/src/commands/lint.mjs +0 -74
  79. package/src/commands/log.mjs +0 -60
  80. package/src/commands/map.mjs +0 -47
  81. package/src/commands/new.mjs +0 -53
  82. package/src/commands/pr-summary.mjs +0 -137
  83. package/src/commands/progress.mjs +0 -40
  84. package/src/commands/report.mjs +0 -115
  85. package/src/commands/review.mjs +0 -141
  86. package/src/commands/setup.mjs +0 -393
  87. package/src/commands/status.mjs +0 -250
  88. package/src/commands/ui-test.mjs +0 -38
  89. package/src/config.mjs +0 -122
  90. package/src/context.mjs +0 -67
  91. package/src/copilot-mcp.mjs +0 -56
  92. package/src/documents.mjs +0 -188
  93. package/src/errors.mjs +0 -16
  94. package/src/feature.mjs +0 -225
  95. package/src/fix.mjs +0 -108
  96. package/src/git.mjs +0 -83
  97. package/src/hook.mjs +0 -48
  98. package/src/json-file.mjs +0 -24
  99. package/src/log.mjs +0 -51
  100. package/src/managed.mjs +0 -178
  101. package/src/mcp-config.mjs +0 -83
  102. package/src/mcp.mjs +0 -147
  103. package/src/plan.mjs +0 -45
  104. package/src/progress-view.mjs +0 -466
  105. package/src/progress.mjs +0 -85
  106. package/src/review-policy.mjs +0 -91
  107. package/src/review.mjs +0 -416
  108. package/src/scope.mjs +0 -30
  109. package/src/terminal.mjs +0 -118
  110. package/src/test-results.mjs +0 -111
  111. package/src/tests-map.mjs +0 -29
  112. package/src/ui.mjs +0 -136
  113. package/src/usage.mjs +0 -118
  114. package/src/validate.mjs +0 -41
@@ -1,38 +0,0 @@
1
- import { spawnSync } from 'node:child_process';
2
- import { parseArgs } from 'node:util';
3
- import { UsageError } from '../errors.mjs';
4
- import { UI_SCRIPT, hasUiTests, probeBrowser } from '../browser.mjs';
5
-
6
- /**
7
- * agjan ui-test [--require]: runs the project's UI tests (`npm run test:ui`, Playwright)
8
- * when Chromium can start here. Where it cannot, it says why and how to enable them, and
9
- * exits 0: UI tests are optional (design decision 75). --require makes a skip exit 1
10
- * (for a CI job that installs the browser). Exit code 1 when the tests fail.
11
- */
12
- export function run(ctx, argv) {
13
- const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { require: { type: 'boolean' } } });
14
- if (positionals.length) throw new UsageError('usage: agjan ui-test [--require]');
15
- const s = ctx.style;
16
- const root = ctx.root;
17
- if (!hasUiTests(root)) {
18
- ctx.out(s.gray(`no UI tests: package.json has no ${UI_SCRIPT} script (the fiori-developer skill sets them up)`));
19
- return values.require ? 1 : 0;
20
- }
21
- const browser = probeBrowser(root);
22
- if (!browser.ready) {
23
- ctx.out(`${s.bold('ui tests')} ${s.yellow('skipped')}: ${browser.reason}`);
24
- ctx.out(` enable: ${browser.enable}`);
25
- ctx.out(' The UI ACs were not tested in a browser: name them to the user, who tries them by hand.');
26
- return values.require ? 1 : 0;
27
- }
28
- ctx.out(`${s.bold('ui tests')}: ${s.gray(`npm run ${UI_SCRIPT}`)}`);
29
- const result = spawnSync(`npm run ${UI_SCRIPT}`, { cwd: root, shell: true, encoding: 'utf8', timeout: 1_800_000, maxBuffer: 64 * 1024 * 1024 });
30
- const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim();
31
- if (output) ctx.out(output);
32
- if (result.status === 0) {
33
- ctx.out(` ${s.green('ok')}`);
34
- return 0;
35
- }
36
- ctx.out(` ${s.red(result.status === null ? 'could not run (stopped)' : `failed (exit code ${result.status})`)}`);
37
- return 1;
38
- }
package/src/config.mjs DELETED
@@ -1,122 +0,0 @@
1
- import { join } from 'node:path';
2
- import { readJson } from './json-file.mjs';
3
- import { AgjanError } from './errors.mjs';
4
-
5
- export const CONFIG_FILE = 'agjan.config.json';
6
-
7
- const KIT_DIR = new URL('../kit/', import.meta.url);
8
-
9
- /**
10
- * The commands `agjan init` offers for `agent.allow`: agjan itself (approve, accept and
11
- * reject stay denied by the guard), the tests, and the git commands of the workflow.
12
- */
13
- export const RECOMMENDED_ALLOW = ['npx agjan', 'npm test', 'git status', 'git diff', 'git log', 'git add', 'git commit'];
14
-
15
- /**
16
- * Reviewer models (`models.<host>.<tier>`). "session" means the reviewer agent runs on the
17
- * model of the session that starts it: no model is written into the agent file. `init`
18
- * writes this default visibly for every host, so users notice it and can change it.
19
- */
20
- export const SESSION_MODEL = 'session';
21
- export const MODEL_TIERS = ['balanced', 'deep'];
22
-
23
- /** The model to write into an agent file, or undefined for the session's model. */
24
- export function agentModel(config, host, tier) {
25
- const value = config.models?.[host]?.[tier] ?? config.models?.[host]?.balanced;
26
- return value && value !== SESSION_MODEL ? value : undefined;
27
- }
28
-
29
- /** Package defaults. Domain defaults and project overrides are layered on top. */
30
- const DEFAULTS = {
31
- domains: ['btp'],
32
- hosts: ['claude-code'],
33
- language: 'en',
34
- git: { base: null },
35
- scope: { implicit: {} },
36
- risk_paths: [],
37
- tests: {},
38
- fix: {
39
- max_total: 80,
40
- max_per_file: 50,
41
- protected: [],
42
- ignored: ['package-lock.json', '**/package-lock.json', 'gen/**', 'dist/**'],
43
- },
44
- verify: {},
45
- lint: {},
46
- build: { fix_attempts: 3 },
47
- review: { build: 'area', rounds: 3 },
48
- ci: { policy_changes: 'warn', untracked_changes: 'fail' },
49
- limits: { spec_kb: 12, design_kb: 20 },
50
- };
51
-
52
- function isObject(value) {
53
- return value !== null && typeof value === 'object' && !Array.isArray(value);
54
- }
55
-
56
- /** Deep merge: objects merge key by key, everything else (arrays included) replaces. */
57
- export function merge(base, override) {
58
- if (!isObject(base) || !isObject(override)) return override === undefined ? base : override;
59
- const out = { ...base };
60
- for (const [key, value] of Object.entries(override)) out[key] = merge(base[key], value);
61
- return out;
62
- }
63
-
64
- export function loadDomain(id) {
65
- const domain = readJson(new URL(`domains/${id}/domain.json`, KIT_DIR));
66
- if (!domain) throw new AgjanError(`unknown domain '${id}'`);
67
- return domain;
68
- }
69
-
70
- /**
71
- * Loads the effective configuration of the project at `root`: package defaults, then
72
- * the enabled domains' defaults, then agjan.config.json. Also resolves the areas of all
73
- * enabled domains, keyed by both the short id and the canonical `domain:area` id.
74
- */
75
- export function loadConfig(root) {
76
- const project = readJson(join(root, CONFIG_FILE)) ?? {};
77
- if (!isObject(project)) throw new AgjanError(`${CONFIG_FILE} must contain a JSON object`);
78
- const domainIds = project.domains ?? DEFAULTS.domains;
79
-
80
- let config = merge(DEFAULTS, {});
81
- const areas = {};
82
- const shortCount = {};
83
- for (const id of domainIds) {
84
- const domain = loadDomain(id);
85
- const implicit = {};
86
- const tests = {};
87
- const verify = {};
88
- const lint = {};
89
- for (const [name, area] of Object.entries(domain.areas)) {
90
- const canonical = `${id}:${name}`;
91
- areas[canonical] = { id: canonical, domain: id, name, role: area.role };
92
- shortCount[name] = (shortCount[name] ?? 0) + 1;
93
- implicit[name] = area.implicit ?? [];
94
- tests[name] = area.tests ?? [];
95
- verify[name] = area.verify ?? {};
96
- if (area.lint) lint[name] = area.lint;
97
- }
98
- config = merge(config, {
99
- scope: { implicit },
100
- tests,
101
- verify,
102
- lint,
103
- risk_paths: [...config.risk_paths, ...(domain.risk_paths ?? [])],
104
- fix: { protected: [...config.fix.protected, ...(domain.protected ?? [])] },
105
- watched: [...(config.watched ?? []), ...(domain.watched ?? [])],
106
- });
107
- }
108
- // Short ids resolve only when they are unique among the enabled domains (design 3).
109
- for (const area of Object.values(areas)) {
110
- if (shortCount[area.name] === 1) areas[area.name] = area;
111
- }
112
-
113
- config = merge(config, project);
114
- config.domains = domainIds;
115
- config.areas = areas;
116
- return config;
117
- }
118
-
119
- /** Resolves a short or canonical area id; returns null when unknown or ambiguous. */
120
- export function resolveArea(config, id) {
121
- return config.areas[id] ?? null;
122
- }
package/src/context.mjs DELETED
@@ -1,67 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { repoRoot, userEmail } from './git.mjs';
3
- import { loadConfig } from './config.mjs';
4
- import { askOnTerminal, confirmOnTerminal, editOnTerminal } from './terminal.mjs';
5
- import { createStyle } from './ui.mjs';
6
-
7
- export const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
8
-
9
- /** UTC timestamp without milliseconds, for example 2026-10-17T09:12:03Z. */
10
- export function utcNow() {
11
- return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
12
- }
13
-
14
- /**
15
- * Everything a command needs from the outside world. Tests pass their own streams,
16
- * clock, confirmation and line editor; the CLI uses the real ones. There is deliberately
17
- * no option
18
- * to skip the confirmation from the command line or the environment.
19
- */
20
- export function createContext({
21
- cwd = process.cwd(),
22
- stdout = process.stdout,
23
- stderr = process.stderr,
24
- now = utcNow,
25
- confirm = confirmOnTerminal,
26
- edit = editOnTerminal,
27
- ask = askOnTerminal,
28
- } = {}) {
29
- let root;
30
- let config;
31
- return {
32
- cwd,
33
- /** Colors for stdout; plain text unless stdout is a terminal (see ui.mjs). */
34
- style: createStyle(stdout),
35
- now,
36
- confirm,
37
- /** Asks the human for one line, prefilled with `initial` (async). */
38
- edit,
39
- /** Asks the human a yes/no question; null without a terminal. */
40
- ask,
41
- kit: pkg.version,
42
- get root() {
43
- root ??= repoRoot(cwd);
44
- return root;
45
- },
46
- get config() {
47
- config ??= loadConfig(this.root);
48
- return config;
49
- },
50
- email() {
51
- return userEmail(this.root);
52
- },
53
- /** Whether stdout is a terminal (for the mark's blink). */
54
- isTTY: Boolean(stdout?.isTTY),
55
- /** Writes raw text to stdout, for terminal control sequences. */
56
- write(text) {
57
- stdout.write(text);
58
- },
59
- /** Writes each argument as one line; no argument writes an empty line. */
60
- out(...lines) {
61
- stdout.write(`${(lines.length ? lines : ['']).join('\n')}\n`);
62
- },
63
- err(...lines) {
64
- stderr.write(`${(lines.length ? lines : ['']).join('\n')}\n`);
65
- },
66
- };
67
- }
@@ -1,56 +0,0 @@
1
- import { spawnSync } from 'node:child_process';
2
-
3
- /**
4
- * Copilot CLI loads a project's .mcp.json only in folders it remembers as trusted, so
5
- * `init` also adds the documentation servers to Copilot's user configuration with
6
- * `copilot mcp add` (design decision 72). Servers there load in every folder. agjan
7
- * never removes or changes a server in that configuration: one that exists is reported
8
- * and left as it is.
9
- */
10
-
11
- /** Runs the copilot command; AGJAN_COPILOT names a Node script that replaces it (tests). */
12
- function copilot(args) {
13
- const options = { encoding: 'utf8', timeout: 60_000 };
14
- const fake = process.env.AGJAN_COPILOT;
15
- if (fake) return spawnSync(process.execPath, [fake, ...args], options);
16
- return spawnSync('copilot', args, { ...options, shell: process.platform === 'win32' });
17
- }
18
-
19
- /** The command line that adds one server, for messages and for doing it by hand. */
20
- export function addCommand(name, server) {
21
- const env = Object.entries(server.env ?? {}).flatMap(([k, v]) => ['--env', `${k}=${v}`]);
22
- return ['copilot', 'mcp', 'add', ...env, name, '--', server.command, ...(server.args ?? [])];
23
- }
24
-
25
- /**
26
- * The servers Copilot knows (user, workspace, plugin; not its built-in ones), as
27
- * { name: { source, command, args } }, or null when copilot cannot be run.
28
- */
29
- export function copilotServers() {
30
- const run = copilot(['mcp', 'list', '--json']);
31
- if (run.error || run.status !== 0) return null;
32
- try {
33
- const list = JSON.parse(run.stdout).mcpServers ?? {};
34
- return Object.fromEntries(Object.entries(list).filter(([, s]) => s.source !== 'builtin'));
35
- } catch {
36
- return null;
37
- }
38
- }
39
-
40
- /**
41
- * Adds each server that Copilot does not know yet. Returns one result per server:
42
- * `added`, `exists` (left as it is), or `failed` with the reason.
43
- */
44
- export function addCopilotServers(servers) {
45
- const known = copilotServers();
46
- if (!known) return Object.keys(servers).map((name) => ({ name, state: 'failed', detail: 'copilot is not on PATH' }));
47
- return Object.entries(servers).map(([name, server]) => {
48
- if (known[name]) return { name, state: 'exists', detail: `already in Copilot's ${known[name].source} configuration; left as it is` };
49
- const run = copilot(addCommand(name, server).slice(1));
50
- const output = `${run.stdout ?? ''}${run.stderr ?? ''}`.trim();
51
- if (run.error || run.status !== 0 || /^Error:/m.test(output)) {
52
- return { name, state: 'failed', detail: (output.split('\n').find((l) => l.startsWith('Error:')) ?? output.split('\n')[0] ?? `exit code ${run.status}`).trim() };
53
- }
54
- return { name, state: 'added', detail: "Copilot's user configuration" };
55
- });
56
- }
package/src/documents.mjs DELETED
@@ -1,188 +0,0 @@
1
- import { parse as parseYaml } from 'yaml';
2
-
3
- /** Required `##` headings per document (design 8). Keys stay English in every language. */
4
- export const SPEC_HEADINGS = [
5
- 'Summary',
6
- 'Why',
7
- 'Users and roles',
8
- 'Scope',
9
- 'Acceptance criteria',
10
- 'Non-functional requirements',
11
- 'Authorization',
12
- 'Business constraints',
13
- 'Open technical questions',
14
- ];
15
- export const DESIGN_HEADINGS_LIGHT = ['Impact summary', 'Mode rationale', 'Areas and rationale'];
16
- export const DESIGN_HEADINGS_FULL = [
17
- ...DESIGN_HEADINGS_LIGHT,
18
- 'Decisions',
19
- 'Answers to open technical questions',
20
- 'Risks and trade-offs',
21
- ];
22
-
23
- const TASK_ID = /^T[1-9][0-9]*$/;
24
-
25
- /**
26
- * Splits a leading YAML frontmatter block from the body. Returns `data: null` when there
27
- * is none, and an `error` string when the YAML is invalid or not a mapping.
28
- */
29
- export function splitFrontmatter(text) {
30
- const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
31
- if (!match) return { data: null, body: text };
32
- const body = text.slice(match[0].length);
33
- try {
34
- const data = parseYaml(match[1]) ?? {};
35
- if (typeof data !== 'object' || Array.isArray(data)) return { data: null, body, error: 'frontmatter must be a mapping' };
36
- return { data, body };
37
- } catch (error) {
38
- return { data: null, body, error: `invalid frontmatter: ${error.message.split('\n')[0]}` };
39
- }
40
- }
41
-
42
- /** Splits the body into lines, skipping fenced code blocks so their content is not parsed. */
43
- function outsideFences(body) {
44
- const out = [];
45
- let fence = null;
46
- body.split(/\r?\n/).forEach((line, index) => {
47
- const marker = /^(```|~~~)/.exec(line);
48
- if (marker) {
49
- if (fence === null) fence = marker[1];
50
- else if (line.startsWith(fence)) fence = null;
51
- return;
52
- }
53
- if (fence === null) out.push({ line, number: index + 1 });
54
- });
55
- return out;
56
- }
57
-
58
- export function headings(body, level = 2) {
59
- const prefix = `${'#'.repeat(level)} `;
60
- return outsideFences(body)
61
- .filter(({ line }) => line.startsWith(prefix) && !line.startsWith(`${prefix}#`))
62
- .map(({ line }) => line.slice(prefix.length).trim());
63
- }
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
-
70
- /** The lines of one `##` section (without its heading), or null when absent. */
71
- function section(body, title) {
72
- const lines = outsideFences(body);
73
- const start = lines.findIndex(({ line }) => line.trim() === `## ${title}`);
74
- if (start === -1) 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
- /**
80
- * Parses `spec.md`. Returns the authored frontmatter, the acceptance criteria and the
81
- * list of problems. `key` is the feature key; AC ids must be `<key>-AC<n>`.
82
- */
83
- export function parseSpec(text, key) {
84
- const problems = [];
85
- const { data, body, error } = splitFrontmatter(text);
86
- if (error) problems.push(error);
87
- const kind = data?.kind;
88
- if (kind !== 'business' && kind !== 'technical') problems.push("frontmatter 'kind' must be 'business' or 'technical'");
89
-
90
- problems.push(...missingHeadings(body, kind === 'technical' ? [...SPEC_HEADINGS, 'Technical constraints'] : SPEC_HEADINGS));
91
-
92
- const acs = [];
93
- const lines = section(body, 'Acceptance criteria') ?? [];
94
- const idPattern = new RegExp(`^${key}-AC[1-9][0-9]*$`);
95
- let current = null;
96
- for (const { line, number } of lines) {
97
- const heading = /^### (.+?)\s*$/.exec(line);
98
- if (heading) {
99
- current = { id: heading[1], line: number, given: false, when: false, then: false, verification: 'automated' };
100
- acs.push(current);
101
- if (!idPattern.test(current.id)) problems.push(`line ${number}: AC id '${current.id}' must look like ${key}-AC1`);
102
- continue;
103
- }
104
- if (!current) continue;
105
- const field = /^\s*(Given|When|Then|And|Verification:)\s*(.*)$/.exec(line);
106
- if (!field) continue;
107
- if (field[1] === 'Given') current.given = true;
108
- if (field[1] === 'When') current.when = true;
109
- if (field[1] === 'Then') current.then = true;
110
- if (field[1] === 'Verification:') {
111
- const value = field[2].trim();
112
- if (value === 'automated' || value === 'manual') current.verification = value;
113
- else problems.push(`line ${number}: ${current.id} verification must be 'automated' or 'manual'`);
114
- }
115
- }
116
- if (acs.length === 0) problems.push("no acceptance criteria ('### <KEY>-AC<n>' under '## Acceptance criteria')");
117
- const seen = new Set();
118
- for (const ac of acs) {
119
- if (seen.has(ac.id)) problems.push(`duplicate AC id ${ac.id}`);
120
- seen.add(ac.id);
121
- for (const part of ['given', 'when', 'then']) {
122
- if (!ac[part]) problems.push(`${ac.id} has no '${part[0].toUpperCase()}${part.slice(1)}' line`);
123
- }
124
- }
125
- return { kind, acs, problems };
126
- }
127
-
128
- /** Parses `design.md`: mode, areas and the required headings for the mode. */
129
- export function parseDesign(text) {
130
- const problems = [];
131
- const { data, body, error } = splitFrontmatter(text);
132
- if (error) problems.push(error);
133
- const mode = data?.mode;
134
- if (mode !== 'light' && mode !== 'full') problems.push("frontmatter 'mode' must be 'light' or 'full'");
135
- const areas = data?.areas;
136
- if (!Array.isArray(areas) || areas.length === 0 || !areas.every((a) => typeof a === 'string')) {
137
- problems.push("frontmatter 'areas' must be a non-empty list of area ids");
138
- }
139
- problems.push(...missingHeadings(body, mode === 'full' ? DESIGN_HEADINGS_FULL : DESIGN_HEADINGS_LIGHT));
140
- return { mode, areas: Array.isArray(areas) ? areas : [], problems };
141
- }
142
-
143
- function isRepoPath(value) {
144
- return typeof value === 'string' && value.length > 0 && !value.includes('\\') &&
145
- !value.startsWith('/') && !/^[A-Za-z]:/.test(value) && !value.split('/').includes('..');
146
- }
147
-
148
- /** Parses `tasks.md`: exactly one fenced YAML block with a `tasks` list (design 8.3). */
149
- export function parseTasks(text) {
150
- const problems = [];
151
- const blocks = [...text.matchAll(/^```ya?ml[ \t]*\r?\n([\s\S]*?)^```[ \t]*$/gm)];
152
- if (blocks.length !== 1) {
153
- return { tasks: [], problems: [`tasks.md must contain exactly one fenced yaml block (found ${blocks.length})`] };
154
- }
155
- let data;
156
- try {
157
- data = parseYaml(blocks[0][1]);
158
- } catch (error) {
159
- return { tasks: [], problems: [`invalid tasks yaml: ${error.message.split('\n')[0]}`] };
160
- }
161
- if (!Array.isArray(data?.tasks) || data.tasks.length === 0) {
162
- return { tasks: [], problems: ["the yaml block must have a non-empty 'tasks' list"] };
163
- }
164
- const tasks = [];
165
- const ids = new Set();
166
- data.tasks.forEach((task, index) => {
167
- const where = typeof task?.id === 'string' ? task.id : `task #${index + 1}`;
168
- if (typeof task !== 'object' || task === null) {
169
- problems.push(`${where}: must be a mapping`);
170
- return;
171
- }
172
- if (!TASK_ID.test(task.id ?? '')) problems.push(`${where}: id must look like T1`);
173
- else if (ids.has(task.id)) problems.push(`${where}: duplicate task id`);
174
- ids.add(task.id);
175
- if (typeof task.area !== 'string') problems.push(`${where}: 'area' is required`);
176
- if (typeof task.title !== 'string' || task.title.trim() === '') problems.push(`${where}: 'title' is required`);
177
- const covers = Array.isArray(task.covers) ? task.covers : [];
178
- if (covers.length === 0) problems.push(`${where}: 'covers' must list at least one AC id`);
179
- const paths = Array.isArray(task.paths) ? task.paths : [];
180
- if (paths.length === 0) problems.push(`${where}: 'paths' must list at least one path or glob`);
181
- for (const p of paths) {
182
- if (!isRepoPath(p)) problems.push(`${where}: path '${p}' must be relative, POSIX, without '..'`);
183
- }
184
- if (task.verify !== undefined && typeof task.verify !== 'string') problems.push(`${where}: 'verify' must be a string`);
185
- tasks.push({ id: task.id, area: task.area, title: task.title, covers, paths, verify: task.verify });
186
- });
187
- return { tasks, problems };
188
- }
package/src/errors.mjs DELETED
@@ -1,16 +0,0 @@
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
-
10
- /** Wrong command line: exit code 2. */
11
- export class UsageError extends AgjanError {
12
- constructor(message) {
13
- super(message, { exitCode: 2 });
14
- this.name = 'UsageError';
15
- }
16
- }