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,248 +0,0 @@
1
- import { parseArgs } from 'node:util';
2
- import { FEATURES_DIR, changedFeatures, listFeatures, loadFeature, selectFeature, stillBlocked } from '../feature.mjs';
3
- import { UsageError } from '../errors.mjs';
4
- import { buildProgress, verifyState } from '../progress.mjs';
5
- import { gateReadiness, pendingGate } from './gates.mjs';
6
- import { fixRules, freshReview } from '../fix.mjs';
7
- import { projectProblems } from '../baseline.mjs';
8
- import { readFix } from './fix.mjs';
9
- import { fixAttempts, reviewerFor, roundLimit, roundState } from '../review-policy.mjs';
10
- import { mark, markLine, pad, tone } from '../ui.mjs';
11
- import { acTestFiles } from '../tests-map.mjs';
12
- import { acResults, loadResults } from '../test-results.mjs';
13
- import { runChecks } from './check.mjs';
14
- import { readLog } from '../log.mjs';
15
- import { optionalSteps } from '../progress-view.mjs';
16
-
17
- /** One indented row: a label column, then the value. `next` and `blocks` stand out. */
18
- function row(ctx, label, value) {
19
- const s = ctx.style;
20
- const styled = { next: s.bold(s.cyan(label)), blocks: s.red(label) }[label] ?? s.gray(label);
21
- ctx.out(` ${pad(styled, label, 8)} ${value}`);
22
- }
23
-
24
- /** The unit's heading: slug, key and stage (or kind). */
25
- function heading(ctx, unit, detail) {
26
- const s = ctx.style;
27
- ctx.out(`${s.bold(unit.slug)} (${s.cyan(unit.key)}) ${detail}`);
28
- }
29
-
30
- /** "review step X with agent Y", or the hand-over when the step used up its rounds. */
31
- function reviewNext(ctx, feature, step) {
32
- const state = roundState(feature, ctx.config, step);
33
- if (state.exhausted) {
34
- return `the ${step} review is still blocked after ${state.round} of ${state.limit} rounds: ask the user whether to run another round (yes: npx agjan review extend ${step}) or to stop and take over (fix with them, accept findings, or change the documents)`;
35
- }
36
- const round = state.round ? `, round ${state.next} of ${state.limit}` : '';
37
- return `review step ${step} with ${reviewerFor(ctx.config, step)}${round}`;
38
- }
39
-
40
- /** The review step a feature in Spec or Design needs next. */
41
- function gateStep(feature) {
42
- if (feature.stage === 'design') return 'design';
43
- return feature.design?.parsed.mode === 'light' ? 'design:light' : 'spec';
44
- }
45
-
46
- /** The next action in Build: a due review first, then the next task, then Verify, then the PR. */
47
- function nextInBuild(ctx, feature, progress) {
48
- // The same rule as the progress pages: a skill runs once it logged its start (decision 70).
49
- const events = readLog(feature.dir);
50
- const since = feature.approvals.approvals.design?.at_utc;
51
- const building = events.some((e) => e.event === 'step' && e.stage === 'build' && (!since || e.at_utc >= since));
52
- const lastStage = events.filter((e) => e.event === 'step').at(-1)?.stage;
53
- if (!building && (progress.next || progress.due.length)) {
54
- return `a human starts the build: /agjan-build${progress.next ? ` (first task ${progress.next.id}: ${progress.next.title})` : ''}`;
55
- }
56
- if (progress.due.length) return reviewNext(ctx, feature, progress.due[0].step);
57
- if (progress.next) return `task ${progress.next.id}: ${progress.next.title} (commit as '<KEY>-${progress.next.id}: …')`;
58
- const { state, record } = verifyState(ctx.root, ctx.config, feature);
59
- if (state === 'blocked') return `the verify review ${record.id} is blocked: resolve its findings, then /agjan-verify again`;
60
- if (state === 'stale') return `files changed after the verify review ${record.id}: /agjan-verify again`;
61
- if (state === 'current') return `${ctx.style.green('done')}: development finished and verified (${record.id}); the next steps below are optional`;
62
- return lastStage === 'verify' ? 'verify is running: /agjan-verify' : 'all tasks done and reviewed: a human starts the verification: /agjan-verify';
63
- }
64
-
65
- /** "2 open, 1 blocker(s)", red when a blocker is open. */
66
- function findingCount(ctx, open) {
67
- const blockers = open.filter((f) => f.severity === 'blocker').length;
68
- const text = `${open.length} open, ${blockers} blocker(s)`;
69
- return blockers ? ctx.style.red(text) : ctx.style.yellow(text);
70
- }
71
-
72
- /** A fix or a map run: its checks, its review, and the next step. */
73
- function describeRecord(ctx, unit, onBase = false) {
74
- if (onBase) return describeRecordOnBase(ctx, unit);
75
- heading(ctx, unit, ctx.style.magenta(unit.kind));
76
- const problems = unit.kind === 'fix' ? fixRules(ctx.root, ctx.config).problems : projectProblems(ctx.root, ctx.config);
77
- for (const p of problems) row(ctx, 'blocks', p);
78
- const review = freshReview(ctx.root, ctx.config, unit, unit.kind);
79
- row(ctx, 'review', review.problem ?? `${review.record.id} ${tone(ctx.style, review.record.verdict)}, ${tone(ctx.style, 'current')}`);
80
- const open = unit.findings.filter((f) => f.status === 'open');
81
- if (open.length) row(ctx, 'findings', findingCount(ctx, open));
82
- let next;
83
- if (problems.length) next = unit.kind === 'fix' ? 'the change is not a fix: revert it and use /agjan-spec' : `complete docs/agjan/project.md`;
84
- else if (review.problem) next = reviewNext(ctx, unit, unit.kind);
85
- else if (unit.kind === 'fix' && readFix(unit)?.review?.tree_hash !== review.record.tree_hash) next = 'npx agjan fix record --verify "<command and result>"';
86
- else next = unit.kind === 'map' ? 'npx agjan baseline refresh, commit, open a PR' : 'commit and open a PR';
87
- row(ctx, 'next', next);
88
- }
89
-
90
- /**
91
- * A feature that did not change on this branch is already on the base branch (merged, or
92
- * committed there directly): its tasks come from the whole history, and work on it
93
- * continues as a new feature on a branch.
94
- */
95
- function describeOnBase(ctx, feature) {
96
- const s = ctx.style;
97
- const progress = buildProgress(ctx.root, ctx.config, feature, { history: true });
98
- const verify = feature.reviews.records.filter((r) => r.step === 'verify').at(-1);
99
- const merged = progress.complete && verify && !stillBlocked(feature, verify);
100
- heading(ctx, feature, merged ? `stage: ${s.green('merged')}` : `stage: ${s.magenta(feature.stage)} (on the base branch)`);
101
- row(ctx, 'spec', tone(s, feature.state.spec));
102
- row(ctx, 'design', `${tone(s, feature.state.design)}${feature.design?.parsed.mode ? ` (${feature.design.parsed.mode})` : ''}`);
103
- const reviews = feature.reviews.records;
104
- if (reviews.length) row(ctx, 'reviews', `${reviews.length}, last ${reviews.at(-1).id} ${reviews.at(-1).step}: ${tone(s, reviews.at(-1).verdict)}`);
105
- for (const t of progress.tasks) {
106
- row(ctx, 'task', `${tone(s, t.commit ? 'done' : 'open')} ${t.id} [${t.areaName}] ${t.title}${t.commit ? s.gray(` (${t.commit.slice(0, 7)})`) : ''}`);
107
- }
108
- if (!merged) row(ctx, 'next', 'continue on a feature branch, or start follow-up work as a new feature');
109
- }
110
-
111
- /** A fix or a map run already on the base branch: merged once its last review passed. */
112
- function describeRecordOnBase(ctx, unit) {
113
- const s = ctx.style;
114
- const last = unit.reviews.records.at(-1);
115
- const merged = last && !stillBlocked(unit, last);
116
- heading(ctx, unit, `${s.magenta(unit.kind)} ${merged ? `stage: ${s.green('merged')}` : '(on the base branch)'}`);
117
- row(ctx, 'review', last ? `${last.id} ${tone(s, last.verdict)}` : 'none');
118
- const open = unit.findings.filter((f) => f.status === 'open');
119
- if (open.length) row(ctx, 'findings', findingCount(ctx, open));
120
- if (!merged) row(ctx, 'next', `start follow-up work on a branch (/agjan-${unit.kind === 'fix' ? 'fix' : 'map'})`);
121
- }
122
-
123
- /**
124
- * The end of a feature's agent work (verified, CI check clean or not): a screen that says
125
- * so unmistakably, what was met, what is open, and what the human does next (Gate 3).
126
- * Colored with the agjan mark on a terminal; the same content as plain text for agents,
127
- * who end /agjan-verify with it.
128
- */
129
- function completion(ctx, feature, progress) {
130
- const s = ctx.style;
131
- const areaNames = [...new Set(progress.tasks.map((t) => t.areaName))];
132
- const automated = feature.spec.parsed.acs.filter((ac) => ac.verification !== 'manual');
133
- const manual = feature.spec.parsed.acs.filter((ac) => ac.verification === 'manual');
134
- const loaded = loadResults(ctx.root, ctx.config, areaNames);
135
- const results = loaded.files.length ? acResults(loaded, feature.key) : null;
136
- const tests = acTestFiles(ctx.root, ctx.config, areaNames, feature.key);
137
- const covered = automated.filter((ac) => (results ? results.get(ac.id)?.passed && !results.get(ac.id)?.failed : tests.has(ac.id))).length;
138
- const { report } = runChecks(ctx, 'ci', feature.slug);
139
- const open = feature.findings.filter((f) => f.status === 'open');
140
- const blockers = open.filter((f) => f.severity === 'blocker').length;
141
- const ok = (text) => `${s.teal('✔')} ${text}`;
142
- const bad = (text) => `${s.red('✖')} ${text}`;
143
- const lines = [
144
- [ok(`tasks ${progress.tasks.length}/${progress.tasks.length}`), (covered === automated.length ? ok : bad)(`ACs ${covered}/${automated.length} ${results ? 'with passing tests' : 'with tests'}`),
145
- report.errors ? bad(`check --ci: ${report.errors} error(s)`) : ok('check --ci clean')].join(' '),
146
- [(blockers ? bad : ok)(`reviews ${feature.reviews.records.length}, ${blockers} blocker(s) open`), open.length - blockers ? `${s.gray('●')} ${open.length - blockers} note(s) open` : ok('no open notes')].join(' '),
147
- ];
148
- ctx.out();
149
- if (s.brand) {
150
- const stars = `${s.teal('✦')} ${s.violet('✦')} ${s.teal('✦')}`;
151
- for (const line of mark(s, ctx.kit, `${stars} ${s.bold(`${feature.key} is done`)} ${stars}`, `${feature.slug} · development finished and verified`)) ctx.out(line);
152
- } else {
153
- ctx.out(`✔ ${feature.key} is done: development finished and verified (${feature.slug})`);
154
- }
155
- for (const line of lines) ctx.out(` ${line}`);
156
- ctx.out(` ${s.bold('Optional next steps:')}`);
157
- const steps = optionalSteps(ctx.root, feature, { manual: manual.map((ac) => ac.id) });
158
- for (const step of steps) ctx.out(` ${s.violet('▸')} ${step}`);
159
- }
160
-
161
- function describe(ctx, feature, onBase = false) {
162
- if (feature.kind !== 'feature') return describeRecord(ctx, feature, onBase);
163
- if (onBase) return describeOnBase(ctx, feature);
164
- heading(ctx, feature, `stage: ${ctx.style.magenta(feature.stage)}`);
165
- row(ctx, 'spec', tone(ctx.style, feature.state.spec));
166
- const mode = feature.design?.parsed.mode ? ` (${feature.design.parsed.mode})` : '';
167
- row(ctx, 'design', `${tone(ctx.style, feature.state.design)}${mode}`);
168
- const steps = [...new Set(feature.reviews.records.map((r) => r.step))];
169
- for (const step of steps) {
170
- const records = feature.reviews.records.filter((r) => r.step === step);
171
- const last = records[records.length - 1];
172
- const { limit, extra } = roundState(feature, ctx.config, step);
173
- row(ctx, 'review', `${step}: ${tone(ctx.style, last.verdict)} (round ${last.round} of ${limit}${extra ? `, ${extra} granted by the user` : ''}, ${last.id})`);
174
- }
175
- const open = feature.findings.filter((f) => f.status === 'open');
176
- if (open.length) {
177
- row(ctx, 'findings', findingCount(ctx, open));
178
- }
179
- for (const a of feature.amendments.filter((x) => x.status !== 'approved')) {
180
- row(ctx, 'amend', `${a.id} ${tone(ctx.style, a.status)}: ${a.paths.join(', ')}`);
181
- }
182
- if (feature.stage === 'build') {
183
- const progress = buildProgress(ctx.root, ctx.config, feature);
184
- for (const t of progress.tasks) {
185
- row(ctx, 'task', `${tone(ctx.style, t.commit ? 'done' : 'open')} ${t.id} [${t.areaName}] ${t.title}${t.commit ? ctx.style.gray(` (${t.commit.slice(0, 7)})`) : ''}`);
186
- }
187
- for (const d of progress.due) row(ctx, 'due', ctx.style.yellow(`review ${d.step} (${d.reason})`));
188
- row(ctx, 'next', nextInBuild(ctx, feature, progress).replace('<KEY>', feature.key));
189
- const verify = verifyState(ctx.root, ctx.config, feature);
190
- if (progress.complete && progress.due.length === 0 && verify.state === 'current') completion(ctx, feature, progress);
191
- } else {
192
- // Spec and Design: either the gate is ready for the human, or what blocks it.
193
- const gate = pendingGate(feature);
194
- const { problems } = gateReadiness(ctx, feature, gate);
195
- if (problems.length === 0) {
196
- row(ctx, 'next', `${ctx.style.green('ready for approval')}: a human runs '${ctx.style.bold(`npx agjan approve ${gate}`)}' in a terminal`);
197
- } else {
198
- for (const p of problems) row(ctx, 'blocks', p);
199
- const step = gateStep(feature);
200
- const state = roundState(feature, ctx.config, step);
201
- if (state.exhausted) row(ctx, 'next', ctx.style.red(reviewNext(ctx, feature, step)));
202
- else row(ctx, 'next', `resolve the points above, then ${reviewNext(ctx, feature, step)}; then request 'approve ${gate}'`);
203
- }
204
- }
205
- }
206
-
207
- /**
208
- * agjan status --done [--feature <slug>]: only the completion block of a verified feature,
209
- * for the agent's final message (exit 1 with the next step while it is not done).
210
- */
211
- function done(ctx, slug) {
212
- const feature = loadFeature(ctx.root, slug);
213
- const progress = feature.kind === 'feature' && feature.stage === 'build' ? buildProgress(ctx.root, ctx.config, feature) : null;
214
- if (progress?.complete && progress.due.length === 0 && verifyState(ctx.root, ctx.config, feature).state === 'current') {
215
- completion(ctx, feature, progress);
216
- return 0;
217
- }
218
- ctx.out(`${feature.key} is not done yet: ${progress ? nextInBuild(ctx, feature, progress).replace('<KEY>', feature.key) : `stage ${feature.stage}`}`);
219
- return 1;
220
- }
221
-
222
- /** agjan status [--feature <slug> | --all | --done] */
223
- export function run(ctx, argv) {
224
- const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' }, all: { type: 'boolean' }, done: { type: 'boolean' } } });
225
- const root = ctx.root;
226
- if (values.done) return done(ctx, selectFeature(root, ctx.config, values.feature));
227
- let slugs;
228
- if (values.feature) {
229
- if (!listFeatures(root).includes(values.feature)) throw new UsageError(`no feature '${values.feature}'`);
230
- slugs = [values.feature];
231
- } else {
232
- slugs = values.all ? listFeatures(root) : changedFeatures(root, ctx.config);
233
- }
234
- const c = ctx.config;
235
- const branches = 'branches: ask the user, then npx agjan branch';
236
- for (const line of markLine(ctx.style, ctx.kit, 'status')) ctx.out(line);
237
- ctx.out(ctx.style.gray(`settings: documents in '${c.language ?? 'en'}' (headings in English); reviews up to ${roundLimit(c)} rounds; ${fixAttempts(c)} attempts for failing checks; ${branches}`));
238
- if (slugs.length === 0) {
239
- ctx.out(values.all ? `no features in ${FEATURES_DIR}` : 'no changed feature on this branch (agjan status --all lists every feature)');
240
- return 0;
241
- }
242
- const changed = new Set(changedFeatures(root, ctx.config));
243
- slugs.forEach((slug, i) => {
244
- if (i > 0) ctx.out();
245
- describe(ctx, loadFeature(root, slug), !changed.has(slug));
246
- });
247
- return 0;
248
- }
package/src/config.mjs DELETED
@@ -1,122 +0,0 @@
1
- import { join } from 'node:path';
2
- import { readJson } from './json-file.mjs';
3
- import { AgjanError } from './errors.mjs';
4
-
5
- export const CONFIG_FILE = 'agjan.config.json';
6
-
7
- const KIT_DIR = new URL('../kit/', import.meta.url);
8
-
9
- /**
10
- * The commands `agjan init` offers for `agent.allow`: agjan itself (approve, accept and
11
- * reject stay denied by the guard), the tests, and the git commands of the workflow.
12
- */
13
- export const RECOMMENDED_ALLOW = ['npx agjan', 'npm test', 'git status', 'git diff', 'git log', 'git add', 'git commit'];
14
-
15
- /**
16
- * Reviewer models (`models.<host>.<tier>`). "session" means the reviewer agent runs on the
17
- * model of the session that starts it: no model is written into the agent file. `init`
18
- * writes this default visibly for every host, so users notice it and can change it.
19
- */
20
- export const SESSION_MODEL = 'session';
21
- export const MODEL_TIERS = ['balanced', 'deep'];
22
-
23
- /** The model to write into an agent file, or undefined for the session's model. */
24
- export function agentModel(config, host, tier) {
25
- const value = config.models?.[host]?.[tier] ?? config.models?.[host]?.balanced;
26
- return value && value !== SESSION_MODEL ? value : undefined;
27
- }
28
-
29
- /** Package defaults. Domain defaults and project overrides are layered on top. */
30
- const DEFAULTS = {
31
- domains: ['btp'],
32
- hosts: ['claude-code'],
33
- language: 'en',
34
- git: { base: null },
35
- scope: { implicit: {} },
36
- risk_paths: [],
37
- tests: {},
38
- fix: {
39
- max_total: 80,
40
- max_per_file: 50,
41
- protected: [],
42
- ignored: ['package-lock.json', '**/package-lock.json', 'gen/**', 'dist/**'],
43
- },
44
- verify: {},
45
- lint: {},
46
- build: { fix_attempts: 3 },
47
- review: { build: 'area', rounds: 3 },
48
- ci: { policy_changes: 'warn', untracked_changes: 'fail' },
49
- limits: { spec_kb: 12, design_kb: 20 },
50
- };
51
-
52
- function isObject(value) {
53
- return value !== null && typeof value === 'object' && !Array.isArray(value);
54
- }
55
-
56
- /** Deep merge: objects merge key by key, everything else (arrays included) replaces. */
57
- export function merge(base, override) {
58
- if (!isObject(base) || !isObject(override)) return override === undefined ? base : override;
59
- const out = { ...base };
60
- for (const [key, value] of Object.entries(override)) out[key] = merge(base[key], value);
61
- return out;
62
- }
63
-
64
- export function loadDomain(id) {
65
- const domain = readJson(new URL(`domains/${id}/domain.json`, KIT_DIR));
66
- if (!domain) throw new AgjanError(`unknown domain '${id}'`);
67
- return domain;
68
- }
69
-
70
- /**
71
- * Loads the effective configuration of the project at `root`: package defaults, then
72
- * the enabled domains' defaults, then agjan.config.json. Also resolves the areas of all
73
- * enabled domains, keyed by both the short id and the canonical `domain:area` id.
74
- */
75
- export function loadConfig(root) {
76
- const project = readJson(join(root, CONFIG_FILE)) ?? {};
77
- if (!isObject(project)) throw new AgjanError(`${CONFIG_FILE} must contain a JSON object`);
78
- const domainIds = project.domains ?? DEFAULTS.domains;
79
-
80
- let config = merge(DEFAULTS, {});
81
- const areas = {};
82
- const shortCount = {};
83
- for (const id of domainIds) {
84
- const domain = loadDomain(id);
85
- const implicit = {};
86
- const tests = {};
87
- const verify = {};
88
- const lint = {};
89
- for (const [name, area] of Object.entries(domain.areas)) {
90
- const canonical = `${id}:${name}`;
91
- areas[canonical] = { id: canonical, domain: id, name, role: area.role };
92
- shortCount[name] = (shortCount[name] ?? 0) + 1;
93
- implicit[name] = area.implicit ?? [];
94
- tests[name] = area.tests ?? [];
95
- verify[name] = area.verify ?? {};
96
- if (area.lint) lint[name] = area.lint;
97
- }
98
- config = merge(config, {
99
- scope: { implicit },
100
- tests,
101
- verify,
102
- lint,
103
- risk_paths: [...config.risk_paths, ...(domain.risk_paths ?? [])],
104
- fix: { protected: [...config.fix.protected, ...(domain.protected ?? [])] },
105
- watched: [...(config.watched ?? []), ...(domain.watched ?? [])],
106
- });
107
- }
108
- // Short ids resolve only when they are unique among the enabled domains (design 3).
109
- for (const area of Object.values(areas)) {
110
- if (shortCount[area.name] === 1) areas[area.name] = area;
111
- }
112
-
113
- config = merge(config, project);
114
- config.domains = domainIds;
115
- config.areas = areas;
116
- return config;
117
- }
118
-
119
- /** Resolves a short or canonical area id; returns null when unknown or ambiguous. */
120
- export function resolveArea(config, id) {
121
- return config.areas[id] ?? null;
122
- }
package/src/context.mjs DELETED
@@ -1,67 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { repoRoot, userEmail } from './git.mjs';
3
- import { loadConfig } from './config.mjs';
4
- import { askOnTerminal, confirmOnTerminal, editOnTerminal } from './terminal.mjs';
5
- import { createStyle } from './ui.mjs';
6
-
7
- export const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
8
-
9
- /** UTC timestamp without milliseconds, for example 2026-10-17T09:12:03Z. */
10
- export function utcNow() {
11
- return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
12
- }
13
-
14
- /**
15
- * Everything a command needs from the outside world. Tests pass their own streams,
16
- * clock, confirmation and line editor; the CLI uses the real ones. There is deliberately
17
- * no option
18
- * to skip the confirmation from the command line or the environment.
19
- */
20
- export function createContext({
21
- cwd = process.cwd(),
22
- stdout = process.stdout,
23
- stderr = process.stderr,
24
- now = utcNow,
25
- confirm = confirmOnTerminal,
26
- edit = editOnTerminal,
27
- ask = askOnTerminal,
28
- } = {}) {
29
- let root;
30
- let config;
31
- return {
32
- cwd,
33
- /** Colors for stdout; plain text unless stdout is a terminal (see ui.mjs). */
34
- style: createStyle(stdout),
35
- now,
36
- confirm,
37
- /** Asks the human for one line, prefilled with `initial` (async). */
38
- edit,
39
- /** Asks the human a yes/no question; null without a terminal. */
40
- ask,
41
- kit: pkg.version,
42
- get root() {
43
- root ??= repoRoot(cwd);
44
- return root;
45
- },
46
- get config() {
47
- config ??= loadConfig(this.root);
48
- return config;
49
- },
50
- email() {
51
- return userEmail(this.root);
52
- },
53
- /** Whether stdout is a terminal (for the mark's blink). */
54
- isTTY: Boolean(stdout?.isTTY),
55
- /** Writes raw text to stdout, for terminal control sequences. */
56
- write(text) {
57
- stdout.write(text);
58
- },
59
- /** Writes each argument as one line; no argument writes an empty line. */
60
- out(...lines) {
61
- stdout.write(`${(lines.length ? lines : ['']).join('\n')}\n`);
62
- },
63
- err(...lines) {
64
- stderr.write(`${(lines.length ? lines : ['']).join('\n')}\n`);
65
- },
66
- };
67
- }
@@ -1,56 +0,0 @@
1
- import { spawnSync } from 'node:child_process';
2
-
3
- /**
4
- * Copilot CLI loads a project's .mcp.json only in folders it remembers as trusted, so
5
- * `init` also adds the documentation servers to Copilot's user configuration with
6
- * `copilot mcp add` (design decision 72). Servers there load in every folder. agjan
7
- * never removes or changes a server in that configuration: one that exists is reported
8
- * and left as it is.
9
- */
10
-
11
- /** Runs the copilot command; AGJAN_COPILOT names a Node script that replaces it (tests). */
12
- function copilot(args) {
13
- const options = { encoding: 'utf8', timeout: 60_000 };
14
- const fake = process.env.AGJAN_COPILOT;
15
- if (fake) return spawnSync(process.execPath, [fake, ...args], options);
16
- return spawnSync('copilot', args, { ...options, shell: process.platform === 'win32' });
17
- }
18
-
19
- /** The command line that adds one server, for messages and for doing it by hand. */
20
- export function addCommand(name, server) {
21
- const env = Object.entries(server.env ?? {}).flatMap(([k, v]) => ['--env', `${k}=${v}`]);
22
- return ['copilot', 'mcp', 'add', ...env, name, '--', server.command, ...(server.args ?? [])];
23
- }
24
-
25
- /**
26
- * The servers Copilot knows (user, workspace, plugin; not its built-in ones), as
27
- * { name: { source, command, args } }, or null when copilot cannot be run.
28
- */
29
- export function copilotServers() {
30
- const run = copilot(['mcp', 'list', '--json']);
31
- if (run.error || run.status !== 0) return null;
32
- try {
33
- const list = JSON.parse(run.stdout).mcpServers ?? {};
34
- return Object.fromEntries(Object.entries(list).filter(([, s]) => s.source !== 'builtin'));
35
- } catch {
36
- return null;
37
- }
38
- }
39
-
40
- /**
41
- * Adds each server that Copilot does not know yet. Returns one result per server:
42
- * `added`, `exists` (left as it is), or `failed` with the reason.
43
- */
44
- export function addCopilotServers(servers) {
45
- const known = copilotServers();
46
- if (!known) return Object.keys(servers).map((name) => ({ name, state: 'failed', detail: 'copilot is not on PATH' }));
47
- return Object.entries(servers).map(([name, server]) => {
48
- if (known[name]) return { name, state: 'exists', detail: `already in Copilot's ${known[name].source} configuration; left as it is` };
49
- const run = copilot(addCommand(name, server).slice(1));
50
- const output = `${run.stdout ?? ''}${run.stderr ?? ''}`.trim();
51
- if (run.error || run.status !== 0 || /^Error:/m.test(output)) {
52
- return { name, state: 'failed', detail: (output.split('\n').find((l) => l.startsWith('Error:')) ?? output.split('\n')[0] ?? `exit code ${run.status}`).trim() };
53
- }
54
- return { name, state: 'added', detail: "Copilot's user configuration" };
55
- });
56
- }