agjan 0.0.0-stage → 0.0.1

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 (84) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +105 -2
  4. package/bin/agjan.mjs +12 -0
  5. package/docs/brand/agjan-icon.svg +14 -0
  6. package/docs/brand/agjan-logo-dark.svg +17 -0
  7. package/docs/brand/agjan-logo-light.svg +17 -0
  8. package/docs/guide.md +232 -0
  9. package/kit/domains/btp/domain.json +27 -0
  10. package/kit/hooks/guard.mjs +61 -0
  11. package/kit/mcp/servers.json +5 -0
  12. package/kit/skills/agjan-build/SKILL.md +61 -0
  13. package/kit/skills/agjan-design/SKILL.md +95 -0
  14. package/kit/skills/agjan-fix/SKILL.md +55 -0
  15. package/kit/skills/agjan-map/SKILL.md +51 -0
  16. package/kit/skills/agjan-spec/SKILL.md +111 -0
  17. package/kit/skills/agjan-verify/SKILL.md +60 -0
  18. package/kit/skills/btp-architect/SKILL.md +51 -0
  19. package/kit/skills/btp-architect/references/deployment.md +72 -0
  20. package/kit/skills/btp-architect/references/security.md +54 -0
  21. package/kit/skills/cap-developer/SKILL.md +49 -0
  22. package/kit/skills/cap-developer/references/handlers.md +47 -0
  23. package/kit/skills/cap-developer/references/modeling.md +52 -0
  24. package/kit/skills/cap-developer/references/services.md +53 -0
  25. package/kit/skills/cap-developer/references/testing.md +39 -0
  26. package/kit/skills/cap-developer/references/validation-security.md +49 -0
  27. package/kit/skills/fiori-developer/SKILL.md +64 -0
  28. package/kit/skills/fiori-developer/references/elements.md +77 -0
  29. package/kit/skills/fiori-developer/references/freestyle-ts.md +45 -0
  30. package/kit/skills/fiori-developer/references/testing.md +32 -0
  31. package/kit/skills/fiori-developer/references/ui5-basics.md +52 -0
  32. package/kit/skills/solution-reviewer/SKILL.md +51 -0
  33. package/kit/templates/agents-block.md +20 -0
  34. package/kit/templates/agjan-ci.yml +40 -0
  35. package/kit/templates/design.md +17 -0
  36. package/kit/templates/project.md +28 -0
  37. package/kit/templates/spec.md +33 -0
  38. package/kit/templates/tasks.md +13 -0
  39. package/package.json +50 -4
  40. package/schemas/approvals.schema.json +93 -0
  41. package/schemas/config.schema.json +79 -0
  42. package/schemas/log.schema.json +30 -0
  43. package/schemas/reviews.schema.json +68 -0
  44. package/schemas/tasks.schema.json +26 -0
  45. package/src/adapters/claude-code.mjs +95 -0
  46. package/src/adapters/copilot.mjs +88 -0
  47. package/src/baseline.mjs +66 -0
  48. package/src/cli.mjs +133 -0
  49. package/src/commands/check.mjs +363 -0
  50. package/src/commands/fix.mjs +116 -0
  51. package/src/commands/gates.mjs +264 -0
  52. package/src/commands/log.mjs +53 -0
  53. package/src/commands/map.mjs +47 -0
  54. package/src/commands/new.mjs +53 -0
  55. package/src/commands/pr-summary.mjs +134 -0
  56. package/src/commands/report.mjs +110 -0
  57. package/src/commands/review.mjs +49 -0
  58. package/src/commands/setup.mjs +269 -0
  59. package/src/commands/status.mjs +163 -0
  60. package/src/config.mjs +98 -0
  61. package/src/context.mjs +58 -0
  62. package/src/documents.mjs +188 -0
  63. package/src/errors.mjs +16 -0
  64. package/src/feature.mjs +214 -0
  65. package/src/fix.mjs +108 -0
  66. package/src/git.mjs +66 -0
  67. package/src/hash.mjs +33 -0
  68. package/src/hook.mjs +48 -0
  69. package/src/json-file.mjs +24 -0
  70. package/src/log.mjs +37 -0
  71. package/src/managed.mjs +178 -0
  72. package/src/mcp-config.mjs +83 -0
  73. package/src/mcp.mjs +142 -0
  74. package/src/plan.mjs +41 -0
  75. package/src/progress.mjs +85 -0
  76. package/src/review-policy.mjs +49 -0
  77. package/src/review.mjs +320 -0
  78. package/src/scope.mjs +30 -0
  79. package/src/terminal.mjs +98 -0
  80. package/src/test-results.mjs +111 -0
  81. package/src/tests-map.mjs +29 -0
  82. package/src/ui.mjs +110 -0
  83. package/src/usage.mjs +118 -0
  84. package/src/validate.mjs +41 -0
@@ -0,0 +1,134 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { resolveArea } from '../config.mjs';
3
+ import { FEATURES_DIR } from '../feature.mjs';
4
+ import { acTestFiles } from '../tests-map.mjs';
5
+ import { acResults, loadResults, resultLabel } from '../test-results.mjs';
6
+ import { overrideBase, runChecks } from './check.mjs';
7
+ import { readFix } from './fix.mjs';
8
+ import { highlightMarkdown } from '../ui.mjs';
9
+
10
+ function short(hash) {
11
+ return hash ? hash.slice('sha256:'.length, 'sha256:'.length + 12) : '-';
12
+ }
13
+
14
+ /** A fix or a map run in the PR summary. */
15
+ function recordSection(feature) {
16
+ const out = [`### ${feature.kind === 'fix' ? 'Fix' : 'Map run'} ${feature.slug} (${feature.key})`, ''];
17
+ if (feature.kind === 'fix') {
18
+ const fix = readFix(feature);
19
+ out.push(`**What:** ${fix?.what ?? '(not stated)'}`, '');
20
+ if (fix?.files) {
21
+ out.push(`**Size:** ${fix.total} changed lines (limit ${fix.limits.max_total}, per file ${fix.limits.max_per_file})`, '');
22
+ out.push(`**Verified with:** ${fix.verify ?? 'not stated'}`, '');
23
+ } else {
24
+ out.push('**Not recorded yet** (`npx agjan fix record`).', '');
25
+ }
26
+ } else {
27
+ out.push('Writes the baseline `docs/agjan/project.md` and `docs/agjan/baseline.json`.', '');
28
+ }
29
+ for (const r of feature.reviews.records) out.push(`- ${r.id} ${r.step} round ${r.round}: ${r.verdict} (${r.findings?.length ?? 0} findings, isolation ${r.reviewer?.isolation ?? 'unknown'})`);
30
+ if (feature.reviews.records.length) out.push('');
31
+ return out;
32
+ }
33
+
34
+ function featureSection(ctx, feature) {
35
+ if (feature.kind !== 'feature') return recordSection(feature);
36
+ const out = [];
37
+ const mode = feature.design?.parsed.mode ?? '-';
38
+ out.push(`### ${feature.slug} (${feature.key})`, '');
39
+ out.push('| Document | State | Hash | Approved |', '|---|---|---|---|');
40
+ const spec = feature.approvals.approvals.spec;
41
+ const design = feature.approvals.approvals.design;
42
+ out.push(`| spec.md | ${feature.state.spec} | ${short(feature.spec?.hash)} | ${spec ? `${spec.at_utc} by ${spec.by}` : '-'} |`);
43
+ out.push(`| design (${mode}) | ${feature.state.design} | ${short(feature.designHash)} | ${design ? `${design.at_utc} by ${design.by}` : '-'} |`, '');
44
+
45
+ if (feature.spec && feature.tasks) {
46
+ const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(ctx.config, t.area)?.name).filter(Boolean))];
47
+ const tests = acTestFiles(ctx.root, ctx.config, areaNames, feature.key);
48
+ const tasksFor = (id) => feature.tasks.parsed.tasks.filter((t) => t.covers.includes(id)).map((t) => t.id).join(', ') || '-';
49
+ const loaded = loadResults(ctx.root, ctx.config, areaNames);
50
+ const results = loaded.files.length ? acResults(loaded, feature.key) : null;
51
+ out.push('**Acceptance criteria**', '');
52
+ out.push(results ? '| AC | Verification | Tasks | Tests | Result |' : '| AC | Verification | Tasks | Tests |');
53
+ out.push(results ? '|---|---|---|---|---|' : '|---|---|---|---|');
54
+ for (const ac of feature.spec.parsed.acs) {
55
+ const files = [...(tests.get(ac.id) ?? [])].join(', ');
56
+ const manual = ac.verification === 'manual';
57
+ const row = `| ${ac.id} | ${ac.verification} | ${tasksFor(ac.id)} | ${manual ? 'manual' : files || '**missing**'} |`;
58
+ if (!results) out.push(row);
59
+ else out.push(`${row} ${manual ? '-' : resultLabel(results.get(ac.id)).replace(/^(failed|not run|skipped)$/, '**$1**')} |`);
60
+ }
61
+ out.push('');
62
+ if (results) out.push(`Results from ${loaded.files.map((f) => `\`${f.file}\``).join(', ')}.`, '');
63
+ else out.push('Test coverage is by AC id in test files (existence only).', '');
64
+ const manual = feature.spec.parsed.acs.filter((ac) => ac.verification === 'manual');
65
+ if (manual.length) {
66
+ out.push('**Verify before merge (manual ACs):**', '');
67
+ for (const ac of manual) out.push(`- [ ] ${ac.id}`);
68
+ out.push('');
69
+ }
70
+ }
71
+
72
+ if (feature.reviews.records.length) {
73
+ out.push('**Reviews**', '', '| Review | Step | Round | Verdict | Findings | Isolation |', '|---|---|---|---|---|---|');
74
+ for (const r of feature.reviews.records) {
75
+ out.push(`| ${r.id} | ${r.step} | ${r.round} | ${r.verdict} | ${r.findings?.length ?? 0} | ${r.reviewer?.isolation ?? 'unknown'} |`);
76
+ }
77
+ out.push('');
78
+ const weak = feature.reviews.records.filter((r) => r.reviewer?.isolation !== 'agent');
79
+ if (weak.length) out.push(`Reviews without an isolated reviewer agent: ${weak.map((r) => r.id).join(', ')}.`, '');
80
+ }
81
+
82
+ const open = feature.findings.filter((f) => f.status === 'open');
83
+ const accepted = feature.findings.filter((f) => f.status === 'accepted');
84
+ if (open.length) {
85
+ out.push('**Open findings**', '');
86
+ for (const f of open) out.push(`- ${f.id} [${f.severity}] ${f.issue}`);
87
+ out.push('');
88
+ }
89
+ if (accepted.length) {
90
+ out.push('**Accepted findings**', '');
91
+ for (const f of accepted) {
92
+ const a = feature.approvals.accepted.find((x) => x.finding === f.id);
93
+ out.push(`- ${f.id} [${f.severity}] ${f.issue} (accepted by ${a.by}: ${a.reason})`);
94
+ }
95
+ out.push('');
96
+ }
97
+ const amendments = feature.amendments.filter((a) => a.status !== 'lapsed');
98
+ if (amendments.length) {
99
+ out.push('**Scope amendments**', '');
100
+ for (const a of amendments) out.push(`- ${a.id} (${a.task}, ${a.status}): ${a.paths.join(', ')}: ${a.reason}`);
101
+ out.push('');
102
+ }
103
+ return out;
104
+ }
105
+
106
+ /** agjan pr-summary [--feature <slug>]: prints the PR description in Markdown (design 6.6). */
107
+ export function run(ctx, argv) {
108
+ const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' }, base: { type: 'string' } } });
109
+ overrideBase(ctx, values.base);
110
+ const { report, features, files, policy } = runChecks(ctx, 'ci', values.feature);
111
+ const out = ['## agjan summary', ''];
112
+
113
+ if (features.length === 0) out.push('No agjan feature in this change.', '');
114
+ for (const feature of features) out.push(...featureSection(ctx, feature));
115
+
116
+ const code = files.filter((f) => !f.startsWith(`${FEATURES_DIR}/`) && !f.startsWith('.agjan/'));
117
+ out.push(`**Changed files** (${code.length} outside ${FEATURES_DIR}/)`, '');
118
+ for (const f of code) out.push(`- ${f}`);
119
+ if (code.length) out.push('');
120
+ if (files.includes(`${FEATURES_DIR}/project.md`)) out.push('The baseline `docs/agjan/project.md` is updated in this change.', '');
121
+
122
+ if (policy.length) {
123
+ out.push('**Policy changes** (these change the rules that check this PR)', '');
124
+ for (const p of policy) out.push(`- ${p}`);
125
+ out.push('');
126
+ }
127
+
128
+ const state = report.errors > 0 ? `**failing**: ${report.errors} error(s)` : 'passing';
129
+ out.push(`**agjan check --ci**: ${state}, ${report.warnings} warning(s)`, '');
130
+ for (const item of report.items.filter((i) => i.level === 'error')) out.push(`- ${item.scope}: ${item.message}`);
131
+ if (report.errors) out.push('');
132
+ ctx.out(highlightMarkdown(ctx.style, out.join('\n').trimEnd()));
133
+ return 0;
134
+ }
@@ -0,0 +1,110 @@
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.mjs';
5
+ import { readLog } from '../log.mjs';
6
+ import { usageBetween } from '../usage.mjs';
7
+
8
+ export const REPORT_FILE = 'report.md';
9
+
10
+ function minutes(ms) {
11
+ if (ms < 60_000) return `${Math.round(ms / 1000)}s`;
12
+ const m = Math.round(ms / 60_000);
13
+ return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`;
14
+ }
15
+
16
+ function tokens(n) {
17
+ return n >= 10_000 ? `${(n / 1000).toFixed(0)}k` : String(n);
18
+ }
19
+
20
+ function sum(records) {
21
+ const total = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
22
+ for (const r of records) for (const k of Object.keys(total)) total[k] += r[k];
23
+ return total;
24
+ }
25
+
26
+ function models(records) {
27
+ return [...new Set(records.map((r) => r.model))].join(', ') || '-';
28
+ }
29
+
30
+ /**
31
+ * Spans of the feature's life from its log (design 12.1): each step runs from its
32
+ * `step` event to the next `step` or `gate-requested` event; each gate wait runs from
33
+ * `gate-requested` to the matching approval or rejection.
34
+ */
35
+ export function spans(events, end) {
36
+ const out = [];
37
+ const times = events.map((e) => Date.parse(e.at_utc));
38
+ events.forEach((event, i) => {
39
+ const at = times[i];
40
+ if (event.event === 'step') {
41
+ const next = events.findIndex((e, j) => j > i && (e.event === 'step' || e.event === 'gate-requested'));
42
+ const label = [event.stage, event.task, event.role].filter(Boolean).join(' ');
43
+ out.push({ kind: 'step', label, from: at, to: next === -1 ? end : times[next] });
44
+ }
45
+ if (event.event === 'gate-requested') {
46
+ const done = events.findIndex((e, j) => j > i && (e.event === 'approved' || e.event === 'rejected'));
47
+ out.push({ kind: 'gate', label: `gate ${event.gate}`, from: at, to: done === -1 ? end : times[done], open: done === -1 });
48
+ }
49
+ });
50
+ return out;
51
+ }
52
+
53
+ /** report.md for a feature (design 12.2). */
54
+ export function buildReport(root, feature, { now = Date.now(), homes = {} } = {}) {
55
+ const events = readLog(feature.dir);
56
+ const lines = [`# Report: ${feature.slug} (${feature.key})`, '', `<!-- Generated by agjan report at ${new Date(now).toISOString().replace(/\.\d{3}Z$/, 'Z')}. Do not edit. -->`, ''];
57
+ if (events.length === 0) return [...lines, 'No log events yet.', ''].join('\n');
58
+
59
+ const start = Date.parse(events[0].at_utc);
60
+ const list = spans(events, now);
61
+ const usage = usageBetween(root, start, now, homes);
62
+ const inSpan = (span) => usage.filter((r) => r.at >= span.from && r.at < span.to);
63
+
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
+
71
+ lines.push('## Summary', '');
72
+ lines.push(`| | |`, `|---|---|`);
73
+ lines.push(`| Time window | ${events[0].at_utc} to ${new Date(now).toISOString().replace(/\.\d{3}Z$/, 'Z')} |`);
74
+ lines.push(`| Active work (steps) | ${minutes(active)} |`);
75
+ lines.push(`| Waiting at gates | ${minutes(waiting)}${gates.some((g) => g.open) ? ' (a gate is still open)' : ''} |`);
76
+ lines.push(`| Reviews | ${feature.reviews.records.length} (${feature.reviews.records.filter((r) => r.verdict === 'blocked').length} blocked) |`);
77
+ if (usage.length) {
78
+ lines.push(`| Tokens: input / cache read / cache write / output | ${tokens(total.input)} / ${tokens(total.cacheRead)} / ${tokens(total.cacheWrite)} / ${tokens(total.output)} |`);
79
+ lines.push(`| Share of output by reviewer agents | ${total.output ? Math.round((sum(reviewer).output / total.output) * 100) : 0}% |`);
80
+ lines.push(`| Models | ${models(usage)} |`);
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
+
86
+ lines.push('## Steps and gates', '', '| Step | Start | Duration | Input | Output | Models |', '|---|---|---|---|---|---|');
87
+ for (const s of list) {
88
+ const r = inSpan(s);
89
+ const t = sum(r);
90
+ const when = new Date(s.from).toISOString().slice(11, 16);
91
+ 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)} |`);
92
+ }
93
+ lines.push('');
94
+ lines.push(
95
+ 'Durations come from `log.jsonl`. Tokens and models come from the hosts\' session records (Claude Code, GitHub Copilot CLI) for this ' +
96
+ 'folder within each time span; other work in the same folder at the same time is included.',
97
+ '',
98
+ );
99
+ return lines.join('\n');
100
+ }
101
+
102
+ /** agjan report [--feature <slug>]: writes docs/agjan/<slug>/report.md. */
103
+ export function run(ctx, argv) {
104
+ const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' } } });
105
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
106
+ const text = buildReport(ctx.root, feature, { now: Date.parse(ctx.now()) });
107
+ writeFileSync(join(feature.dir, REPORT_FILE), text);
108
+ ctx.out(`wrote ${FEATURES_DIR}/${feature.slug}/${REPORT_FILE}`);
109
+ return 0;
110
+ }
@@ -0,0 +1,49 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { serve } from '../mcp.mjs';
3
+ import { buildContextText, parseStep } from '../review.mjs';
4
+ import { loadFeature, selectFeature } from '../feature.mjs';
5
+ import { tone } from '../ui.mjs';
6
+ import { UsageError } from '../errors.mjs';
7
+
8
+ /** agjan mcp [--host <name>] [--isolation agent|fork|none]: the agjan MCP server on stdio. */
9
+ export function mcp(ctx, argv) {
10
+ const { values } = parseArgs({ args: argv, options: { host: { type: 'string' }, isolation: { type: 'string' } } });
11
+ const isolation = values.isolation ?? 'unknown';
12
+ if (!['agent', 'shared', 'fork', 'none', 'unknown'].includes(isolation)) {
13
+ throw new UsageError('--isolation must be agent, shared, fork or none');
14
+ }
15
+ // Resolve the repository now so a misconfigured server fails at start, not on first call.
16
+ void ctx.root;
17
+ return serve(ctx, { host: values.host ?? 'unknown', isolation });
18
+ }
19
+
20
+ /**
21
+ * agjan review show [--step <step>] [--feature <slug>]: read-only. Without --step it lists
22
+ * the review records; with --step it prints the context a reviewer would get.
23
+ * There is deliberately no CLI command that records a review.
24
+ */
25
+ export function show(ctx, argv) {
26
+ const { values, positionals } = parseArgs({
27
+ args: argv,
28
+ options: { step: { type: 'string' }, feature: { type: 'string' } },
29
+ allowPositionals: true,
30
+ });
31
+ if (positionals[0] !== 'show' || positionals.length !== 1) throw new UsageError('usage: agjan review show [--step <step>] [--feature <slug>]');
32
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
33
+ if (values.step) {
34
+ ctx.out(buildContextText(ctx.root, ctx.config, feature, parseStep(values.step, feature, ctx.config)));
35
+ return 0;
36
+ }
37
+ if (feature.reviews.records.length === 0) {
38
+ ctx.out(`no reviews recorded for ${feature.slug}`);
39
+ return 0;
40
+ }
41
+ const status = new Map(feature.findings.map((f) => [f.id, f.status]));
42
+ for (const r of feature.reviews.records) {
43
+ const st = ctx.style;
44
+ const meta = st.gray(`(${r.at_utc}, ${r.reviewer?.host ?? '?'}, isolation ${r.reviewer?.isolation ?? '?'})`);
45
+ ctx.out(`${st.bold(r.id)} ${r.step} round ${r.round}: ${tone(st, r.verdict)} ${meta}`);
46
+ for (const f of r.findings ?? []) ctx.out(` ${st.cyan(f.id)} [${tone(st, f.severity)}] ${tone(st, status.get(f.id))}: ${f.issue}`);
47
+ }
48
+ return 0;
49
+ }
@@ -0,0 +1,269 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { parseArgs } from 'node:util';
7
+ import { CONFIG_FILE, loadConfig, loadDomain } from '../config.mjs';
8
+ import { readJson, writeJson } from '../json-file.mjs';
9
+ import { applyPlan, planStatus } from '../managed.mjs';
10
+ import { ADAPTERS, buildPlan, unsupportedHosts } from '../plan.mjs';
11
+ import { hookStatus, installHook } from '../hook.mjs';
12
+ import { GUARD } from '../adapters/copilot.mjs';
13
+ import { git, mergeBase, resolveBase } from '../git.mjs';
14
+ import { AgjanError, UsageError } from '../errors.mjs';
15
+ import { banner, pad, tone, verdictColor } from '../ui.mjs';
16
+
17
+ const CI_FILE = '.github/workflows/agjan.yml';
18
+ const CI_TEMPLATE = new URL('../../kit/templates/agjan-ci.yml', import.meta.url);
19
+ const BIN = fileURLToPath(new URL('../../bin/agjan.mjs', import.meta.url));
20
+
21
+ const CODEOWNERS = `# agjan: changes to the rules need an owner's review
22
+ /agjan.config.json @<owner>
23
+ /agjan.lock.json @<owner>
24
+ /docs/agjan/**/approvals.json @<owner>
25
+ /.claude/ @<owner>
26
+ /.github/agents/ @<owner>
27
+ /.github/hooks/ @<owner>
28
+ /.github/workflows/ @<owner>
29
+ /package.json @<owner>
30
+ /package-lock.json @<owner>`;
31
+
32
+ function list(value) {
33
+ return value ? value.split(',').map((v) => v.trim()).filter(Boolean) : null;
34
+ }
35
+
36
+ function printResults(ctx, results) {
37
+ const s = ctx.style;
38
+ for (const r of results) {
39
+ if (r.action === 'unchanged') continue;
40
+ const [word, ...rest] = r.action.split(' ');
41
+ ctx.out(` ${pad([tone(s, word), ...rest].join(' '), r.action, 14)} ${r.path}`);
42
+ }
43
+ const unchanged = results.filter((r) => r.action === 'unchanged').length;
44
+ if (unchanged) ctx.out(s.gray(` ${unchanged} file(s) unchanged`));
45
+ }
46
+
47
+ /** Writes the managed files for the current configuration and updates the recorded kit version. */
48
+ function doSync(ctx, { force }) {
49
+ const config = loadConfig(ctx.root);
50
+ for (const host of unsupportedHosts(config)) ctx.err(`agjan: host '${host}' has no adapter in this version; skipped`);
51
+ const results = applyPlan(ctx.root, buildPlan(config), { kit: ctx.kit, force });
52
+ const file = join(ctx.root, CONFIG_FILE);
53
+ const raw = readJson(file) ?? {};
54
+ if (raw.kit !== ctx.kit) {
55
+ writeJson(file, { ...raw, kit: ctx.kit });
56
+ results.push({ path: CONFIG_FILE, action: raw.kit ? `kit ${raw.kit} -> ${ctx.kit}` : `kit ${ctx.kit}` });
57
+ }
58
+ return results;
59
+ }
60
+
61
+ /** agjan init [--domains btp] [--hosts claude-code] [--language en] [--base <ref>] [--no-hook] [--no-ci] [--prepare] */
62
+ export function init(ctx, argv) {
63
+ const { values } = parseArgs({
64
+ args: argv,
65
+ options: {
66
+ domains: { type: 'string' },
67
+ hosts: { type: 'string' },
68
+ language: { type: 'string' },
69
+ base: { type: 'string' },
70
+ 'no-hook': { type: 'boolean' },
71
+ 'no-ci': { type: 'boolean' },
72
+ prepare: { type: 'boolean' },
73
+ },
74
+ });
75
+ const root = ctx.root;
76
+ if (existsSync(join(root, CONFIG_FILE))) throw new AgjanError(`${CONFIG_FILE} already exists; run 'agjan sync' to update the managed files`);
77
+ const domains = list(values.domains) ?? ['btp'];
78
+ for (const d of domains) loadDomain(d);
79
+ const hosts = list(values.hosts) ?? ['claude-code'];
80
+ for (const h of hosts) if (!ADAPTERS[h]) throw new UsageError(`host '${h}' is not supported in this version (supported: ${Object.keys(ADAPTERS).join(', ')})`);
81
+
82
+ const config = {
83
+ $schema: './node_modules/agjan/schemas/config.schema.json',
84
+ kit: ctx.kit,
85
+ domains,
86
+ hosts,
87
+ language: values.language ?? 'en',
88
+ };
89
+ if (values.base) config.git = { base: values.base };
90
+ writeJson(join(root, CONFIG_FILE), config);
91
+ const s = ctx.style;
92
+ for (const line of banner(s, ctx.kit)) ctx.out(line);
93
+ ctx.out(`${s.bold('agjan init')}: ${CONFIG_FILE} (domains ${domains.join(', ')}; hosts ${hosts.join(', ')})`);
94
+
95
+ printResults(ctx, doSync(ctx, { force: false }));
96
+
97
+ if (!values['no-hook']) {
98
+ const hook = installHook(root);
99
+ ctx.out(` ${pad(tone(s, hook.action), hook.action, 14)} pre-commit hook`);
100
+ }
101
+ if (values.prepare) ctx.out(` package.json ${addPrepare(root)}`);
102
+ if (!values['no-ci']) {
103
+ const ci = join(root, CI_FILE);
104
+ if (existsSync(ci)) {
105
+ ctx.out(` ${pad(s.gray('unchanged'), 'unchanged', 14)} ${CI_FILE} (exists)`);
106
+ } else {
107
+ mkdirSync(join(ci, '..'), { recursive: true });
108
+ writeFileSync(ci, readFileSync(CI_TEMPLATE, 'utf8'));
109
+ ctx.out(` ${pad(tone(s, 'created'), 'created', 14)} ${CI_FILE}`);
110
+ }
111
+ }
112
+
113
+ const pkg = readJson(join(root, 'package.json'));
114
+ if (!pkg?.devDependencies?.agjan && !pkg?.dependencies?.agjan) {
115
+ ctx.out('', s.yellow('Pin agjan in this project so every developer and CI use the same version:'), ` ${s.cyan('npm install --save-dev agjan')}`);
116
+ }
117
+ ctx.out(
118
+ '',
119
+ s.bold('Next steps:'),
120
+ ' 1. Open this folder once in Claude Code and trust it: the reviewer agent\'s',
121
+ ' agjan MCP server loads only in trusted folders.',
122
+ ' 2. Protect the base branch: require the "agjan-check" status check and a review.',
123
+ ' 3. Add this to .github/CODEOWNERS (replace @<owner>):',
124
+ ...CODEOWNERS.split('\n').map((l) => ` ${l}`),
125
+ ` 4. Run: ${s.cyan('npx agjan doctor')}`,
126
+ );
127
+ return 0;
128
+ }
129
+
130
+ function addPrepare(root) {
131
+ const file = join(root, 'package.json');
132
+ const pkg = readJson(file);
133
+ if (!pkg) return 'no package.json; prepare script not added';
134
+ const command = 'agjan hook install';
135
+ const current = pkg.scripts?.prepare;
136
+ if (current?.includes(command)) return 'prepare script already installs the hook';
137
+ if (current) return `prepare script exists; add '&& ${command}' to it yourself`;
138
+ writeJson(file, { ...pkg, scripts: { ...(pkg.scripts ?? {}), prepare: command } });
139
+ return `added "prepare": "${command}"`;
140
+ }
141
+
142
+ /** agjan sync [--force]: regenerate managed files; edited ones are kept unless --force. */
143
+ export function sync(ctx, argv) {
144
+ const { values } = parseArgs({ args: argv, options: { force: { type: 'boolean' } } });
145
+ if (!existsSync(join(ctx.root, CONFIG_FILE))) throw new AgjanError(`no ${CONFIG_FILE}; run 'agjan init' first`);
146
+ ctx.out(`${ctx.style.bold('agjan sync')}:`);
147
+ const results = doSync(ctx, { force: values.force });
148
+ printResults(ctx, results);
149
+ return results.some((r) => r.action.startsWith('kept')) ? 1 : 0;
150
+ }
151
+
152
+ /** agjan hook install */
153
+ export function hook(ctx, argv) {
154
+ if (argv[0] !== 'install' || argv.length !== 1) throw new UsageError('usage: agjan hook install');
155
+ const result = installHook(ctx.root);
156
+ ctx.out(`${ctx.style.bold('agjan hook')}: ${tone(ctx.style, result.action)} (${result.path})`);
157
+ return result.state === 'installed' ? 0 : 1;
158
+ }
159
+
160
+ /** Starts the agjan MCP server and checks that it answers initialize and lists its tools. */
161
+ function probeMcp(root) {
162
+ const input = [
163
+ { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'agjan-doctor', version: '1' } } },
164
+ { jsonrpc: '2.0', id: 2, method: 'tools/list' },
165
+ ].map((m) => JSON.stringify(m)).join('\n');
166
+ const run = spawnSync(process.execPath, [BIN, 'mcp'], { cwd: root, input: `${input}\n`, encoding: 'utf8', timeout: 10_000 });
167
+ try {
168
+ const lines = run.stdout.trim().split('\n').map((l) => JSON.parse(l));
169
+ const tools = lines.find((l) => l.id === 2)?.result?.tools?.map((t) => t.name) ?? [];
170
+ return tools.includes('review_record') ? null : `unexpected answer: ${run.stdout.slice(0, 200)}`;
171
+ } catch {
172
+ return `did not answer: ${(run.stderr || run.error?.message || '').trim().slice(0, 200)}`;
173
+ }
174
+ }
175
+
176
+ /** Runs the Copilot guard hook the way Copilot does, with a payload it must deny. */
177
+ function probeGuard(root) {
178
+ const payload = JSON.stringify({ toolName: 'bash', toolArgs: { command: 'npx agjan approve spec' } });
179
+ const run = spawnSync(process.execPath, [join(root, GUARD)], { cwd: root, input: payload, encoding: 'utf8', timeout: 10_000 });
180
+ if (run.status !== 0) return `${GUARD} did not run (is agjan installed locally?); the hook then allows every command`;
181
+ return run.stdout.includes('"deny"') ? null : `unexpected answer: ${run.stdout.slice(0, 120)}`;
182
+ }
183
+
184
+ /** Whether Claude Code has the project folder trusted, from ~/.claude.json (read-only). */
185
+ function claudeTrust(root) {
186
+ const data = readJson(join(homedir(), '.claude.json'));
187
+ if (!data?.projects) return 'unknown';
188
+ return data.projects[root]?.hasTrustDialogAccepted === true ? 'trusted' : 'not trusted';
189
+ }
190
+
191
+ /** agjan doctor: checks the environment and the project setup; exit 1 on any failure. */
192
+ export function doctor(ctx) {
193
+ const rows = [];
194
+ const ok = (what, detail = '') => rows.push(['ok', what, detail]);
195
+ const warn = (what, detail) => rows.push(['warn', what, detail]);
196
+ const fail = (what, detail) => rows.push(['fail', what, detail]);
197
+
198
+ const major = Number(process.versions.node.split('.')[0]);
199
+ if (major >= 22) ok('node', process.versions.node);
200
+ else fail('node', `${process.versions.node}; agjan needs Node 22 or later`);
201
+ const gitVersion = spawnSync('git', ['--version'], { encoding: 'utf8' });
202
+ if (gitVersion.status === 0) ok('git', gitVersion.stdout.trim().replace(/^git version /, ''));
203
+ else fail('git', 'not found on PATH');
204
+
205
+ let root;
206
+ try {
207
+ root = ctx.root;
208
+ } catch (error) {
209
+ fail('repository', error.message);
210
+ }
211
+ if (root) {
212
+ ok('agjan', ctx.kit);
213
+ const raw = readJson(join(root, CONFIG_FILE));
214
+ if (!raw) {
215
+ fail('configuration', `no ${CONFIG_FILE}; run: npx agjan init`);
216
+ } else {
217
+ const config = loadConfig(root);
218
+ ok('configuration', `domains ${config.domains.join(', ')}; hosts ${config.hosts.join(', ')}`);
219
+ if (raw.kit !== ctx.kit) warn('kit version', `project records ${raw.kit}, installed ${ctx.kit}; run: npx agjan sync`);
220
+ const local = readJson(join(root, 'node_modules', 'agjan', 'package.json'));
221
+ if (!local) warn('local install', 'agjan is not installed in node_modules; run: npm install --save-dev agjan');
222
+ else if (local.version !== ctx.kit) warn('local install', `node_modules has ${local.version}, this command is ${ctx.kit}`);
223
+ else ok('local install', local.version);
224
+
225
+ const base = resolveBase(root, config.git?.base);
226
+ if (!base) warn('base branch', `none found; set git.base in ${CONFIG_FILE}`);
227
+ else if (!mergeBase(root, base)) warn('base branch', `${base} has no common history with HEAD (fetch it?)`);
228
+ else ok('base branch', base);
229
+
230
+ const problems = planStatus(root, buildPlan(config)).filter((i) => i.state !== 'ok');
231
+ if (problems.length === 0) ok('managed files', 'up to date');
232
+ for (const p of problems) {
233
+ const fix = p.state === 'modified' ? 'edited locally; agjan sync --force restores it' : 'run: npx agjan sync';
234
+ warn('managed file', `${p.path}: ${p.state}; ${fix}`);
235
+ }
236
+
237
+ const hookState = hookStatus(root);
238
+ if (hookState.state === 'installed') ok('pre-commit hook', hookState.kind);
239
+ else warn('pre-commit hook', `${hookState.state}; run: npx agjan hook install`);
240
+
241
+ if (!existsSync(join(root, CI_FILE))) warn('ci', `${CI_FILE} is missing`);
242
+ else ok('ci', CI_FILE);
243
+
244
+ const mcp = probeMcp(root);
245
+ if (mcp) fail('agjan mcp server', mcp);
246
+ else ok('agjan mcp server', 'answers initialize and tools/list');
247
+
248
+ if (config.hosts.includes('copilot')) {
249
+ const guard = probeGuard(root);
250
+ if (guard) warn('copilot guard', guard);
251
+ else ok('copilot guard', 'denies agjan approve in a test payload');
252
+ }
253
+ if (config.hosts.includes('claude-code')) {
254
+ const trust = claudeTrust(root);
255
+ if (trust === 'trusted') ok('claude code trust', 'project folder trusted');
256
+ else warn('claude code trust', `${trust}; open the folder in Claude Code once and trust it, or the reviewer has no agjan tools`);
257
+ }
258
+ const ignored = git(root, ['check-ignore', '-q', '.agjan/x'], { allowFail: true }) !== null;
259
+ if (!ignored) warn('.gitignore', '.agjan/ is not ignored; run: npx agjan sync');
260
+ }
261
+ }
262
+
263
+ const s = ctx.style;
264
+ for (const [level, what, detail] of rows) ctx.out(`${pad(tone(s, level), level, 4)} ${pad(s.bold(what), what, 18)} ${detail}`);
265
+ const failed = rows.filter((r) => r[0] === 'fail').length;
266
+ const warned = rows.filter((r) => r[0] === 'warn').length;
267
+ ctx.out(`${s.bold('agjan doctor')}: ${verdictColor(s, failed, warned)(`${failed} failure(s), ${warned} warning(s)`)}`);
268
+ return failed ? 1 : 0;
269
+ }