@aigis-ai/cli 1.0.3 → 2.0.2

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 (47) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/README.md +58 -188
  3. package/SKILL.md +20 -55
  4. package/aigis-ai-cli-2.0.1.tgz +0 -0
  5. package/bin/aigis.js +446 -59
  6. package/content/index/audit-scan.md +21 -207
  7. package/content/index/auto-verify-rules.json +439 -0
  8. package/content/index/context-rules.json +90 -0
  9. package/content/resolvers/triggers.json +229 -0
  10. package/content/{implement → skills/areas}/audit-logging.md +5 -0
  11. package/content/skills/areas/fallback-patterns.md +200 -0
  12. package/content/skills/areas/input-validation.md +380 -0
  13. package/content/skills/areas/pii-handling.md +189 -0
  14. package/content/skills/areas/rate-limiting.md +246 -0
  15. package/content/skills/core.md +62 -0
  16. package/content/skills/infrastructure/logging.md +202 -0
  17. package/content/skills/infrastructure/rate-limiting.md +169 -0
  18. package/content/skills/infrastructure/secrets.md +167 -0
  19. package/content/skills/workflows/fastapi-llm.md +86 -0
  20. package/docs/resolvers.md +114 -0
  21. package/lib/auto-verify.js +378 -0
  22. package/lib/build.js +629 -0
  23. package/lib/checksum.js +39 -0
  24. package/lib/fetch.js +164 -9
  25. package/lib/init.js +141 -93
  26. package/lib/keywords.js +92 -130
  27. package/lib/special-recognizers.js +370 -0
  28. package/package.json +1 -1
  29. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  30. package/scripts/bootstrap-step-6-bench.js +85 -0
  31. package/scripts/check-content-sync.js +91 -0
  32. package/scripts/triggers.schema.json +50 -0
  33. package/scripts/validate-triggers.js +176 -0
  34. package/content/implement/fallback-patterns.md +0 -190
  35. package/content/implement/input-validation.md +0 -212
  36. package/content/implement/pii-handling.md +0 -207
  37. package/content/implement/rate-limiting.md +0 -217
  38. /package/content/{implement → skills/areas}/bias-monitoring.md +0 -0
  39. /package/content/{implement → skills/areas}/confidence-scoring.md +0 -0
  40. /package/content/{implement → skills/areas}/data-integrity.md +0 -0
  41. /package/content/{implement → skills/areas}/explainability.md +0 -0
  42. /package/content/{implement → skills/areas}/human-oversight.md +0 -0
  43. /package/content/{implement → skills/areas}/monitoring.md +0 -0
  44. /package/content/{implement → skills/areas}/output-sanitization.md +0 -0
  45. /package/content/{implement → skills/areas}/prompt-security.md +0 -0
  46. /package/content/{implement → skills/areas}/rag-security.md +0 -0
  47. /package/content/{implement → skills/areas}/supply-chain.md +0 -0
package/lib/build.js ADDED
@@ -0,0 +1,629 @@
1
+ /**
2
+ * `aigis build "<description>"` — Step 8.
3
+ *
4
+ * Pure functions. No I/O beyond reading the canonical content tree (which
5
+ * `lib/fetch.js` already does). The CLI wrapper in bin/aigis.js handles the
6
+ * interactive prompt loop, --confirm/--reject flags, TTY detection, and stdout.
7
+ *
8
+ * Outputs:
9
+ * - buildBrief({...}) → { brief, meta } for Shape B (default)
10
+ * - buildList({...}) → string for Shape A (--list)
11
+ *
12
+ * Design decisions worth flagging in code (see Step 8 design proposal):
13
+ * - Description is normalized (trim, collapse whitespace, strip trailing
14
+ * punctuation, lowercase) BEFORE classify and BEFORE display, so
15
+ * "Customer Chatbot" and "customer chatbot" produce byte-identical briefs.
16
+ * - Trigger IDs in the brief use a human-readable t-<slug> form (e.g.
17
+ * `t-influence`) derived from the phrase, not the numeric ids that
18
+ * `lib/keywords.js` emits. The CLI translates --confirm/--reject flag
19
+ * values back to numeric before calling applyConfirmations.
20
+ * - Uncertain traits (low-confidence triggers the user marked `unsure`, or
21
+ * the non-TTY default) are *included* in the trait set passed to classify
22
+ * — they affect area selection — and are flagged with ⚠ in the brief.
23
+ * This is a deliberate divergence from Step 6's default-reject behavior
24
+ * in `aigis classify`. See design proposal §3.
25
+ * - Hard char cap (default 20,000). Throws BriefTooLargeError; never
26
+ * produces a partial brief.
27
+ */
28
+
29
+ const fs = require('fs');
30
+ const path = require('path');
31
+ const matter = require('gray-matter');
32
+ const { classify, ALL_TRAITS } = require('./classify');
33
+ const { detectTraitsFromText, applyConfirmations } = require('./keywords');
34
+ const { get: fetchAreas, getInfra } = require('./fetch');
35
+
36
+ const CONTENT_DIR = path.join(__dirname, '..', 'content');
37
+
38
+ // Caps per mode (Step 8 design proposal addendum):
39
+ // AUTO: try full at 120k; if exceeded, silently fall back to compact.
40
+ // FULL: hard fail at 200k.
41
+ // COMPACT: no cap (it is pointer-only and small by construction).
42
+ const AUTO_FULL_CAP = 120000;
43
+ const FULL_HARD_CAP = 200000;
44
+
45
+ class BriefTooLargeError extends Error {
46
+ constructor(charCount, charCap, areas) {
47
+ super(
48
+ `Brief is ${charCount} chars; cap is ${charCap}. Your description matched ` +
49
+ `${areas.length} area${areas.length === 1 ? '' : 's'} (${areas.join(', ')}). ` +
50
+ `Try a more focused description, or split the build into per-domain runs. ` +
51
+ `To see what would be included without rendering: aigis build "..." --list`
52
+ );
53
+ this.name = 'BriefTooLargeError';
54
+ this.charCount = charCount;
55
+ this.charCap = charCap;
56
+ this.areas = areas;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Normalize a user-provided description.
62
+ * - trim leading/trailing whitespace
63
+ * - collapse runs of internal whitespace to a single space
64
+ * - strip trailing .!? punctuation
65
+ * - lowercase
66
+ *
67
+ * Determinism contract: any two inputs that normalize to the same string
68
+ * MUST produce byte-identical briefs (modulo the timestamp line, which the
69
+ * test suite masks).
70
+ */
71
+ function normalizeDescription(raw) {
72
+ if (typeof raw !== 'string') return '';
73
+ return raw
74
+ .trim()
75
+ .replace(/\s+/g, ' ')
76
+ .replace(/[.!?]+$/, '')
77
+ .toLowerCase();
78
+ }
79
+
80
+ /**
81
+ * Convert a trigger phrase into a human-readable id like `t-influence`.
82
+ * Slug rules: lowercase, non-alphanumerics → '-', collapse multiple '-',
83
+ * trim leading/trailing '-'. Max 24 chars (longer phrases get truncated
84
+ * cleanly at a word boundary).
85
+ *
86
+ * If two low-confidence triggers in the same detection produce the same
87
+ * slug, the second gets a `-2` suffix, third `-3`, etc. Caller is
88
+ * responsible for passing all slugs through assignUniqueSlugs() to handle
89
+ * collisions deterministically.
90
+ */
91
+ function phraseToSlug(phrase) {
92
+ let slug = phrase
93
+ .toLowerCase()
94
+ .replace(/[^a-z0-9]+/g, '-')
95
+ .replace(/-+/g, '-')
96
+ .replace(/^-|-$/g, '');
97
+ if (slug.length > 24) {
98
+ // truncate at the last word boundary within 24 chars
99
+ const truncated = slug.slice(0, 24);
100
+ const lastDash = truncated.lastIndexOf('-');
101
+ slug = lastDash > 0 ? truncated.slice(0, lastDash) : truncated;
102
+ }
103
+ return `t-${slug || 'trigger'}`;
104
+ }
105
+
106
+ function assignUniqueSlugs(lowConfMatches) {
107
+ // Returns parallel arrays: { numericId, slug, phrase, ... } per match.
108
+ const slugCounts = new Map();
109
+ return lowConfMatches.map((m) => {
110
+ const baseSlug = phraseToSlug(m.phrase);
111
+ const count = slugCounts.get(baseSlug) || 0;
112
+ slugCounts.set(baseSlug, count + 1);
113
+ const slug = count === 0 ? baseSlug : `${baseSlug}-${count + 1}`;
114
+ return { ...m, slug };
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Strip YAML frontmatter from a file's content. Used to inline area + infra
120
+ * markdown into the brief without per-section frontmatter noise.
121
+ */
122
+ function stripFrontmatterRaw(content) {
123
+ if (!content.startsWith('---\n')) return content.trim();
124
+ const end = content.indexOf('\n---\n', 4);
125
+ if (end === -1) return content.trim();
126
+ return content.slice(end + 5).trim();
127
+ }
128
+
129
+ /**
130
+ * Parse the "Related infrastructure" pointer block from an area's content.
131
+ * Returns the list of infra ids referenced (in order, deduped).
132
+ *
133
+ * Pointer block format (canonical, established in Step 7):
134
+ * ## Related infrastructure
135
+ *
136
+ * - `aigis infra <id>` — explanation
137
+ * - `aigis infra <id>` — explanation
138
+ *
139
+ * If an area has no such block, returns [].
140
+ */
141
+ function extractInfraReferences(areaContent) {
142
+ const infraIds = [];
143
+ const seen = new Set();
144
+ const blockMatch = areaContent.match(/##\s+Related infrastructure\s*\n([\s\S]*?)(?:\n##\s|$)/);
145
+ if (!blockMatch) return infraIds;
146
+ const lineRe = /aigis infra ([a-z0-9][a-z0-9-]*)/gi;
147
+ let m;
148
+ while ((m = lineRe.exec(blockMatch[1])) !== null) {
149
+ const id = m[1].toLowerCase();
150
+ if (!seen.has(id)) {
151
+ seen.add(id);
152
+ infraIds.push(id);
153
+ }
154
+ }
155
+ return infraIds;
156
+ }
157
+
158
+ /**
159
+ * Resolve traits + decisions into the final classify input.
160
+ *
161
+ * decisionMap shape: { '<numericId>': 'yes' | 'no' | 'unsure' }
162
+ *
163
+ * Returns:
164
+ * confirmedTraits: traits from high-confidence + low-conf with 'yes' decision
165
+ * uncertainTraits: traits from low-conf with 'unsure' decision (kept distinct
166
+ * so the brief can flag them with ⚠)
167
+ * allTraits: union — what gets passed to classify()
168
+ * userDecisions: array preserving the per-trigger decisions for display
169
+ */
170
+ function resolveTraits(detection, decisionMap, opts = {}) {
171
+ const { uncertainAsIncluded = true } = opts;
172
+
173
+ const confirmed = new Set(detection.traits_auto_applied);
174
+ const uncertain = new Set();
175
+ const userDecisions = [];
176
+
177
+ for (const sug of detection.low_confidence_matches) {
178
+ const raw = (decisionMap[sug.id] || (uncertainAsIncluded ? 'unsure' : 'no')).toLowerCase();
179
+ let decision;
180
+ if (raw === 'y' || raw === 'yes') decision = 'yes';
181
+ else if (raw === 'n' || raw === 'no') decision = 'no';
182
+ else decision = 'unsure';
183
+ userDecisions.push({ ...sug, user_decision: decision });
184
+ if (decision === 'yes') {
185
+ for (const t of sug.traits) confirmed.add(t);
186
+ } else if (decision === 'unsure') {
187
+ for (const t of sug.traits) {
188
+ if (!confirmed.has(t)) uncertain.add(t);
189
+ }
190
+ }
191
+ }
192
+
193
+ // A trait that is both confirmed and uncertain is treated as confirmed
194
+ // (high-confidence wins; the uncertain branch was redundant).
195
+ for (const t of confirmed) uncertain.delete(t);
196
+
197
+ const all = new Set([...confirmed, ...uncertain]);
198
+ return {
199
+ confirmed_traits: [...confirmed].sort(),
200
+ uncertain_traits: [...uncertain].sort(),
201
+ all_traits: [...all].sort(),
202
+ user_decisions: userDecisions,
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Shape A — `aigis build --list` output (text). Includes trigger IDs so
208
+ * users can pre-build --confirm/--reject flags without an interactive run.
209
+ */
210
+ function buildList({ description } = {}) {
211
+ const normalized = normalizeDescription(description);
212
+ if (!normalized) {
213
+ throw new Error('Provide a description in quotes. Example: aigis build "customer chatbot with RAG"');
214
+ }
215
+ const detection = detectTraitsFromText(normalized);
216
+ const lowConfWithSlugs = assignUniqueSlugs(detection.low_confidence_matches);
217
+ const detectionWithSlugs = { ...detection, low_confidence_matches: lowConfWithSlugs };
218
+ const resolved = resolveTraits(detectionWithSlugs, {}, { uncertainAsIncluded: true });
219
+ if (resolved.all_traits.length === 0) {
220
+ throw new Error('No traits resolved from description. Try a more specific description, or use `aigis classify --traits ...` directly.');
221
+ }
222
+ const cls = classify(resolved.all_traits);
223
+ const areas = cls.implement_files;
224
+
225
+ // Collect referenced infra (best-effort; missing files are skipped quietly).
226
+ const infraIds = collectInfraReferences(areas);
227
+
228
+ const lines = [];
229
+ lines.push(`Description: ${normalized}`);
230
+ lines.push(`Risk tier: ${cls.risk_tier}`);
231
+ lines.push('');
232
+ lines.push(`Confirmed traits (${resolved.confirmed_traits.length}):`);
233
+ lines.push(` ${resolved.confirmed_traits.join(', ') || '(none)'}`);
234
+ lines.push('');
235
+ lines.push(`Uncertain traits (${resolved.uncertain_traits.length}):`);
236
+ if (lowConfWithSlugs.length === 0) {
237
+ lines.push(' (none)');
238
+ } else {
239
+ for (const m of lowConfWithSlugs) {
240
+ lines.push(` [${m.slug}] ${m.traits.join(', ')} ← "${m.phrase}"`);
241
+ }
242
+ lines.push('');
243
+ lines.push(`Pre-build flags (run non-interactively):`);
244
+ const slugs = lowConfWithSlugs.map((m) => m.slug);
245
+ lines.push(` aigis build "${normalized}" --confirm ${slugs.join(',')}`);
246
+ lines.push(` aigis build "${normalized}" --reject ${slugs.join(',')}`);
247
+ }
248
+ lines.push('');
249
+ lines.push(`Recommended areas (${areas.length}):`);
250
+ for (const a of areas) lines.push(` aigis get ${a}`);
251
+ if (infraIds.length > 0) {
252
+ lines.push('');
253
+ lines.push(`Referenced infrastructure (${infraIds.length}):`);
254
+ for (const i of infraIds) lines.push(` aigis infra ${i}`);
255
+ }
256
+ if (cls.templates.length > 0) {
257
+ lines.push('');
258
+ lines.push(`Documentation templates (${cls.templates.length}):`);
259
+ for (const t of cls.templates) lines.push(` aigis template ${t}`);
260
+ }
261
+ return lines.join('\n') + '\n';
262
+ }
263
+
264
+ function collectInfraReferences(areas) {
265
+ const infraIds = [];
266
+ const seen = new Set();
267
+ for (const area of areas) {
268
+ let content;
269
+ try {
270
+ content = fs.readFileSync(path.join(CONTENT_DIR, 'skills', 'areas', `${area}.md`), 'utf8');
271
+ } catch (_) {
272
+ continue; // missing area file — caller will surface this elsewhere
273
+ }
274
+ for (const id of extractInfraReferences(content)) {
275
+ if (!seen.has(id)) {
276
+ seen.add(id);
277
+ infraIds.push(id);
278
+ }
279
+ }
280
+ }
281
+ return infraIds;
282
+ }
283
+
284
+ /**
285
+ * Read the YAML frontmatter `title` field from an area or infra file.
286
+ * Returns the file id as fallback if no title is set or the file is unreadable.
287
+ */
288
+ function readTitle(subdir, id) {
289
+ try {
290
+ const raw = fs.readFileSync(path.join(CONTENT_DIR, subdir, `${id}.md`), 'utf8');
291
+ const parsed = matter(raw);
292
+ return parsed.data && parsed.data.title ? String(parsed.data.title) : id;
293
+ } catch (_) {
294
+ return id;
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Shared header + instructions + verification — used by both full and compact
300
+ * briefs. Returns an array of section strings (joined with '\n' by the caller).
301
+ */
302
+ function renderCommonSections({
303
+ normalized, version, ts, modeNote, cls, resolved, areas, infraIds,
304
+ }) {
305
+ const sections = [];
306
+
307
+ sections.push(`# Aigis governance brief`);
308
+ sections.push('');
309
+ sections.push(`> Generated by \`aigis build "${normalized}"\``);
310
+ sections.push(`> aigis ${version} — generated ${ts}`);
311
+ if (modeNote) sections.push(`> ${modeNote}`);
312
+ sections.push(`> Determinism note: same description + same trait decisions produces byte-identical brief (timestamp masked).`);
313
+ sections.push('');
314
+
315
+ sections.push(`## Input`);
316
+ sections.push('');
317
+ sections.push(`- Description: \`${normalized}\``);
318
+ sections.push(`- Risk tier: **${cls.risk_tier}** _(${cls.reason})_`);
319
+ sections.push(`- Confirmed traits (${resolved.confirmed_traits.length}): ${resolved.confirmed_traits.map((t) => `\`${t}\``).join(', ') || '(none)'}`);
320
+ if (resolved.uncertain_traits.length > 0) {
321
+ sections.push(`- Uncertain traits (${resolved.uncertain_traits.length}, marked ⚠ in this brief):`);
322
+ for (const t of resolved.uncertain_traits) {
323
+ sections.push(` - ⚠ \`${t}\` — surfaced from a low-confidence trigger; treat as *possibly applicable*. Ask the user before assuming.`);
324
+ }
325
+ } else {
326
+ sections.push(`- Uncertain traits (0)`);
327
+ }
328
+ sections.push('');
329
+
330
+ sections.push(`## Instructions for the agent`);
331
+ sections.push('');
332
+ sections.push(`The following are governance areas Aigis identified based on the description above. **Treat them as a starting point, not a closed list.**`);
333
+ sections.push('');
334
+ sections.push(`1. Verify these match your understanding of *this* codebase before implementing. If any area clearly does not apply (e.g. \`pii-handling\` for a system that genuinely handles no user data), say so to the user and skip it with a written reason.`);
335
+ sections.push(`2. If the codebase reveals concerns Aigis missed (a webhook surface, a privileged tool the LLM can call, a regulated jurisdiction), add the matching area. Run \`aigis search --list\` to see what's available.`);
336
+ sections.push(`3. For each area below, follow the procedure step by step. Honor every **verification checkpoint** — those are not suggestions.`);
337
+ sections.push(`4. Run \`aigis verify <area> --auto .\` after implementing each area. Fix any FAIL or OVERCLAIM before moving on.`);
338
+ sections.push(`5. For uncertain traits (⚠ above), pause before implementing the dependent area and ask the user to confirm it applies.`);
339
+ sections.push('');
340
+
341
+ return sections;
342
+ }
343
+
344
+ function renderVerificationSection({ areas, resolved, cls }) {
345
+ const sections = [];
346
+ sections.push(`## Verification`);
347
+ sections.push('');
348
+ sections.push(`After implementing the areas above, the agent should confirm:`);
349
+ sections.push('');
350
+ sections.push(`- [ ] Every area's verification checkpoints pass.`);
351
+ for (const area of areas) {
352
+ sections.push(`- [ ] \`aigis verify ${area} --auto .\` returns no FAIL or OVERCLAIM.`);
353
+ }
354
+ sections.push(`- [ ] If any area was added or removed from the recommended set, document the reason in the PR description.`);
355
+ if (resolved.uncertain_traits.length > 0) {
356
+ sections.push(`- [ ] Uncertain trait${resolved.uncertain_traits.length === 1 ? '' : 's'} (${resolved.uncertain_traits.map((t) => `\`${t}\``).join(', ')}) confirmed or rejected with the user before relevant code paths shipped.`);
357
+ }
358
+ if (cls.templates.length > 0) {
359
+ sections.push(`- [ ] Documentation templates generated:`);
360
+ for (const t of cls.templates) {
361
+ sections.push(` - [ ] \`aigis template ${t}\``);
362
+ }
363
+ }
364
+ sections.push('');
365
+ sections.push(`---`);
366
+ sections.push('');
367
+ sections.push(`*Generated by aigis. This brief is content, not a scaffold — Aigis writes nothing into your project. The agent and the user remain responsible for what ships.*`);
368
+ sections.push('');
369
+ return sections;
370
+ }
371
+
372
+ /**
373
+ * Compact mode — pointer-only brief. ~3-5k chars regardless of area count.
374
+ * Used when --compact is passed, or as the auto-fallback when the full brief
375
+ * would exceed AUTO_FULL_CAP.
376
+ */
377
+ function buildCompact({
378
+ description,
379
+ decisions = {},
380
+ timestamp = null,
381
+ versionString = null,
382
+ fellBackFromFull = false, // if true, header notes the auto-fallback
383
+ } = {}) {
384
+ const prep = prepareBriefInputs({ description, decisions });
385
+ const { normalized, resolved, cls, areas, infraIds, lowConfWithSlugs } = prep;
386
+ const ts = (timestamp || new Date()).toISOString();
387
+ const version = versionString || readPackageVersion();
388
+
389
+ const modeNote = fellBackFromFull
390
+ ? `Compact mode (auto-fallback): full brief would exceed ${AUTO_FULL_CAP.toLocaleString()} chars. Run \`aigis build "${normalized}" --full\` to force inlined content; you may need to split into per-domain runs.`
391
+ : `Compact mode: pointer-only. Run \`aigis build "${normalized}" --full\` to inline procedure content.`;
392
+
393
+ const sections = renderCommonSections({ normalized, version, ts, modeNote, cls, resolved, areas, infraIds });
394
+
395
+ // ─── Areas (pointers) ──────────────────────────────────────────────────
396
+ sections.push(`## Areas (${areas.length})`);
397
+ sections.push('');
398
+ sections.push(`For each area below, run \`aigis get <area>\` to fetch the full procedure, then implement step by step. Run \`aigis verify <area> --auto .\` after.`);
399
+ sections.push('');
400
+ let i = 1;
401
+ for (const area of areas) {
402
+ const title = readTitle(path.join('skills', 'areas'), area);
403
+ sections.push(`${i}. **${area}** — ${title}`);
404
+ sections.push(` - Fetch: \`aigis get ${area}\``);
405
+ sections.push(` - Verify: \`aigis verify ${area} --auto .\``);
406
+ i++;
407
+ }
408
+ sections.push('');
409
+
410
+ // ─── Infrastructure (pointers) ─────────────────────────────────────────
411
+ if (infraIds.length > 0) {
412
+ sections.push(`## Infrastructure (${infraIds.length})`);
413
+ sections.push('');
414
+ sections.push(`The areas above reference these infrastructure files. Fetch as needed:`);
415
+ sections.push('');
416
+ for (const id of infraIds) {
417
+ const title = readTitle(path.join('skills', 'infrastructure'), id);
418
+ sections.push(`- \`aigis infra ${id}\` — ${title}`);
419
+ }
420
+ sections.push('');
421
+ }
422
+
423
+ sections.push(...renderVerificationSection({ areas, resolved, cls }));
424
+
425
+ const brief = sections.join('\n');
426
+ return {
427
+ brief,
428
+ meta: makeMeta({ prep, brief, mode: 'compact', cap: null, ts, version, fellBackFromFull }),
429
+ };
430
+ }
431
+
432
+ /**
433
+ * Shape B — full consolidated brief with inlined area + infra content.
434
+ */
435
+ function buildFull({
436
+ description,
437
+ decisions = {},
438
+ charCap = FULL_HARD_CAP, // dispatcher overrides this to AUTO_FULL_CAP for auto mode
439
+ timestamp = null,
440
+ versionString = null,
441
+ } = {}) {
442
+ const prep = prepareBriefInputs({ description, decisions });
443
+ const { normalized, resolved, cls, areas, infraIds, lowConfWithSlugs } = prep;
444
+ const ts = (timestamp || new Date()).toISOString();
445
+ const version = versionString || readPackageVersion();
446
+
447
+ const sections = renderCommonSections({ normalized, version, ts, modeNote: null, cls, resolved, areas, infraIds });
448
+
449
+ // ─── Areas (inlined) ───────────────────────────────────────────────────
450
+ sections.push(`## Areas`);
451
+ sections.push('');
452
+ let i = 1;
453
+ for (const area of areas) {
454
+ let raw;
455
+ try {
456
+ raw = fs.readFileSync(path.join(CONTENT_DIR, 'skills', 'areas', `${area}.md`), 'utf8');
457
+ } catch (_) {
458
+ continue;
459
+ }
460
+ const stripped = stripFrontmatterRaw(raw);
461
+ sections.push(`### ${i}. ${area}`);
462
+ sections.push('');
463
+ sections.push(stripped);
464
+ sections.push('');
465
+ sections.push('---');
466
+ sections.push('');
467
+ i++;
468
+ }
469
+
470
+ // ─── Infrastructure (inlined) ──────────────────────────────────────────
471
+ if (infraIds.length > 0) {
472
+ sections.push(`## Infrastructure`);
473
+ sections.push('');
474
+ sections.push(`The areas above reference these infrastructure files. Apply whichever shape (from-scratch / existing) matches the project.`);
475
+ sections.push('');
476
+ for (const id of infraIds) {
477
+ let raw;
478
+ try {
479
+ raw = getInfra(id);
480
+ } catch (_) {
481
+ continue;
482
+ }
483
+ const stripped = stripFrontmatterRaw(raw);
484
+ sections.push(`### ${id}`);
485
+ sections.push('');
486
+ sections.push(stripped);
487
+ sections.push('');
488
+ sections.push('---');
489
+ sections.push('');
490
+ }
491
+ }
492
+
493
+ sections.push(...renderVerificationSection({ areas, resolved, cls }));
494
+
495
+ const brief = sections.join('\n');
496
+
497
+ if (brief.length > charCap) {
498
+ throw new BriefTooLargeError(brief.length, charCap, areas);
499
+ }
500
+
501
+ return {
502
+ brief,
503
+ meta: makeMeta({ prep, brief, mode: 'full', cap: charCap, ts, version, fellBackFromFull: false }),
504
+ };
505
+ }
506
+
507
+ /**
508
+ * Dispatcher. mode = 'auto' (default) | 'full' | 'compact'.
509
+ *
510
+ * auto: try buildFull at AUTO_FULL_CAP; on overflow, fall back to compact
511
+ * with a stderr-bound warning (caller renders the warning).
512
+ * full: buildFull at FULL_HARD_CAP. Throws BriefTooLargeError on overflow.
513
+ * compact: buildCompact (no cap concern).
514
+ */
515
+ function buildBrief(opts = {}) {
516
+ const mode = opts.mode || 'auto';
517
+ if (mode === 'compact') {
518
+ return { ...buildCompact(opts), mode: 'compact', auto_fallback: false };
519
+ }
520
+ if (mode === 'full') {
521
+ return { ...buildFull({ ...opts, charCap: FULL_HARD_CAP }), mode: 'full', auto_fallback: false };
522
+ }
523
+ // auto
524
+ try {
525
+ const result = buildFull({ ...opts, charCap: AUTO_FULL_CAP });
526
+ return { ...result, mode: 'full', auto_fallback: false };
527
+ } catch (e) {
528
+ if (!(e instanceof BriefTooLargeError)) throw e;
529
+ const compact = buildCompact({ ...opts, fellBackFromFull: true });
530
+ return {
531
+ ...compact,
532
+ mode: 'compact',
533
+ auto_fallback: true,
534
+ auto_fallback_full_chars: e.charCount,
535
+ auto_fallback_full_cap: e.charCap,
536
+ };
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Shared input prep used by buildFull, buildCompact, and buildList. Centralizes
542
+ * the normalize → detect → slug → resolve → classify pipeline so all three modes
543
+ * see the same trait/area/infra outputs given the same input.
544
+ */
545
+ function prepareBriefInputs({ description, decisions = {} }) {
546
+ const normalized = normalizeDescription(description);
547
+ if (!normalized) {
548
+ throw new Error('Provide a description in quotes. Example: aigis build "customer chatbot with RAG"');
549
+ }
550
+ const detection = detectTraitsFromText(normalized);
551
+ const lowConfWithSlugs = assignUniqueSlugs(detection.low_confidence_matches);
552
+ const detectionWithSlugs = { ...detection, low_confidence_matches: lowConfWithSlugs };
553
+
554
+ // Translate slug-keyed decisions back to numeric ids (CLI accepts both).
555
+ const numericDecisions = {};
556
+ for (const m of lowConfWithSlugs) {
557
+ if (decisions[m.slug] != null) numericDecisions[m.id] = decisions[m.slug];
558
+ else if (decisions[m.id] != null) numericDecisions[m.id] = decisions[m.id];
559
+ }
560
+
561
+ const resolved = resolveTraits(detectionWithSlugs, numericDecisions, { uncertainAsIncluded: true });
562
+ if (resolved.all_traits.length === 0) {
563
+ throw new Error('No traits resolved from description. Try a more specific description, or use `aigis classify --traits ...` directly.');
564
+ }
565
+
566
+ const cls = classify(resolved.all_traits);
567
+ const areas = cls.implement_files;
568
+ const infraIds = collectInfraReferences(areas);
569
+
570
+ return { normalized, raw_input: description, detection, lowConfWithSlugs, resolved, cls, areas, infraIds };
571
+ }
572
+
573
+ function makeMeta({ prep, brief, mode, cap, ts, version, fellBackFromFull }) {
574
+ const { normalized, raw_input, resolved, cls, areas, infraIds, lowConfWithSlugs } = prep;
575
+ return {
576
+ mode,
577
+ auto_fallback: fellBackFromFull,
578
+ normalized_description: normalized,
579
+ input_was_normalized: normalized !== raw_input,
580
+ raw_input,
581
+ confirmed_traits: resolved.confirmed_traits,
582
+ uncertain_traits: resolved.uncertain_traits,
583
+ all_traits: resolved.all_traits,
584
+ risk_tier: cls.risk_tier,
585
+ areas,
586
+ infra: infraIds,
587
+ templates: cls.templates,
588
+ char_count: brief.length,
589
+ char_cap: cap,
590
+ low_confidence_matches: lowConfWithSlugs.map((m) => ({
591
+ slug: m.slug,
592
+ phrase: m.phrase,
593
+ traits: m.traits,
594
+ confirmation_prompt: m.confirmation_prompt,
595
+ notes: m.notes,
596
+ })),
597
+ user_decisions: resolved.user_decisions,
598
+ generated_at: ts,
599
+ version,
600
+ };
601
+ }
602
+
603
+ let _cachedVersion = null;
604
+ function readPackageVersion() {
605
+ if (_cachedVersion) return _cachedVersion;
606
+ try {
607
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
608
+ _cachedVersion = pkg.version || 'unknown';
609
+ } catch (_) {
610
+ _cachedVersion = 'unknown';
611
+ }
612
+ return _cachedVersion;
613
+ }
614
+
615
+ module.exports = {
616
+ buildBrief,
617
+ buildFull,
618
+ buildCompact,
619
+ buildList,
620
+ normalizeDescription,
621
+ phraseToSlug,
622
+ assignUniqueSlugs,
623
+ resolveTraits,
624
+ extractInfraReferences,
625
+ collectInfraReferences,
626
+ BriefTooLargeError,
627
+ AUTO_FULL_CAP,
628
+ FULL_HARD_CAP,
629
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Deterministic file checksum for Aigis content artifacts.
3
+ *
4
+ * Algorithm (locked, documented so it's reproducible from this spec):
5
+ * 1. Read the file as UTF-8 bytes.
6
+ * 2. Strip a leading UTF-8 BOM (\uFEFF) if present.
7
+ * 3. Normalize line endings: convert CRLF and lone CR to LF.
8
+ * 4. SHA-256 the resulting bytes.
9
+ * 5. Return the lowercase hex digest.
10
+ *
11
+ * Why canonicalize: the checksum gets written into IDE rules files and
12
+ * compared on subsequent invocations of `aigis init`. Editors / git-attribute
13
+ * settings can flip line endings or insert BOMs without the user noticing,
14
+ * which would otherwise produce spurious mismatches.
15
+ */
16
+
17
+ const fs = require('fs');
18
+ const crypto = require('crypto');
19
+
20
+ function canonicalizeBytes(text) {
21
+ // Strip leading BOM
22
+ if (text.charCodeAt(0) === 0xFEFF) {
23
+ text = text.slice(1);
24
+ }
25
+ // CRLF and lone CR → LF
26
+ return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
27
+ }
28
+
29
+ function computeChecksum(text) {
30
+ const canonical = canonicalizeBytes(text);
31
+ return crypto.createHash('sha256').update(canonical, 'utf8').digest('hex');
32
+ }
33
+
34
+ function computeFileChecksum(filepath) {
35
+ const text = fs.readFileSync(filepath, 'utf8');
36
+ return computeChecksum(text);
37
+ }
38
+
39
+ module.exports = { computeChecksum, computeFileChecksum, canonicalizeBytes };