agjan 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +105 -0
  4. package/dist/adapters/copilot.js +80 -0
  5. package/dist/auto.js +24 -0
  6. package/dist/baseline.js +66 -0
  7. package/dist/browser.js +46 -0
  8. package/dist/cli.js +164 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +420 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +462 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +72 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/new.js +65 -0
  17. package/dist/commands/pr-summary.js +168 -0
  18. package/dist/commands/progress.js +42 -0
  19. package/dist/commands/report.js +105 -0
  20. package/dist/commands/review.js +146 -0
  21. package/dist/commands/setup.js +393 -0
  22. package/dist/commands/status.js +303 -0
  23. package/dist/commands/ui-test.js +39 -0
  24. package/dist/config.js +110 -0
  25. package/dist/context.js +56 -0
  26. package/dist/copilot-mcp.js +56 -0
  27. package/dist/documents.js +207 -0
  28. package/dist/errors.js +15 -0
  29. package/dist/feature.js +221 -0
  30. package/dist/fix.js +117 -0
  31. package/dist/git.js +88 -0
  32. package/{src/hash.mjs → dist/hash.js} +11 -14
  33. package/dist/hook.js +47 -0
  34. package/dist/json-file.js +26 -0
  35. package/dist/log.js +50 -0
  36. package/dist/managed.js +182 -0
  37. package/dist/mcp-config.js +76 -0
  38. package/dist/mcp.js +142 -0
  39. package/dist/plan.js +40 -0
  40. package/dist/progress-view.js +494 -0
  41. package/dist/progress.js +106 -0
  42. package/{src/review-policy.mjs → dist/review-policy.js} +39 -47
  43. package/dist/review.js +435 -0
  44. package/dist/scope.js +30 -0
  45. package/dist/terminal.js +127 -0
  46. package/dist/test-results.js +101 -0
  47. package/dist/tests-map.js +29 -0
  48. package/dist/types.js +5 -0
  49. package/dist/ui.js +136 -0
  50. package/dist/usage.js +116 -0
  51. package/dist/validate.js +46 -0
  52. package/docs/guide.md +98 -37
  53. package/kit/domains/btp/domain.json +4 -4
  54. package/kit/hooks/guard.mjs +48 -119
  55. package/kit/skills/agjan-build/SKILL.md +14 -8
  56. package/kit/skills/agjan-design/SKILL.md +42 -6
  57. package/kit/skills/agjan-fix/SKILL.md +9 -10
  58. package/kit/skills/agjan-map/SKILL.md +9 -10
  59. package/kit/skills/agjan-spec/SKILL.md +22 -11
  60. package/kit/skills/agjan-verify/SKILL.md +46 -19
  61. package/kit/skills/cap-developer/SKILL.md +10 -2
  62. package/kit/skills/cap-developer/references/handlers.md +11 -9
  63. package/kit/skills/cap-developer/references/project-setup.md +21 -8
  64. package/kit/skills/cap-developer/references/testing.md +38 -14
  65. package/kit/skills/cap-developer/references/typescript.md +143 -0
  66. package/kit/skills/cap-developer/references/validation-security.md +26 -8
  67. package/kit/skills/fiori-developer/SKILL.md +20 -5
  68. package/kit/skills/fiori-developer/references/app-setup.md +91 -16
  69. package/kit/skills/fiori-developer/references/elements.md +19 -5
  70. package/kit/skills/fiori-developer/references/freestyle-ts.md +5 -1
  71. package/kit/skills/fiori-developer/references/testing.md +109 -15
  72. package/kit/templates/agents-block.md +7 -3
  73. package/package.json +11 -3
  74. package/schemas/approvals.schema.json +23 -2
  75. package/schemas/config.schema.json +0 -5
  76. package/schemas/log.schema.json +1 -1
  77. package/src/adapters/claude-code.mjs +0 -121
  78. package/src/adapters/copilot.mjs +0 -89
  79. package/src/baseline.mjs +0 -66
  80. package/src/cli.mjs +0 -155
  81. package/src/commands/branch.mjs +0 -60
  82. package/src/commands/check.mjs +0 -365
  83. package/src/commands/fix.mjs +0 -116
  84. package/src/commands/gates.mjs +0 -264
  85. package/src/commands/lint.mjs +0 -74
  86. package/src/commands/log.mjs +0 -60
  87. package/src/commands/map.mjs +0 -47
  88. package/src/commands/new.mjs +0 -53
  89. package/src/commands/pr-summary.mjs +0 -137
  90. package/src/commands/progress.mjs +0 -40
  91. package/src/commands/report.mjs +0 -115
  92. package/src/commands/review.mjs +0 -76
  93. package/src/commands/setup.mjs +0 -383
  94. package/src/commands/status.mjs +0 -248
  95. package/src/config.mjs +0 -122
  96. package/src/context.mjs +0 -67
  97. package/src/copilot-mcp.mjs +0 -56
  98. package/src/documents.mjs +0 -188
  99. package/src/errors.mjs +0 -16
  100. package/src/feature.mjs +0 -225
  101. package/src/fix.mjs +0 -108
  102. package/src/git.mjs +0 -83
  103. package/src/hook.mjs +0 -48
  104. package/src/json-file.mjs +0 -24
  105. package/src/log.mjs +0 -51
  106. package/src/managed.mjs +0 -178
  107. package/src/mcp-config.mjs +0 -83
  108. package/src/mcp.mjs +0 -147
  109. package/src/plan.mjs +0 -45
  110. package/src/progress-view.mjs +0 -466
  111. package/src/progress.mjs +0 -85
  112. package/src/review.mjs +0 -413
  113. package/src/scope.mjs +0 -30
  114. package/src/terminal.mjs +0 -118
  115. package/src/test-results.mjs +0 -111
  116. package/src/tests-map.mjs +0 -29
  117. package/src/ui.mjs +0 -136
  118. package/src/usage.mjs +0 -118
  119. package/src/validate.mjs +0 -41
@@ -1,33 +1,30 @@
1
1
  import { createHash } from 'node:crypto';
2
-
3
2
  /**
4
3
  * Normalizes text before hashing so that line endings and trailing whitespace never
5
4
  * change a hash (design 8): LF line endings, no trailing whitespace on a line, no
6
5
  * trailing blank lines, exactly one final newline.
7
6
  */
8
7
  export function normalize(text) {
9
- const lines = text.replace(/\r\n?/g, '\n').split('\n').map((line) => line.replace(/[ \t]+$/, ''));
10
- while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
11
- return lines.length === 0 ? '' : `${lines.join('\n')}\n`;
8
+ const lines = text.replace(/\r\n?/g, '\n').split('\n').map((line) => line.replace(/[ \t]+$/, ''));
9
+ while (lines.length > 0 && lines[lines.length - 1] === '')
10
+ lines.pop();
11
+ return lines.length === 0 ? '' : `${lines.join('\n')}\n`;
12
12
  }
13
-
14
13
  export function sha256(data) {
15
- return `sha256:${createHash('sha256').update(data).digest('hex')}`;
14
+ return `sha256:${createHash('sha256').update(data).digest('hex')}`;
16
15
  }
17
-
18
16
  /** Hash of one document's content. */
19
17
  export function hashText(text) {
20
- return sha256(normalize(text));
18
+ return sha256(normalize(text));
21
19
  }
22
-
23
20
  /**
24
21
  * Hash of several named documents taken together, for example the design hash over
25
22
  * design.md and tasks.md. Names are part of the hash, so swapping contents changes it.
26
23
  */
27
24
  export function hashParts(parts) {
28
- const hash = createHash('sha256');
29
- for (const [name, text] of parts) {
30
- hash.update(name).update('\0').update(normalize(text)).update('\0');
31
- }
32
- return `sha256:${hash.digest('hex')}`;
25
+ const hash = createHash('sha256');
26
+ for (const [name, text] of parts) {
27
+ hash.update(name).update('\0').update(normalize(text)).update('\0');
28
+ }
29
+ return `sha256:${hash.digest('hex')}`;
33
30
  }
package/dist/hook.js ADDED
@@ -0,0 +1,47 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { git } from './git.js';
4
+ /** The command the hook runs; also what a husky pre-commit file must contain. */
5
+ export const HOOK_COMMAND = 'npx --no-install agjan check --staged';
6
+ const MARKER = '# agjan pre-commit hook';
7
+ const HOOK = `#!/bin/sh
8
+ ${MARKER} (managed by agjan; reinstall with: npx agjan hook install)
9
+ # Fast checks on the staged change. CI runs the full check; --no-verify skips this.
10
+ exec ${HOOK_COMMAND}
11
+ `;
12
+ /** Where the pre-commit hook lives: husky if the project uses it, else git's hooks dir. */
13
+ function target(root) {
14
+ const husky = join(root, '.husky');
15
+ if (existsSync(husky))
16
+ return { kind: 'husky', path: join(husky, 'pre-commit') };
17
+ const dir = git(root, ['rev-parse', '--git-path', 'hooks']).trim();
18
+ return { kind: 'git', path: join(isAbsolute(dir) ? dir : join(root, dir), 'pre-commit') };
19
+ }
20
+ /** installed | missing | foreign (a hook agjan did not write and will not touch). */
21
+ export function hookStatus(root) {
22
+ const { kind, path } = target(root);
23
+ if (!existsSync(path))
24
+ return { kind, path, state: 'missing' };
25
+ const text = readFileSync(path, 'utf8');
26
+ if (text.includes(HOOK_COMMAND))
27
+ return { kind, path, state: 'installed' };
28
+ return { kind, path, state: kind === 'husky' ? 'missing' : 'foreign' };
29
+ }
30
+ /** Installs the hook. Never overwrites a foreign git hook; appends to husky's file. */
31
+ export function installHook(root) {
32
+ const status = hookStatus(root);
33
+ if (status.state === 'installed')
34
+ return { ...status, action: 'unchanged' };
35
+ if (status.state === 'foreign') {
36
+ return { ...status, action: `not installed: ${status.path} exists and is not agjan's; add this line to it: ${HOOK_COMMAND}` };
37
+ }
38
+ if (status.kind === 'husky') {
39
+ const current = existsSync(status.path) ? readFileSync(status.path, 'utf8') : '';
40
+ writeFileSync(status.path, `${current.replace(/\s*$/, '')}${current.trim() ? '\n' : ''}${HOOK_COMMAND}\n`);
41
+ return { ...status, state: 'installed', action: 'added to husky' };
42
+ }
43
+ mkdirSync(join(status.path, '..'), { recursive: true });
44
+ writeFileSync(status.path, HOOK);
45
+ chmodSync(status.path, 0o755);
46
+ return { ...status, state: 'installed', action: 'installed' };
47
+ }
@@ -0,0 +1,26 @@
1
+ import { readFileSync, writeFileSync, renameSync } from 'node:fs';
2
+ import { AgjanError } from './errors.js';
3
+ /** Parses a JSON file; null when it does not exist. The caller states the shape it expects. */
4
+ export function readJson(file) {
5
+ let text;
6
+ try {
7
+ text = readFileSync(file, 'utf8');
8
+ }
9
+ catch (error) {
10
+ if (error.code === 'ENOENT')
11
+ return null;
12
+ throw error;
13
+ }
14
+ try {
15
+ return JSON.parse(text);
16
+ }
17
+ catch (error) {
18
+ throw new AgjanError(`${file} is not valid JSON: ${error.message}`);
19
+ }
20
+ }
21
+ /** Writes JSON with stable formatting, atomically (write then rename). */
22
+ export function writeJson(file, value) {
23
+ const tmp = `${file}.tmp-${process.pid}`;
24
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
25
+ renameSync(tmp, file);
26
+ }
package/dist/log.js ADDED
@@ -0,0 +1,50 @@
1
+ import { appendFileSync, readFileSync, existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export const LOG_FILE = 'log.jsonl';
4
+ /** Event types (design 12.1). Script events are written by the commands themselves. */
5
+ export const EVENTS = [
6
+ 'step', // a skill starts a step (from `agjan log`)
7
+ 'gate-requested', // a skill hands a gate to the human (from `agjan log`)
8
+ 'waiting', // the agent stopped and waits for the user (from `agjan log --waiting`)
9
+ 'approved',
10
+ 'rejected',
11
+ 'accepted',
12
+ 'amendment-proposed',
13
+ 'review-recorded',
14
+ 'round-granted', // the user allowed one more review round (from `agjan review extend`)
15
+ 'auto-on', // the user switched auto mode on for the feature (from `agjan auto on`)
16
+ 'auto-off',
17
+ ];
18
+ let listener = null;
19
+ /** Called after every appended event (the CLI regenerates the progress pages with it). */
20
+ export function onEvent(fn) {
21
+ listener = fn;
22
+ }
23
+ /** Appends one event to the feature's log.jsonl. The time is always set by the script. */
24
+ export function appendLog(featureDir, at, event, fields = {}) {
25
+ const entry = { at_utc: at, event, ...fields };
26
+ appendFileSync(join(featureDir, LOG_FILE), `${JSON.stringify(entry)}\n`);
27
+ try {
28
+ listener?.(featureDir);
29
+ }
30
+ catch {
31
+ // the progress pages never break the command that recorded the event
32
+ }
33
+ return entry;
34
+ }
35
+ export function readLog(featureDir) {
36
+ const file = join(featureDir, LOG_FILE);
37
+ if (!existsSync(file))
38
+ return [];
39
+ return readFileSync(file, 'utf8')
40
+ .split('\n')
41
+ .filter(Boolean)
42
+ .flatMap((line) => {
43
+ try {
44
+ return [JSON.parse(line)];
45
+ }
46
+ catch {
47
+ return []; // a damaged line is skipped, not fatal: the log is observability only
48
+ }
49
+ });
50
+ }
@@ -0,0 +1,182 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join, relative, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { hashText } from './hash.js';
5
+ import { readJson, writeJson } from './json-file.js';
6
+ /**
7
+ * Managed content (design 16.3): whole files agjan owns (kit skills, generated agents),
8
+ * marked blocks inside files the project owns (AGENTS.md, CLAUDE.md, .gitattributes,
9
+ * .gitignore), and entries merged into JSON files (.claude/settings.json).
10
+ *
11
+ * agjan.lock.json records the hash of every managed file as agjan last wrote it, so a
12
+ * later sync can tell "the kit changed it" from "someone edited it".
13
+ */
14
+ export const LOCK_FILE = 'agjan.lock.json';
15
+ const KIT_SKILLS = new URL('../kit/skills/', import.meta.url);
16
+ const MARKERS = {
17
+ md: ['<!-- agjan:begin (managed by agjan sync; edit outside this block) -->', '<!-- agjan:end -->'],
18
+ hash: ['# agjan:begin (managed by agjan sync)', '# agjan:end'],
19
+ };
20
+ function readText(path) {
21
+ return existsSync(path) ? readFileSync(path, 'utf8') : null;
22
+ }
23
+ function toPosix(path) {
24
+ return path.split(sep).join('/');
25
+ }
26
+ /** All files of the kit's skills, as { 'name/SKILL.md': content }. */
27
+ export function kitSkillFiles() {
28
+ const root = fileURLToPath(KIT_SKILLS);
29
+ const out = {};
30
+ const walk = (dir) => {
31
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
32
+ const path = join(dir, entry.name);
33
+ if (entry.isDirectory())
34
+ walk(path);
35
+ else
36
+ out[toPosix(relative(root, path))] = readFileSync(path, 'utf8');
37
+ }
38
+ };
39
+ if (existsSync(root))
40
+ walk(root);
41
+ return out;
42
+ }
43
+ /** The body of a skill file without its frontmatter. */
44
+ export function skillBody(text) {
45
+ return text.replace(/^---\r?\n[\s\S]*?\r?\n---[ \t]*\r?\n/, '').replace(/^\s+/, '');
46
+ }
47
+ /** Finds agjan's block in a text; returns [start, end] offsets of the whole block or null. */
48
+ function findBlock(text, style) {
49
+ const [begin, end] = MARKERS[style];
50
+ const start = text.indexOf(begin);
51
+ if (start === -1)
52
+ return null;
53
+ const stop = text.indexOf(end, start);
54
+ if (stop === -1)
55
+ return null;
56
+ return [start, stop + end.length];
57
+ }
58
+ export function renderBlock(style, content) {
59
+ const [begin, end] = MARKERS[style];
60
+ return `${begin}\n${content.trimEnd()}\n${end}`;
61
+ }
62
+ /** Inserts or replaces agjan's block; everything outside the markers stays as it was. */
63
+ export function upsertBlock(text, style, content) {
64
+ const block = renderBlock(style, content);
65
+ if (text === null || text.trim() === '')
66
+ return `${block}\n`;
67
+ const at = findBlock(text, style);
68
+ if (at)
69
+ return text.slice(0, at[0]) + block + text.slice(at[1]);
70
+ return `${text.replace(/\s*$/, '')}\n\n${block}\n`;
71
+ }
72
+ export function extractBlock(text, style) {
73
+ if (text === null)
74
+ return null;
75
+ const at = findBlock(text, style);
76
+ return at ? text.slice(at[0], at[1]) : null;
77
+ }
78
+ export function readLock(root) {
79
+ return readJson(join(root, LOCK_FILE)) ?? { schema: 1, kit: null, files: {} };
80
+ }
81
+ /**
82
+ * The state of each plan item in the working tree:
83
+ * ok, missing, outdated (pristine but not what this kit version generates), modified.
84
+ */
85
+ export function planStatus(root, plan, lock = readLock(root)) {
86
+ return plan.map((item) => {
87
+ const path = join(root, item.path);
88
+ const current = readText(path);
89
+ if (item.kind === 'file') {
90
+ if (current === null)
91
+ return { ...item, state: 'missing' };
92
+ const hash = hashText(current);
93
+ if (hash === hashText(item.content))
94
+ return { ...item, state: 'ok' };
95
+ return { ...item, state: lock.files[item.path] === hash ? 'outdated' : 'modified' };
96
+ }
97
+ if (item.kind === 'block') {
98
+ if (item.skip?.(current))
99
+ return { ...item, state: 'ok' };
100
+ const block = extractBlock(current, item.style);
101
+ if (block === null)
102
+ return { ...item, state: 'missing' };
103
+ return { ...item, state: hashText(block) === hashText(renderBlock(item.style, item.content)) ? 'ok' : 'outdated' };
104
+ }
105
+ // json: a merge that must be present
106
+ let data = null;
107
+ try {
108
+ data = current === null ? null : JSON.parse(current);
109
+ }
110
+ catch {
111
+ return { ...item, state: 'modified' };
112
+ }
113
+ return { ...item, state: data !== null && item.present(data) ? 'ok' : 'missing' };
114
+ });
115
+ }
116
+ /**
117
+ * Applies the plan. Managed files someone edited are kept unless `force`; files the
118
+ * previous kit managed and this one does not are removed when pristine.
119
+ * Returns one { path, action } per touched or skipped item, and writes the lock.
120
+ */
121
+ export function applyPlan(root, plan, { kit, force = false }) {
122
+ const lock = readLock(root);
123
+ const results = [];
124
+ const files = {};
125
+ for (const item of planStatus(root, plan, lock)) {
126
+ const path = join(root, item.path);
127
+ if (item.kind === 'file') {
128
+ if (item.state === 'modified' && !force) {
129
+ results.push({ path: item.path, action: 'kept (modified locally; use --force to overwrite)' });
130
+ if (lock.files[item.path])
131
+ files[item.path] = lock.files[item.path];
132
+ continue;
133
+ }
134
+ if (item.state !== 'ok') {
135
+ mkdirSync(dirname(path), { recursive: true });
136
+ writeFileSync(path, item.content);
137
+ }
138
+ files[item.path] = hashText(item.content);
139
+ results.push({ path: item.path, action: { ok: 'unchanged', missing: 'created' }[item.state] ?? 'updated' });
140
+ }
141
+ else if (item.kind === 'block') {
142
+ if (item.state === 'ok') {
143
+ results.push({ path: item.path, action: 'unchanged' });
144
+ continue;
145
+ }
146
+ const current = readText(path);
147
+ mkdirSync(dirname(path), { recursive: true });
148
+ writeFileSync(path, upsertBlock(current, item.style, item.content));
149
+ results.push({ path: item.path, action: current === null ? 'created' : 'block updated' });
150
+ }
151
+ else {
152
+ if (item.state === 'ok') {
153
+ results.push({ path: item.path, action: 'unchanged' });
154
+ continue;
155
+ }
156
+ if (item.state === 'modified') {
157
+ results.push({ path: item.path, action: 'kept (not valid JSON; fix it and run agjan sync)' });
158
+ continue;
159
+ }
160
+ const data = readJson(path) ?? {};
161
+ mkdirSync(dirname(path), { recursive: true });
162
+ writeJson(path, item.merge(data));
163
+ results.push({ path: item.path, action: 'merged' });
164
+ }
165
+ }
166
+ for (const [old, hash] of Object.entries(lock.files)) {
167
+ if (files[old] || plan.some((i) => i.path === old))
168
+ continue;
169
+ const path = join(root, old);
170
+ const current = readText(path);
171
+ if (current !== null && hashText(current) === hash) {
172
+ rmSync(path);
173
+ results.push({ path: old, action: 'removed (no longer part of the kit)' });
174
+ }
175
+ else if (current !== null) {
176
+ results.push({ path: old, action: 'kept (no longer managed; modified locally)' });
177
+ }
178
+ }
179
+ const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
180
+ writeJson(join(root, LOCK_FILE), { schema: 1, kit, files: sorted });
181
+ return results;
182
+ }
@@ -0,0 +1,76 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolveArea } from './config.js';
3
+ /**
4
+ * Documentation MCP servers for the role skills (design 10.1): configured in
5
+ * agjan.config.json under `mcp.servers`, written into the hosts' project MCP files.
6
+ * The agjan server itself is never written here; it lives only in the reviewer agents.
7
+ *
8
+ * Kit defaults pin exact versions (kit/mcp/servers.json, shared with the skill source
9
+ * check in scripts/sources.ts): `npx -y <package>` without a version would run whatever
10
+ * is newest at every start.
11
+ */
12
+ export const PINNED = JSON.parse(readFileSync(new URL('../kit/mcp/servers.json', import.meta.url), 'utf8'));
13
+ export const DEFAULT_SERVERS = Object.fromEntries(Object.entries(PINNED).map(([name, s]) => [name, { command: 'npx', args: ['-y', `${s.package}@${s.version}`], areas: s.areas }]));
14
+ /**
15
+ * The servers to write, and the names to remove (configured with `enabled: false`).
16
+ * A server is written only when one of its areas belongs to an enabled domain.
17
+ */
18
+ export function mcpServers(config) {
19
+ const configured = { ...DEFAULT_SERVERS, ...(config.mcp?.servers ?? {}) };
20
+ const servers = {};
21
+ const removed = [];
22
+ for (const [name, server] of Object.entries(configured)) {
23
+ const merged = { ...(DEFAULT_SERVERS[name] ?? {}), ...server };
24
+ if (merged.enabled === false) {
25
+ removed.push(name);
26
+ continue;
27
+ }
28
+ if (!(merged.areas ?? []).some((a) => resolveArea(config, a)))
29
+ continue;
30
+ servers[name] = { command: merged.command ?? '', args: merged.args ?? [], ...(merged.env ? { env: merged.env } : {}) };
31
+ }
32
+ return { servers, removed };
33
+ }
34
+ function sameEntry(a, b) {
35
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
36
+ }
37
+ /**
38
+ * A JSON-merge plan item for one MCP file; `key` is the file's server map. `fixed`
39
+ * entries are written as they are (the agjan server for VS Code).
40
+ */
41
+ function mergeItem(path, key, servers, removed, shape, fixed = {}) {
42
+ const expected = { ...Object.fromEntries(Object.entries(servers).map(([n, s]) => [n, shape(s)])), ...fixed };
43
+ return {
44
+ kind: 'json',
45
+ path,
46
+ present: (data) => Object.entries(expected).every(([n, s]) => sameEntry(data[key]?.[n], s)) && removed.every((n) => !data[key]?.[n]),
47
+ merge: (data) => {
48
+ const map = { ...(data[key] ?? {}), ...expected };
49
+ for (const n of removed)
50
+ delete map[n];
51
+ return { ...data, [key]: map };
52
+ },
53
+ };
54
+ }
55
+ /**
56
+ * VS Code ignores `mcp-servers` in agent files, so its reviewer can only reach the
57
+ * agjan server through the workspace configuration, which the main chat sees too
58
+ * (decision 55). Records made through it say `isolation: shared`.
59
+ */
60
+ export const VSCODE_AGJAN = { type: 'stdio', command: 'npx', args: ['--no-install', 'agjan', 'mcp', '--host', 'vscode', '--isolation', 'shared'] };
61
+ /**
62
+ * `.mcp.json` (Claude Code, Copilot CLI) and, with the Copilot host, `.vscode/mcp.json`
63
+ * (VS Code). Entries agjan does not manage are kept.
64
+ */
65
+ export function plan(config) {
66
+ const { servers, removed } = mcpServers(config);
67
+ const hosts = config.hosts ?? [];
68
+ const items = [];
69
+ if ((hosts.includes('claude-code') || hosts.includes('copilot')) && (Object.keys(servers).length || removed.length)) {
70
+ items.push(mergeItem('.mcp.json', 'mcpServers', servers, removed, (s) => ({ ...s })));
71
+ }
72
+ if (hosts.includes('copilot')) {
73
+ items.push(mergeItem('.vscode/mcp.json', 'servers', servers, removed, (s) => ({ type: 'stdio', ...s }), { agjan: VSCODE_AGJAN }));
74
+ }
75
+ return items;
76
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,142 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { createReviewContext, recordReview } from './review.js';
3
+ import { selectFeature } from './feature.js';
4
+ import { AgjanError } from './errors.js';
5
+ /**
6
+ * The agjan MCP server (design 7.2): a minimal MCP implementation over stdio,
7
+ * newline-delimited JSON-RPC 2.0. It offers the reviewer's two operations as tools, so
8
+ * the reviewer needs no shell and findings never pass through a command line.
9
+ */
10
+ const SUPPORTED_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
11
+ const FINDING_SCHEMA = {
12
+ type: 'object',
13
+ properties: {
14
+ severity: { type: 'string', enum: ['blocker', 'major', 'minor'] },
15
+ file: { type: 'string', description: 'Repository-relative POSIX path' },
16
+ line: { type: 'integer', minimum: 1 },
17
+ issue: { type: 'string' },
18
+ suggestion: { type: 'string' },
19
+ evidence: {
20
+ type: 'string',
21
+ description: 'Where the claim is confirmed: a skill reference (path and section) or project file. Required when the finding says an API, annotation or syntax is wrong.',
22
+ },
23
+ },
24
+ required: ['severity', 'issue'],
25
+ additionalProperties: false,
26
+ };
27
+ export const TOOLS = [
28
+ {
29
+ name: 'review_context',
30
+ title: 'agjan: get review context',
31
+ description: 'Returns the inputs for one agjan review step and a context_id. Read only this material ' +
32
+ '(and files it points to) for the review. Steps: spec, design:light, design, build:<area>, ' +
33
+ 'build:<task id>, verify.',
34
+ inputSchema: {
35
+ type: 'object',
36
+ properties: {
37
+ step: { type: 'string', description: 'spec | design:light | design | build:<area> | build:<task id> | verify' },
38
+ feature: { type: 'string', description: 'Feature slug; optional when exactly one feature changed on the branch' },
39
+ },
40
+ required: ['step'],
41
+ additionalProperties: false,
42
+ },
43
+ annotations: { readOnlyHint: true },
44
+ },
45
+ {
46
+ name: 'review_record',
47
+ title: 'agjan: record review result',
48
+ description: 'Records the result of the review for a context_id: verdict, findings and the ids of earlier ' +
49
+ 'findings this change resolves. Refused if any file changed since review_context.',
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: {
53
+ context_id: { type: 'string' },
54
+ verdict: { type: 'string', enum: ['pass', 'pass-with-notes', 'blocked'] },
55
+ findings: { type: 'array', items: FINDING_SCHEMA, maxItems: 50 },
56
+ resolves: { type: 'array', items: { type: 'string' } },
57
+ },
58
+ required: ['context_id', 'verdict'],
59
+ additionalProperties: false,
60
+ },
61
+ },
62
+ ];
63
+ function text(content, isError = false) {
64
+ return { content: [{ type: 'text', text: content }], isError };
65
+ }
66
+ /** Handles one tools/call; tool failures are results with isError, not protocol errors. */
67
+ function callTool(ctx, server, name, args = {}) {
68
+ try {
69
+ if (name === 'review_context') {
70
+ const feature = selectFeature(ctx.root, ctx.config, args.feature);
71
+ const { id, text: body } = createReviewContext(ctx.root, ctx.config, { feature, step: args.step });
72
+ return text(`context_id: ${id}\n\n${body}`);
73
+ }
74
+ if (name === 'review_record') {
75
+ const record = recordReview(ctx.root, ctx.config, args, { host: server.host, isolation: server.isolation, now: ctx.now });
76
+ const ids = record.findings.map((f) => f.id).join(', ') || 'none';
77
+ return text(`recorded ${record.id} (${record.step}, round ${record.round}): ${record.verdict}; findings: ${ids}`);
78
+ }
79
+ return null;
80
+ }
81
+ catch (error) {
82
+ if (error instanceof AgjanError)
83
+ return text(error.message, true);
84
+ throw error;
85
+ }
86
+ }
87
+ /** Handles one JSON-RPC message; returns the response, or null for notifications. */
88
+ export function handleMessage(ctx, server, message) {
89
+ const { id, method, params } = message ?? {};
90
+ const isRequest = id !== undefined && id !== null;
91
+ const reply = (result) => (isRequest ? { jsonrpc: '2.0', id, result } : null);
92
+ const fail = (code, msg) => (isRequest ? { jsonrpc: '2.0', id, error: { code, message: msg } } : null);
93
+ // An invalid request always gets an answer, with id null when it has none (JSON-RPC 2.0).
94
+ if (message?.jsonrpc !== '2.0' || typeof method !== 'string') {
95
+ return { jsonrpc: '2.0', id: isRequest ? id : null, error: { code: -32600, message: 'invalid request' } };
96
+ }
97
+ switch (method) {
98
+ case 'initialize': {
99
+ const requested = params?.protocolVersion;
100
+ return reply({
101
+ protocolVersion: SUPPORTED_VERSIONS.includes(requested) ? requested : SUPPORTED_VERSIONS[0],
102
+ capabilities: { tools: { listChanged: false } },
103
+ serverInfo: { name: 'agjan', version: ctx.kit },
104
+ instructions: 'agjan review tools. Only the agjan reviewer agent uses them.',
105
+ });
106
+ }
107
+ case 'ping':
108
+ return reply({});
109
+ case 'tools/list':
110
+ return reply({ tools: TOOLS });
111
+ case 'tools/call': {
112
+ const result = callTool(ctx, server, params?.name, params?.arguments);
113
+ return result ? reply(result) : fail(-32602, `unknown tool '${params?.name}'`);
114
+ }
115
+ default:
116
+ if (method.startsWith('notifications/'))
117
+ return null;
118
+ return fail(-32601, `method not found: ${method}`);
119
+ }
120
+ }
121
+ /** Runs the server until stdin closes. Logs go to stderr; stdout carries only protocol. */
122
+ export function serve(ctx, server, { input = process.stdin, output = process.stdout } = {}) {
123
+ const rl = createInterface({ input, crlfDelay: Infinity });
124
+ rl.on('line', (line) => {
125
+ if (line.trim() === '')
126
+ return;
127
+ let response;
128
+ try {
129
+ response = handleMessage(ctx, server, JSON.parse(line));
130
+ }
131
+ catch (caught) {
132
+ const error = caught;
133
+ response = error instanceof SyntaxError
134
+ ? { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }
135
+ : { jsonrpc: '2.0', id: null, error: { code: -32603, message: error.message } };
136
+ ctx.err(`agjan mcp: ${error.stack ?? error.message}`);
137
+ }
138
+ if (response)
139
+ output.write(`${JSON.stringify(response)}\n`);
140
+ });
141
+ return new Promise((resolve) => rl.on('close', () => resolve(0)));
142
+ }
package/dist/plan.js ADDED
@@ -0,0 +1,40 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { kitSkillFiles } from './managed.js';
3
+ import * as claudeCode from './adapters/claude-code.js';
4
+ import * as copilot from './adapters/copilot.js';
5
+ import * as mcpConfig from './mcp-config.js';
6
+ export const SKILLS_DIR = '.claude/skills';
7
+ export const ADAPTERS = { [claudeCode.HOST]: claudeCode, [copilot.HOST]: copilot };
8
+ const AGENTS_BLOCK = readFileSync(new URL('../kit/templates/agents-block.md', import.meta.url), 'utf8');
9
+ /** CLAUDE.md already imports AGENTS.md outside agjan's block: no block needed. */
10
+ function importsAgents(text) {
11
+ return text !== null && /^@AGENTS\.md\s*$/m.test(text.replace(/<!-- agjan:begin[\s\S]*?<!-- agjan:end -->/, ''));
12
+ }
13
+ /**
14
+ * Everything `agjan sync` maintains for this configuration: kit skills, managed blocks,
15
+ * and the files of each enabled host adapter (design 4.4).
16
+ */
17
+ export function buildPlan(config) {
18
+ const skills = kitSkillFiles();
19
+ const items = Object.entries(skills).map(([path, content]) => ({ kind: 'file', path: `${SKILLS_DIR}/${path}`, content }));
20
+ const hosts = config.hosts ?? [claudeCode.HOST];
21
+ items.push({ kind: 'block', path: 'AGENTS.md', style: 'md', content: AGENTS_BLOCK });
22
+ // Claude Code reads CLAUDE.md; Copilot reads AGENTS.md itself. The skills stay in
23
+ // .claude/skills/ for every host: both read them from there.
24
+ if (hosts.includes(claudeCode.HOST))
25
+ items.push({ kind: 'block', path: 'CLAUDE.md', style: 'md', content: '@AGENTS.md', skip: importsAgents });
26
+ items.push({ kind: 'block', path: '.gitattributes', style: 'hash', content: 'docs/agjan/** text eol=lf\nagjan.lock.json text eol=lf' },
27
+ // node_modules too: a new project often has no .gitignore of its own (design decision 69).
28
+ { kind: 'block', path: '.gitignore', style: 'hash', content: '.agjan/\nnode_modules/\n.DS_Store\nThumbs.db' });
29
+ for (const host of hosts) {
30
+ const adapter = ADAPTERS[host];
31
+ if (adapter)
32
+ items.push(...adapter.plan(config, skills));
33
+ }
34
+ items.push(...mcpConfig.plan(config));
35
+ return items;
36
+ }
37
+ /** Hosts named in the configuration that have no adapter yet. */
38
+ export function unsupportedHosts(config) {
39
+ return (config.hosts ?? []).filter((h) => !ADAPTERS[h]);
40
+ }