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
@@ -0,0 +1,47 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeJson } from '../json-file.js';
5
+ import { APPROVALS_FILE, FEATURES_DIR, changedFeatures, emptyApprovals, featureDir } from '../feature.js';
6
+ import { PROJECT_MD } from '../fix.js';
7
+ import { BASELINE_FILE, refreshBaseline } from '../baseline.js';
8
+ import { appendLog } from '../log.js';
9
+ import { AgjanError, UsageError } from '../errors.js';
10
+ const TEMPLATE = new URL('../../kit/templates/project.md', import.meta.url);
11
+ /** Map runs need finding ids but no unique key: their findings stay in their own folder. */
12
+ const MAP_KEY = 'MAP';
13
+ /** agjan map start: a record folder for this map run, and project.md from the template if absent. */
14
+ function start(ctx) {
15
+ const root = ctx.root;
16
+ const changed = changedFeatures(root, ctx.config);
17
+ if (changed.length)
18
+ throw new AgjanError(`this branch already carries ${changed.join(', ')}; map the project on its own branch`);
19
+ const date = ctx.now().slice(0, 10);
20
+ let id = date;
21
+ for (let n = 2; existsSync(featureDir(root, `maps/${id}`)); n += 1)
22
+ id = `${date}-${n}`;
23
+ const dir = featureDir(root, `maps/${id}`);
24
+ mkdirSync(dir, { recursive: true });
25
+ writeJson(join(dir, APPROVALS_FILE), emptyApprovals(id, MAP_KEY, ctx.kit, ctx.now(), 'map'));
26
+ appendLog(dir, ctx.now(), 'step', { stage: 'map', skill: 'agjan-map' });
27
+ ctx.out(`created ${FEATURES_DIR}/maps/${id}/`);
28
+ if (!existsSync(join(root, PROJECT_MD))) {
29
+ writeFileSync(join(root, PROJECT_MD), readFileSync(TEMPLATE, 'utf8'));
30
+ ctx.out(`created ${PROJECT_MD} from the template`);
31
+ }
32
+ return 0;
33
+ }
34
+ export function map(ctx, argv) {
35
+ if (argv[0] === 'start' && argv.length === 1)
36
+ return start(ctx);
37
+ throw new UsageError('usage: agjan map start');
38
+ }
39
+ /** agjan baseline refresh: records the hashes of the watched files in baseline.json. */
40
+ export function baseline(ctx, argv) {
41
+ const { positionals } = parseArgs({ args: argv, allowPositionals: true });
42
+ if (positionals.join(' ') !== 'refresh')
43
+ throw new UsageError('usage: agjan baseline refresh');
44
+ const data = refreshBaseline(ctx.root, ctx.config, ctx.now());
45
+ ctx.out(`wrote ${BASELINE_FILE}: ${Object.keys(data.watched).length} watched file(s)`);
46
+ return 0;
47
+ }
@@ -0,0 +1,90 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { AGENT_TIERS, CONFIG_FILE, SESSION_MODEL, agentModel } from '../config.js';
5
+ import { readJson, writeJson } from '../json-file.js';
6
+ import { AgjanError, UsageError } from '../errors.js';
7
+ import { pad } from '../ui.js';
8
+ import { sync } from './setup.js';
9
+ /**
10
+ * The models GitHub Copilot CLI accepts, from `copilot help config` (its `model` setting
11
+ * lists them). Null when copilot cannot be run; AGJAN_COPILOT names a stand-in (tests).
12
+ */
13
+ export function copilotModels() {
14
+ const fake = process.env.AGJAN_COPILOT;
15
+ const run = fake
16
+ ? spawnSync(process.execPath, [fake, 'help', 'config'], { encoding: 'utf8', timeout: 30_000 })
17
+ : spawnSync('copilot', ['help', 'config'], { encoding: 'utf8', timeout: 30_000, shell: process.platform === 'win32' });
18
+ if (run.error || run.status !== 0)
19
+ return null;
20
+ const section = /`model`:[^\n]*\n((?:\s+- "[^"]+"\n?)+)/.exec(run.stdout ?? '');
21
+ return section ? [...section[1].matchAll(/- "([^"]+)"/g)].map((m) => m[1]) : null;
22
+ }
23
+ /** What each reviewer runs on, per host and tier. */
24
+ function show(ctx) {
25
+ const s = ctx.style;
26
+ const config = ctx.config;
27
+ for (const host of config.hosts) {
28
+ for (const tier of AGENT_TIERS) {
29
+ const model = agentModel(config, host, tier);
30
+ const agent = tier === 'qa' ? 'agjan-qa' : tier === 'deep' ? 'agjan-reviewer-deep' : 'agjan-reviewer';
31
+ const inherited = tier === 'qa' && !config.models?.[host]?.qa ? s.gray(' (the deep model; its own: models set qa <model>)') : '';
32
+ ctx.out(`${pad(s.bold(host), host, 12)} ${pad(s.gray(tier), tier, 9)} ${pad(agent, agent, 20)} ${model ? s.cyan(model) : s.gray("the session's model")}${inherited}`);
33
+ }
34
+ }
35
+ ctx.out(s.gray(`change: npx agjan models set <balanced|deep|qa> <model> [--host <host>] (in your terminal); '${SESSION_MODEL}' uses the session's model`));
36
+ if (config.hosts.includes('copilot')) {
37
+ const models = copilotModels();
38
+ if (models)
39
+ ctx.out(s.gray(`copilot models: ${models.join(', ')}`));
40
+ }
41
+ if (config.hosts.includes('claude-code'))
42
+ ctx.out(s.gray('claude-code models: an alias (sonnet, opus, haiku, fable) or a full model id'));
43
+ return 0;
44
+ }
45
+ /**
46
+ * agjan models set <tier> <model> [--host <host>] (decision 80): the reviewer's model is a
47
+ * quality decision of the person, not of the agent it reviews: asked on the terminal (the
48
+ * guard denies it to agents), written to agjan.config.json, then `agjan sync` rewrites the
49
+ * reviewer agent files.
50
+ */
51
+ function set(ctx, tier, model, host) {
52
+ const config = ctx.config;
53
+ if (!AGENT_TIERS.includes(tier))
54
+ throw new UsageError(`tier must be one of: ${AGENT_TIERS.join(', ')}`);
55
+ const hosts = host ? [host] : config.hosts;
56
+ for (const h of hosts)
57
+ if (!config.hosts.includes(h))
58
+ throw new UsageError(`host '${h}' is not configured (hosts: ${config.hosts.join(', ')})`);
59
+ if (model !== SESSION_MODEL && hosts.includes('copilot')) {
60
+ const models = copilotModels();
61
+ if (models && !models.includes(model))
62
+ throw new AgjanError(`GitHub Copilot does not offer '${model}'; its models: ${models.join(', ')}`);
63
+ }
64
+ const answer = ctx.ask(`Let the ${tier} reviewer run on ${model === SESSION_MODEL ? "the session's model" : model} (${hosts.join(', ')})?`, { defaultYes: true });
65
+ if (answer === null)
66
+ throw new AgjanError('choosing the reviewer model needs a human at a terminal; agents must not run it. Run it yourself in a terminal.');
67
+ if (!answer) {
68
+ ctx.out(ctx.style.yellow('cancelled, nothing changed'));
69
+ return 1;
70
+ }
71
+ const file = join(ctx.root, CONFIG_FILE);
72
+ const raw = readJson(file);
73
+ if (!raw)
74
+ throw new AgjanError(`no ${CONFIG_FILE}; run 'agjan init' first`);
75
+ raw.models = raw.models ?? {};
76
+ for (const h of hosts)
77
+ raw.models[h] = { ...(raw.models[h] ?? {}), [tier]: model };
78
+ writeJson(file, raw);
79
+ ctx.out(`${ctx.style.green('set')} models.${hosts.length === 1 ? hosts[0] : `{${hosts.join(',')}}`}.${tier} = ${model}`);
80
+ return sync(ctx, []);
81
+ }
82
+ /** agjan models [set <tier> <model> [--host <host>]] */
83
+ export function run(ctx, argv) {
84
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { host: { type: 'string' } } });
85
+ if (positionals.length === 0 && !values.host)
86
+ return show(ctx);
87
+ if (positionals[0] === 'set' && positionals.length === 3)
88
+ return set(ctx, positionals[1], positionals[2], values.host);
89
+ throw new UsageError('usage: agjan models | agjan models set <balanced|deep|qa> <model> [--host <host>]');
90
+ }
@@ -0,0 +1,65 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeJson } from '../json-file.js';
5
+ import { APPROVALS_FILE, FEATURES_DIR, KEY, SLUG, emptyApprovals, featureDir, listFeatures, loadFeature, selectFeature } from '../feature.js';
6
+ import { AgjanError, UsageError } from '../errors.js';
7
+ import { readAutoDefault } from '../auto.js';
8
+ import { appendLog } from '../log.js';
9
+ const TEMPLATES = new URL('../../kit/templates/', import.meta.url);
10
+ export function renderTemplate(name, { slug, key }) {
11
+ return readFileSync(new URL(name, TEMPLATES), 'utf8').replaceAll('{{SLUG}}', slug).replaceAll('{{KEY}}', key);
12
+ }
13
+ /** agjan scaffold design [--feature <slug>]: creates design.md and tasks.md from the templates. */
14
+ export function scaffold(ctx, argv) {
15
+ const { values, positionals } = parseArgs({ args: argv, options: { feature: { type: 'string' } }, allowPositionals: true });
16
+ if (positionals.join(' ') !== 'design')
17
+ throw new UsageError('usage: agjan scaffold design [--feature <slug>]');
18
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
19
+ for (const name of ['design.md', 'tasks.md']) {
20
+ const file = join(feature.dir, name);
21
+ if (existsSync(file)) {
22
+ ctx.out(`${FEATURES_DIR}/${feature.slug}/${name} exists; not changed`);
23
+ continue;
24
+ }
25
+ writeFileSync(file, renderTemplate(name, { slug: feature.slug, key: feature.key }));
26
+ ctx.out(`created ${FEATURES_DIR}/${feature.slug}/${name}`);
27
+ }
28
+ return 0;
29
+ }
30
+ /** agjan new <slug> --key <KEY>: creates the feature folder, approvals.json and spec.md. */
31
+ export function run(ctx, argv) {
32
+ const { values, positionals } = parseArgs({ args: argv, options: { key: { type: 'string' } }, allowPositionals: true });
33
+ const [slug] = positionals;
34
+ if (!slug || positionals.length > 1 || !values.key)
35
+ throw new UsageError('usage: agjan new <slug> --key <KEY>');
36
+ if (!SLUG.test(slug))
37
+ throw new UsageError(`slug '${slug}' must be lowercase letters, digits and '-', at most 48 characters`);
38
+ if (slug === 'fixes')
39
+ throw new UsageError("'fixes' is reserved");
40
+ const key = values.key;
41
+ if (!KEY.test(key))
42
+ throw new UsageError(`key '${key}' must be 2 to 6 uppercase letters or digits, starting with a letter`);
43
+ const root = ctx.root;
44
+ const dir = featureDir(root, slug);
45
+ if (existsSync(dir))
46
+ throw new AgjanError(`${FEATURES_DIR}/${slug} already exists`);
47
+ for (const other of listFeatures(root)) {
48
+ if (loadFeature(root, other).key === key)
49
+ throw new AgjanError(`key ${key} is already used by feature '${other}'`);
50
+ }
51
+ mkdirSync(dir, { recursive: true });
52
+ const approvals = emptyApprovals(slug, key, ctx.kit, ctx.now());
53
+ // The person's auto mode default for this checkout (decision 79).
54
+ const auto = readAutoDefault(root);
55
+ if (auto)
56
+ approvals.auto = { by: auto.by, at_utc: ctx.now(), from: 'default' };
57
+ writeJson(join(dir, APPROVALS_FILE), approvals);
58
+ writeFileSync(join(dir, 'spec.md'), renderTemplate('spec.md', { slug, key }));
59
+ ctx.out(`created ${FEATURES_DIR}/${slug}/ (key ${key}): ${APPROVALS_FILE}, spec.md`);
60
+ if (auto) {
61
+ appendLog(dir, ctx.now(), 'auto-on', { from: 'default' });
62
+ ctx.out(`auto mode on (the default of ${auto.by} in this checkout): spec and design pass automatically after their reviews; approve verify stays with the user`);
63
+ }
64
+ return 0;
65
+ }
@@ -0,0 +1,176 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { resolveArea } from '../config.js';
3
+ import { FEATURES_DIR } from '../feature.js';
4
+ import { acTestFiles } from '../tests-map.js';
5
+ import { acResults, loadResults, resultLabel } from '../test-results.js';
6
+ import { overrideBase, runChecks } from './check.js';
7
+ import { readFix } from './fix.js';
8
+ import { highlightMarkdown } from '../ui.js';
9
+ import { readLog } from '../log.js';
10
+ import { acceptanceState } from '../progress.js';
11
+ import { qaState, qaTestFiles } from '../qa.js';
12
+ function short(hash) {
13
+ return hash ? hash.slice('sha256:'.length, 'sha256:'.length + 12) : '-';
14
+ }
15
+ /** A fix or a map run in the PR summary. */
16
+ function recordSection(feature) {
17
+ const out = [`### ${feature.kind === 'fix' ? 'Fix' : 'Map run'} ${feature.slug} (${feature.key})`, ''];
18
+ if (feature.kind === 'fix') {
19
+ const fix = readFix(feature);
20
+ out.push(`**What:** ${fix?.what ?? '(not stated)'}`, '');
21
+ if (fix?.files) {
22
+ out.push(`**Size:** ${fix.total} changed lines (limit ${fix.limits?.max_total}, per file ${fix.limits?.max_per_file})`, '');
23
+ out.push(`**Verified with:** ${fix.verify ?? 'not stated'}`, '');
24
+ }
25
+ else {
26
+ out.push('**Not recorded yet** (`npx agjan fix record`).', '');
27
+ }
28
+ }
29
+ else {
30
+ out.push('Writes the baseline `docs/agjan/project.md` and `docs/agjan/baseline.json`.', '');
31
+ }
32
+ for (const r of feature.reviews.records)
33
+ out.push(`- ${r.id} ${r.step} round ${r.round}: ${r.verdict} (${r.findings?.length ?? 0} findings, isolation ${r.reviewer?.isolation ?? 'unknown'})`);
34
+ if (feature.reviews.records.length)
35
+ out.push('');
36
+ return out;
37
+ }
38
+ function featureSection(ctx, feature) {
39
+ if (feature.kind !== 'feature')
40
+ return recordSection(feature);
41
+ const out = [];
42
+ const mode = feature.design?.parsed.mode ?? '-';
43
+ out.push(`### ${feature.slug} (${feature.key})`, '');
44
+ out.push('| Document | State | Hash | Approved |', '|---|---|---|---|');
45
+ const spec = feature.approvals.approvals.spec;
46
+ const design = feature.approvals.approvals.design;
47
+ const approver = (stamp) => (stamp.by === 'auto' ? `**auto mode** (switched on by ${stamp.enabled_by})` : stamp.by);
48
+ out.push(`| spec.md | ${feature.state.spec} | ${short(feature.spec?.hash)} | ${spec ? `${spec.at_utc} by ${approver(spec)}` : '-'} |`);
49
+ out.push(`| design (${mode}) | ${feature.state.design} | ${short(feature.designHash)} | ${design ? `${design.at_utc} by ${approver(design)}` : '-'} |`);
50
+ const acceptance = acceptanceState(ctx.root, ctx.config, feature);
51
+ const acceptedBy = acceptance.state === 'accepted' ? acceptance.approval : null;
52
+ const notes = [];
53
+ const autoGates = [spec, design].filter((s) => s?.by === 'auto').length;
54
+ if (autoGates || feature.approvals.auto) {
55
+ const on = feature.approvals.auto;
56
+ notes.push(`**Auto mode:** ${on ? `on since ${on.at_utc} (switched on by ${on.by})` : 'was on'}. ${autoGates ? 'Gates approved automatically after their reviews passed; no person approved them.' : 'No gate was approved automatically yet.'}`);
57
+ }
58
+ out.push(`| acceptance (verify) | ${acceptance.state === 'none' ? 'not accepted' : acceptance.state} | ${short(acceptance.approval?.tree_hash)} | ${acceptance.approval ? `${acceptance.approval.at_utc} by ${acceptance.approval.by}` : '-'} |`, '');
59
+ if (notes.length)
60
+ out.push(...notes, '');
61
+ const tasks = feature.tasks;
62
+ if (feature.spec && tasks) {
63
+ const areaNames = [...new Set(tasks.parsed.tasks.map((t) => resolveArea(ctx.config, t.area)?.name).filter((name) => Boolean(name)))];
64
+ const tests = acTestFiles(ctx.root, ctx.config, areaNames, feature.key);
65
+ const tasksFor = (id) => tasks.parsed.tasks.filter((t) => t.covers.includes(id)).map((t) => t.id).join(', ') || '-';
66
+ const loaded = loadResults(ctx.root, ctx.config, areaNames);
67
+ const results = loaded.files.length ? acResults(loaded, feature.key) : null;
68
+ out.push('**Acceptance criteria**', '');
69
+ out.push(results ? '| AC | Verification | Tasks | Tests | Result |' : '| AC | Verification | Tasks | Tests |');
70
+ out.push(results ? '|---|---|---|---|---|' : '|---|---|---|---|');
71
+ for (const ac of feature.spec.parsed.acs) {
72
+ const files = [...(tests.get(ac.id) ?? [])].join(', ');
73
+ const manual = ac.verification === 'manual';
74
+ const row = `| ${ac.id} | ${ac.verification} | ${tasksFor(ac.id)} | ${manual ? 'manual' : files || '**missing**'} |`;
75
+ if (!results)
76
+ out.push(row);
77
+ else
78
+ out.push(`${row} ${manual ? '-' : resultLabel(results.get(ac.id)).replace(/^(failed|not run|skipped)$/, '**$1**')} |`);
79
+ }
80
+ out.push('');
81
+ if (results)
82
+ out.push(`Results from ${loaded.files.map((f) => `\`${f.file}\``).join(', ')}.`, '');
83
+ else
84
+ out.push('Test coverage is by AC id in test files (existence only).', '');
85
+ const manual = feature.spec.parsed.acs.filter((ac) => ac.verification === 'manual');
86
+ if (manual.length && acceptedBy) {
87
+ out.push(`**Manual ACs, checked by hand by ${acceptedBy.by} when accepting:**`, '');
88
+ for (const ac of manual)
89
+ out.push(`- [x] ${ac.id}`);
90
+ out.push('');
91
+ }
92
+ else if (manual.length) {
93
+ out.push('**Check by hand before accepting (manual ACs):**', '');
94
+ for (const ac of manual)
95
+ out.push(`- [ ] ${ac.id}`);
96
+ out.push('');
97
+ }
98
+ }
99
+ if (feature.reviews.records.length) {
100
+ out.push('**Reviews**', '', '| Review | Step | Round | Verdict | Findings | Isolation |', '|---|---|---|---|---|---|');
101
+ for (const r of feature.reviews.records) {
102
+ out.push(`| ${r.id} | ${r.step} | ${r.round} | ${r.verdict} | ${r.findings?.length ?? 0} | ${r.reviewer?.isolation ?? 'unknown'} |`);
103
+ }
104
+ out.push('');
105
+ const weak = feature.reviews.records.filter((r) => r.reviewer?.isolation !== 'agent');
106
+ if (weak.length)
107
+ out.push(`Reviews without an isolated reviewer agent: ${weak.map((r) => r.id).join(', ')}.`, '');
108
+ const qa = qaState(ctx.root, ctx.config, feature);
109
+ if (qa.state !== 'off') {
110
+ const tests = qaTestFiles(ctx.root, feature.slug);
111
+ out.push(qa.record
112
+ ? `**QA:** ${qa.record.id} round ${qa.record.round}: ${qa.record.verdict} (${qa.state}); ${tests.length} test file(s) written from the spec, kept as regression tests: ${tests.map((f) => `\`${f}\``).join(', ') || '-'}.`
113
+ : '**QA:** not run yet.', '');
114
+ }
115
+ const granted = readLog(feature.dir).filter((e) => e.event === 'round-granted');
116
+ if (granted.length)
117
+ out.push(`Rounds beyond the limit, allowed by the user: ${granted.map((e) => `${e.step} round ${e.round}`).join(', ')}.`, '');
118
+ }
119
+ const open = feature.findings.filter((f) => f.status === 'open');
120
+ const accepted = feature.findings.filter((f) => f.status === 'accepted');
121
+ if (open.length) {
122
+ out.push('**Open findings**', '');
123
+ for (const f of open)
124
+ out.push(`- ${f.id} [${f.severity}] ${f.issue}`);
125
+ out.push('');
126
+ }
127
+ if (accepted.length) {
128
+ out.push('**Accepted findings**', '');
129
+ for (const f of accepted) {
130
+ const a = feature.approvals.accepted.find((x) => x.finding === f.id);
131
+ out.push(`- ${f.id} [${f.severity}] ${f.issue} (accepted by ${a?.by}: ${a?.reason})`);
132
+ }
133
+ out.push('');
134
+ }
135
+ const amendments = feature.amendments.filter((a) => a.status !== 'lapsed');
136
+ if (amendments.length) {
137
+ out.push('**Scope amendments**', '');
138
+ for (const a of amendments)
139
+ out.push(`- ${a.id} (${a.task}, ${a.status}): ${a.paths.join(', ')}: ${a.reason}`);
140
+ out.push('');
141
+ }
142
+ return out;
143
+ }
144
+ /** agjan pr-summary [--feature <slug>]: prints the PR description in Markdown (design 6.6). */
145
+ export function run(ctx, argv) {
146
+ const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' }, base: { type: 'string' } } });
147
+ overrideBase(ctx, values.base);
148
+ const { report, features, files, policy } = runChecks(ctx, 'ci', values.feature);
149
+ const out = ['## agjan summary', ''];
150
+ if (features.length === 0)
151
+ out.push('No agjan feature in this change.', '');
152
+ for (const feature of features)
153
+ out.push(...featureSection(ctx, feature));
154
+ const code = files.filter((f) => !f.startsWith(`${FEATURES_DIR}/`) && !f.startsWith('.agjan/'));
155
+ out.push(`**Changed files** (${code.length} outside ${FEATURES_DIR}/)`, '');
156
+ for (const f of code)
157
+ out.push(`- ${f}`);
158
+ if (code.length)
159
+ out.push('');
160
+ if (files.includes(`${FEATURES_DIR}/project.md`))
161
+ out.push('The baseline `docs/agjan/project.md` is updated in this change.', '');
162
+ if (policy.length) {
163
+ out.push('**Policy changes** (these change the rules that check this PR)', '');
164
+ for (const p of policy)
165
+ out.push(`- ${p}`);
166
+ out.push('');
167
+ }
168
+ const state = report.errors > 0 ? `**failing**: ${report.errors} error(s)` : 'passing';
169
+ out.push(`**agjan check --ci**: ${state}, ${report.warnings} warning(s)`, '');
170
+ for (const item of report.items.filter((i) => i.level === 'error'))
171
+ out.push(`- ${item.scope}: ${item.message}`);
172
+ if (report.errors)
173
+ out.push('');
174
+ ctx.out(highlightMarkdown(ctx.style, out.join('\n').trimEnd()));
175
+ return 0;
176
+ }
@@ -0,0 +1,42 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { relative } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeProgress } from '../progress-view.js';
5
+ import { markLine, tone } from '../ui.js';
6
+ /** Opens a file with the system's default application; failures are reported, not thrown. */
7
+ function openFile(file) {
8
+ const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', file]] : [process.platform === 'darwin' ? 'open' : 'xdg-open', [file]];
9
+ try {
10
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
11
+ child.on('error', () => { });
12
+ child.unref();
13
+ return true;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /** agjan progress [--open]: regenerates the progress pages and prints the overview. */
20
+ export function run(ctx, argv) {
21
+ const { values } = parseArgs({ args: argv, options: { open: { type: 'boolean' } } });
22
+ const s = ctx.style;
23
+ const result = writeProgress(ctx, { now: Date.parse(ctx.now()) });
24
+ for (const line of markLine(s, ctx.kit, 'progress'))
25
+ ctx.out(line);
26
+ if (!result) {
27
+ ctx.err('agjan progress: the pages could not be generated; run npx agjan check for details');
28
+ return 1;
29
+ }
30
+ if (!result.models.length)
31
+ ctx.out('no features, fixes or map runs yet');
32
+ for (const m of result.models) {
33
+ const turn = m.turn === 'you' ? s.violet('your turn') : m.turn === 'merged' ? tone(s, 'merged') : s.cyan('agent working');
34
+ const stage = m.stages[Math.min(m.at, m.stages.length - 1)];
35
+ ctx.out(`${s.bold(m.key.padEnd(6))} ${m.slug.padEnd(34)} ${stage.padEnd(15)} ${turn}${m.turn === 'merged' ? '' : s.gray(` · ${m.now}`)}`);
36
+ }
37
+ const html = relative(ctx.root, result.html).split('\\').join('/');
38
+ ctx.out('', `${s.gray('overview')} ${html} ${s.gray('· per unit: docs/agjan/<unit>/progress.md')}`);
39
+ if (values.open && !openFile(result.html))
40
+ ctx.out(`open ${html} in a browser`);
41
+ return 0;
42
+ }
@@ -0,0 +1,105 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { FEATURES_DIR, loadFeature, selectFeature } from '../feature.js';
5
+ import { readLog } from '../log.js';
6
+ import { usageBetween } from '../usage.js';
7
+ export const REPORT_FILE = 'report.md';
8
+ function minutes(ms) {
9
+ if (ms < 60_000)
10
+ return `${Math.round(ms / 1000)}s`;
11
+ const m = Math.round(ms / 60_000);
12
+ return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`;
13
+ }
14
+ function tokens(n) {
15
+ return n >= 10_000 ? `${(n / 1000).toFixed(0)}k` : String(n);
16
+ }
17
+ function sum(records) {
18
+ const total = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
19
+ for (const r of records)
20
+ for (const k of Object.keys(total))
21
+ total[k] += r[k];
22
+ return total;
23
+ }
24
+ function models(records) {
25
+ return [...new Set(records.map((r) => r.model))].join(', ') || '-';
26
+ }
27
+ /**
28
+ * Spans of the feature's life from its log (design 12.1): each step runs from its
29
+ * `step` event to the next `step` or `gate-requested` event; each gate wait runs from
30
+ * `gate-requested` to the matching approval or rejection.
31
+ */
32
+ export function spans(events, end) {
33
+ const out = [];
34
+ const times = events.map((e) => Date.parse(e.at_utc));
35
+ events.forEach((event, i) => {
36
+ const at = times[i];
37
+ if (event.event === 'step') {
38
+ const next = events.findIndex((e, j) => j > i && ['step', 'gate-requested', 'waiting'].includes(e.event));
39
+ const label = [event.stage, event.task, event.role].filter(Boolean).join(' ');
40
+ out.push({ kind: 'step', label, from: at, to: next === -1 ? end : times[next] });
41
+ }
42
+ if (event.event === 'gate-requested') {
43
+ const done = events.findIndex((e, j) => j > i && (e.event === 'approved' || e.event === 'rejected'));
44
+ out.push({ kind: 'gate', label: `gate ${event.gate}`, from: at, to: done === -1 ? end : times[done], open: done === -1 });
45
+ }
46
+ // The agent stopped for the user: waiting until its next step.
47
+ if (event.event === 'waiting') {
48
+ const next = events.findIndex((e, j) => j > i && e.event === 'step');
49
+ out.push({ kind: 'gate', label: 'waiting for you', from: at, to: next === -1 ? end : times[next], open: next === -1 });
50
+ }
51
+ });
52
+ return out;
53
+ }
54
+ /** report.md for a feature (design 12.2). */
55
+ export function buildReport(root, feature, { now = Date.now(), homes = {} } = {}) {
56
+ const events = readLog(feature.dir);
57
+ const lines = [`# Report: ${feature.slug} (${feature.key})`, '', `<!-- Generated by agjan report at ${new Date(now).toISOString().replace(/\.\d{3}Z$/, 'Z')}. Do not edit. -->`, ''];
58
+ if (events.length === 0)
59
+ return [...lines, 'No log events yet.', ''].join('\n');
60
+ const start = Date.parse(events[0].at_utc);
61
+ const list = spans(events, now);
62
+ const usage = usageBetween(root, start, now, homes);
63
+ const inSpan = (span) => usage.filter((r) => r.at >= span.from && r.at < span.to);
64
+ const steps = list.filter((s) => s.kind === 'step');
65
+ const gates = list.filter((s) => s.kind === 'gate');
66
+ const active = steps.reduce((t, s) => t + (s.to - s.from), 0);
67
+ const waiting = gates.reduce((t, s) => t + (s.to - s.from), 0);
68
+ const total = sum(usage);
69
+ const reviewer = usage.filter((r) => r.agent === 'subagent');
70
+ lines.push('## Summary', '');
71
+ lines.push(`| | |`, `|---|---|`);
72
+ lines.push(`| Time window | ${events[0].at_utc} to ${new Date(now).toISOString().replace(/\.\d{3}Z$/, 'Z')} |`);
73
+ lines.push(`| Active work (steps) | ${minutes(active)} |`);
74
+ lines.push(`| Waiting at gates | ${minutes(waiting)}${gates.some((g) => g.open) ? ' (a gate is still open)' : ''} |`);
75
+ lines.push(`| Reviews | ${feature.reviews.records.length} (${feature.reviews.records.filter((r) => r.verdict === 'blocked').length} blocked) |`);
76
+ if (usage.length) {
77
+ lines.push(`| Tokens: input / cache read / cache write / output | ${tokens(total.input)} / ${tokens(total.cacheRead)} / ${tokens(total.cacheWrite)} / ${tokens(total.output)} |`);
78
+ lines.push(`| Share of output by reviewer agents | ${total.output ? Math.round((sum(reviewer).output / total.output) * 100) : 0}% |`);
79
+ lines.push(`| Models | ${models(usage)} |`);
80
+ }
81
+ else {
82
+ lines.push('| Tokens and models | unknown: no host session records found for this folder and time window |');
83
+ }
84
+ lines.push('');
85
+ lines.push('## Steps and gates', '', '| Step | Start | Duration | Input | Output | Models |', '|---|---|---|---|---|---|');
86
+ for (const s of list) {
87
+ const r = inSpan(s);
88
+ const t = sum(r);
89
+ const when = new Date(s.from).toISOString().slice(11, 16);
90
+ lines.push(`| ${s.label}${s.open ? ' (open)' : ''} | ${when} | ${minutes(s.to - s.from)} | ${r.length ? tokens(t.input + t.cacheRead + t.cacheWrite) : '-'} | ${r.length ? tokens(t.output) : '-'} | ${models(r)} |`);
91
+ }
92
+ lines.push('');
93
+ lines.push('Durations come from `log.jsonl`. Tokens and models come from the hosts\' session records (Claude Code, GitHub Copilot CLI) for this ' +
94
+ 'folder within each time span; other work in the same folder at the same time is included.', '');
95
+ return lines.join('\n');
96
+ }
97
+ /** agjan report [--feature <slug>]: writes docs/agjan/<slug>/report.md. */
98
+ export function run(ctx, argv) {
99
+ const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' } } });
100
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
101
+ const text = buildReport(ctx.root, feature, { now: Date.parse(ctx.now()) });
102
+ writeFileSync(join(feature.dir, REPORT_FILE), text);
103
+ ctx.out(`wrote ${FEATURES_DIR}/${feature.slug}/${REPORT_FILE}`);
104
+ return 0;
105
+ }