@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/fetch.js CHANGED
@@ -26,15 +26,139 @@ function stripFrontmatter(content) {
26
26
  return parsed.content.trim();
27
27
  }
28
28
 
29
+ // Canonical language names → the list of fenced-block tags that should be KEPT
30
+ // for that language. Lookup is case-insensitive after normalization.
31
+ // Aliases (py, js, ts) resolve to the same canonical as their full names.
32
+ const LANG_ALIASES = {
33
+ py: 'python', python: 'python',
34
+ js: 'javascript', javascript: 'javascript', node: 'javascript',
35
+ ts: 'typescript', typescript: 'typescript',
36
+ go: 'go', golang: 'go',
37
+ rust: 'rust', rs: 'rust',
38
+ };
39
+ // What fenced-tag to treat as "the same language" for each canonical.
40
+ // TypeScript keeps both ts and js fences since the content currently only
41
+ // ships js examples (ts callers still benefit).
42
+ const LANG_FENCE_KEEPS = {
43
+ python: ['python', 'py'],
44
+ javascript: ['javascript', 'js', 'node'],
45
+ typescript: ['typescript', 'ts', 'javascript', 'js'],
46
+ go: ['go'],
47
+ rust: ['rust', 'rs'],
48
+ };
49
+ // All fence tags recognized as "a code language we might filter".
50
+ const ALL_LANG_FENCES = new Set(['python', 'py', 'javascript', 'js', 'node', 'typescript', 'ts', 'go', 'rust', 'rs']);
51
+
52
+ function canonicalizeLang(lang) {
53
+ if (!lang) return null;
54
+ const normalized = lang.toLowerCase();
55
+ const canonical = LANG_ALIASES[normalized];
56
+ if (!canonical) {
57
+ throw new Error(`Unknown language "${lang}". Known: py, python, js, javascript, ts, typescript, go, rust.`);
58
+ }
59
+ return canonical;
60
+ }
61
+
62
+ /**
63
+ * Filter fenced code blocks by language. Keeps blocks whose fence tag is in
64
+ * LANG_FENCE_KEEPS[canonical]. Removes blocks whose fence tag is in
65
+ * ALL_LANG_FENCES but not in the keep list. Blocks with tags we don't
66
+ * recognize (or no tag at all) are always preserved — prose remains untouched.
67
+ *
68
+ * Trailing blank lines left by a removed block are collapsed so the output
69
+ * reads naturally when the agent consumes it.
70
+ */
29
71
  function filterLanguage(content, lang) {
30
- if (!lang) return content;
72
+ const canonical = canonicalizeLang(lang);
73
+ if (!canonical) return content;
74
+ const keepSet = new Set(LANG_FENCE_KEEPS[canonical]);
75
+
76
+ // Match ```<tag>...\n<body>\n``` blocks. The tag is captured in group 1.
77
+ const blockRe = /^```([A-Za-z0-9_+-]*)\s*\n[\s\S]*?^```\s*$\n?/gm;
78
+ let out = content.replace(blockRe, (match, tag) => {
79
+ const lowerTag = (tag || '').toLowerCase();
80
+ // Unknown tags (empty, bash, shell, json, etc.) always preserved
81
+ if (!ALL_LANG_FENCES.has(lowerTag)) return match;
82
+ // Language-tagged block: keep or drop based on the language filter
83
+ return keepSet.has(lowerTag) ? match : '';
84
+ });
85
+
86
+ // Collapse 3+ consecutive blank lines to 2 (from removed blocks)
87
+ out = out.replace(/\n{3,}/g, '\n\n');
88
+ return out;
89
+ }
90
+
91
+ // ─── Context filter ────────────────────────────────────────────────────
92
+ // Manifest-driven. The rules file lives at content/index/context-rules.json
93
+ // and declares, per-file, which patterns apply to which contexts. Patterns
94
+ // not listed in the manifest are always preserved.
95
+
96
+ const VALID_CONTEXTS = new Set(['web', 'agentic', 'rag', 'batch']);
97
+ let _contextRulesCache = null;
98
+
99
+ function loadContextRules() {
100
+ if (_contextRulesCache) return _contextRulesCache;
101
+ const rulesPath = path.join(CONTENT_DIR, 'index', 'context-rules.json');
102
+ if (!fs.existsSync(rulesPath)) {
103
+ _contextRulesCache = { rules: [] };
104
+ return _contextRulesCache;
105
+ }
106
+ const raw = JSON.parse(fs.readFileSync(rulesPath, 'utf8'));
107
+ _contextRulesCache = raw;
108
+ return raw;
109
+ }
110
+
111
+ function canonicalizeContext(context) {
112
+ if (!context) return null;
113
+ const normalized = context.toLowerCase();
114
+ if (!VALID_CONTEXTS.has(normalized)) {
115
+ throw new Error(`Unknown context "${context}". Known: web, agentic, rag, batch.`);
116
+ }
117
+ return normalized;
118
+ }
119
+
120
+ /**
121
+ * Given the full markdown content of an implement file, remove pattern
122
+ * subsections whose heading is listed in the context rules with contexts
123
+ * that do NOT include the requested context. A "pattern subsection" is a
124
+ * `### Pattern N:` level-3 heading and everything until the next `### ` at
125
+ * the same level (or the next `## ` section boundary, or EOF).
126
+ *
127
+ * Pattern headings with no rule in the manifest are preserved unconditionally.
128
+ */
129
+ function filterContext(content, context, fileId) {
130
+ const canonical = canonicalizeContext(context);
131
+ if (!canonical) return content;
132
+
133
+ const rules = loadContextRules().rules || [];
134
+ const fileRules = rules.filter((r) => r.file === fileId);
135
+ if (fileRules.length === 0) return content;
136
+
137
+ const lines = content.split('\n');
138
+ const keepLines = new Array(lines.length).fill(true);
31
139
 
32
- const keep = lang === 'py' ? 'python' : 'javascript';
33
- const remove = lang === 'py' ? 'javascript' : 'python';
140
+ for (const rule of fileRules) {
141
+ if (rule.contexts.includes(canonical)) continue; // pattern applies; keep
142
+ // Find the heading line that starts with the prefix
143
+ const headerRe = new RegExp('^###\\s+' + escapeRegex(rule.pattern_heading_prefix) + '\\b');
144
+ for (let i = 0; i < lines.length; i++) {
145
+ if (!headerRe.test(lines[i])) continue;
146
+ // Mark lines from header until next ### or ## or EOF for removal
147
+ let j = i;
148
+ while (j < lines.length) {
149
+ if (j > i && /^(##\s|###\s)/.test(lines[j])) break;
150
+ keepLines[j] = false;
151
+ j++;
152
+ }
153
+ }
154
+ }
34
155
 
35
- // Remove code blocks of the unwanted language
36
- const regex = new RegExp('```' + remove + '[\\s\\S]*?```\\n?', 'g');
37
- return content.replace(regex, '');
156
+ const filtered = lines.filter((_, i) => keepLines[i]).join('\n');
157
+ return filtered.replace(/\n{3,}/g, '\n\n');
158
+ }
159
+
160
+ function escapeRegex(s) {
161
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
38
162
  }
39
163
 
40
164
  function appendAnnotations(content, fileId) {
@@ -50,7 +174,7 @@ function appendAnnotations(content, fileId) {
50
174
 
51
175
  function get(fileIds, opts = {}) {
52
176
  if (opts.all) {
53
- fileIds = listDir('implement');
177
+ fileIds = listDir('skills/areas');
54
178
  }
55
179
 
56
180
  if (!fileIds || fileIds.length === 0) {
@@ -59,7 +183,7 @@ function get(fileIds, opts = {}) {
59
183
 
60
184
  const outputs = [];
61
185
  for (const id of fileIds) {
62
- let content = readFile('implement', id);
186
+ let content = readFile('skills/areas', id);
63
187
 
64
188
  if (opts.frontmatter === false) {
65
189
  content = stripFrontmatter(content);
@@ -69,6 +193,10 @@ function get(fileIds, opts = {}) {
69
193
  content = filterLanguage(content, opts.lang);
70
194
  }
71
195
 
196
+ if (opts.context) {
197
+ content = filterContext(content, opts.context, id);
198
+ }
199
+
72
200
  content = appendAnnotations(content, id);
73
201
  outputs.push(content);
74
202
  }
@@ -109,4 +237,31 @@ function getAuditScan() {
109
237
  return readFile('index', 'audit-scan');
110
238
  }
111
239
 
112
- module.exports = { get, verify, getTemplate, getAuditScan, readFile, listDir };
240
+ function getCore() {
241
+ return readFile('skills', 'core');
242
+ }
243
+
244
+ function getWorkflow(type) {
245
+ if (!type) {
246
+ throw new Error('Provide a workflow type. Run "aigis workflow --list" to see available workflows.');
247
+ }
248
+ return readFile('skills/workflows', type);
249
+ }
250
+
251
+ function listWorkflows() {
252
+ return listDir('skills/workflows');
253
+ }
254
+
255
+ function getInfra(area) {
256
+ if (!area) {
257
+ throw new Error('Provide an infrastructure area. Run "aigis infra --list" to see available areas.');
258
+ }
259
+ return readFile('skills/infrastructure', area);
260
+ }
261
+
262
+ function listInfras() {
263
+ // Sort case-insensitively so output is stable regardless of filesystem listing order.
264
+ return listDir('skills/infrastructure').sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
265
+ }
266
+
267
+ module.exports = { get, verify, getTemplate, getAuditScan, getCore, getWorkflow, listWorkflows, getInfra, listInfras, readFile, listDir };
package/lib/init.js CHANGED
@@ -1,125 +1,173 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
3
  const chalk = require('chalk');
4
+ const { getCore } = require('./fetch');
5
+ const { loadTriggers, TRIGGERS_PATH } = require('./keywords');
6
+ const { computeFileChecksum } = require('./checksum');
4
7
 
5
- const CURSOR_RULES = `# Aigis AI Governance
6
- # Added by: aigis init cursor
7
- # Docs: https://github.com/aigis-ai/aigis
8
+ const HEADER = `# Aigis core skill — installed by \`aigis init\`
9
+ # Re-run \`aigis init <ide>\` to refresh this file when Aigis updates.
10
+ # Area + workflow skills load on demand via the aigis CLI; they are NOT in this file.
8
11
 
9
- When building any AI or LLM feature, use the aigis CLI for governance patterns:
10
-
11
- 1. Before writing LLM code, classify the system:
12
- Run: aigis classify --traits <relevant-traits> --json
13
-
14
- 2. For EACH recommended file in implement_files, work one at a time:
15
- a) Fetch one file:
16
- Run: aigis get <file-id>
17
- b) Implement the patterns in code
18
- c) Verify that same file:
19
- Run: aigis verify <file-id>
20
- d) Fix FAIL/PARTIAL items until all checks pass
21
- e) Move to the next file
12
+ `;
22
13
 
23
- 3. After all files pass, generate compliance docs:
24
- Run: aigis template <template-id>
14
+ const RESOLVER_BLOCK_START = (checksum) =>
15
+ `# --- AIGIS RESOLVER BLOCK START (checksum: ${checksum}) ---`;
16
+ const RESOLVER_BLOCK_END = `# --- AIGIS RESOLVER BLOCK END ---`;
17
+ const RESOLVER_BLOCK_RE = /# --- AIGIS RESOLVER BLOCK START \(checksum: ([a-f0-9]+)\) ---[\s\S]*?# --- AIGIS RESOLVER BLOCK END ---/m;
25
18
 
26
- IMPORTANT: Do NOT fetch all implement files at once. Work through them one at a time. Implement fully and verify before moving to the next.
19
+ const IDE_DESTINATIONS = {
20
+ cursor: { file: '.cursorrules', description: 'Cursor rules file', instruction: 'Cursor will read these instructions on every interaction in this project.' },
21
+ windsurf: { file: '.windsurfrules', description: 'Windsurf rules file', instruction: 'Windsurf will read these instructions on every interaction in this project.' },
22
+ copilot: { file: '.github/copilot-instructions.md', description: 'GitHub Copilot instructions', instruction: 'Copilot will read these instructions for this repository.' },
23
+ 'claude-code': { file: null, description: 'Claude Code skill file', instruction: 'Claude Code will read this skill file. Restart Claude Code for it to take effect.' },
24
+ };
27
25
 
28
- 4. To audit an existing project:
29
- Run: aigis audit --scan
26
+ /**
27
+ * Render the resolver block as a human-readable markdown table the agent can
28
+ * consume directly. Format is deterministic: alphabetical row order within
29
+ * each tier, fixed column widths, no trailing whitespace.
30
+ */
31
+ function renderResolverBlock(checksum) {
32
+ const triggers = loadTriggers();
33
+
34
+ const lines = [];
35
+ lines.push(RESOLVER_BLOCK_START(checksum));
36
+ lines.push(`# Generated by \`aigis init\` from content/resolvers/triggers.json (version ${triggers.version}).`);
37
+ lines.push(`# Do not edit manually. Run \`aigis init <ide> --refresh\` to regenerate after Aigis updates.`);
38
+ lines.push(`#`);
39
+ lines.push(`# When the user describes their project in natural language, scan the description`);
40
+ lines.push(`# for the phrases below.`);
41
+ lines.push(`#`);
42
+ lines.push(`# HIGH-CONFIDENCE: apply the listed traits directly.`);
43
+ lines.push(`# LOW-CONFIDENCE: ask the user the listed clarifying question; apply the trait`);
44
+ lines.push(`# only if they confirm "yes". Default to "no" if the user is`);
45
+ lines.push(`# unsure. Record "unsure" answers distinctly from "no" so future`);
46
+ lines.push(`# iterations can ask again.`);
47
+ lines.push('');
48
+ lines.push('## High-confidence triggers (auto-apply)');
49
+ lines.push('');
50
+
51
+ const hiKeys = Object.keys(triggers.high_confidence);
52
+ const phraseW = Math.max(6, ...hiKeys.map((k) => k.length));
53
+ const traitsW = Math.max(6, ...hiKeys.map((k) => triggers.high_confidence[k].traits.join(', ').length));
54
+ lines.push(`| ${'Phrase'.padEnd(phraseW)} | ${'Traits'.padEnd(traitsW)} |`);
55
+ lines.push(`|${'-'.repeat(phraseW + 2)}|${'-'.repeat(traitsW + 2)}|`);
56
+ for (const k of hiKeys) {
57
+ lines.push(`| ${k.padEnd(phraseW)} | ${triggers.high_confidence[k].traits.join(', ').padEnd(traitsW)} |`);
58
+ }
30
59
 
31
- Available traits: uses-llm, uses-rag, uses-finetuned, uses-thirdparty-api, is-agentic, is-multimodal, processes-pii, handles-financial, handles-health, handles-proprietary, handles-minors, influences-decisions, accepts-user-input, is-external, is-internal, is-high-volume, generates-code, generates-content, multi-model-pipeline, jurisdiction-eu, jurisdiction-us-regulated, jurisdiction-global
60
+ lines.push('');
61
+ lines.push('## Low-confidence triggers (confirm with user before applying)');
62
+ lines.push('');
63
+
64
+ const loKeys = Object.keys(triggers.low_confidence);
65
+ const lpW = Math.max(6, ...loKeys.map((k) => k.length));
66
+ const ltW = Math.max(6, ...loKeys.map((k) => triggers.low_confidence[k].traits.join(', ').length));
67
+ // Question column kept compact — the full prompt is long; we render the trailing
68
+ // question only (sentence between "You mentioned X." and the "(yes / no / unsure)" suffix).
69
+ function shortQuestion(prompt) {
70
+ const m = prompt.match(/^You mentioned [^.]+\.\s*(.+?)\s*\(yes \/ no \/ unsure\)\s*$/);
71
+ return m ? m[1] : prompt;
72
+ }
73
+ const askW = Math.max(6, ...loKeys.map((k) => shortQuestion(triggers.low_confidence[k].confirmation_prompt).length));
74
+ lines.push(`| ${'Phrase'.padEnd(lpW)} | ${'Traits'.padEnd(ltW)} | ${'Ask the user'.padEnd(askW)} |`);
75
+ lines.push(`|${'-'.repeat(lpW + 2)}|${'-'.repeat(ltW + 2)}|${'-'.repeat(askW + 2)}|`);
76
+ for (const k of loKeys) {
77
+ const e = triggers.low_confidence[k];
78
+ lines.push(`| ${k.padEnd(lpW)} | ${e.traits.join(', ').padEnd(ltW)} | ${shortQuestion(e.confirmation_prompt).padEnd(askW)} |`);
79
+ }
32
80
 
33
- Run "aigis search --list" to see all available governance patterns.
34
- Run "aigis traits" to see trait descriptions.
35
- `;
81
+ lines.push('');
82
+ lines.push(RESOLVER_BLOCK_END);
83
+ return lines.join('\n');
84
+ }
36
85
 
37
- const WINDSURF_RULES = CURSOR_RULES;
38
-
39
- const COPILOT_INSTRUCTIONS = CURSOR_RULES;
40
-
41
- const CLAUDE_CODE_SKILL = fs.readFileSync(
42
- path.join(__dirname, '..', 'SKILL.md'),
43
- 'utf8'
44
- );
45
-
46
- const IDE_CONFIG = {
47
- cursor: {
48
- file: '.cursorrules',
49
- content: CURSOR_RULES,
50
- description: 'Cursor rules file',
51
- instruction: 'Cursor will read these instructions on every interaction in this project.',
52
- },
53
- windsurf: {
54
- file: '.windsurfrules',
55
- content: WINDSURF_RULES,
56
- description: 'Windsurf rules file',
57
- instruction: 'Windsurf will read these instructions on every interaction in this project.',
58
- },
59
- copilot: {
60
- file: '.github/copilot-instructions.md',
61
- content: COPILOT_INSTRUCTIONS,
62
- description: 'GitHub Copilot instructions',
63
- instruction: 'Copilot will read these instructions for this repository.',
64
- },
65
- 'claude-code': {
66
- file: null, // Special handling
67
- content: CLAUDE_CODE_SKILL,
68
- description: 'Claude Code skill file',
69
- instruction: null,
70
- },
71
- };
86
+ function buildFullContent() {
87
+ const checksum = computeFileChecksum(TRIGGERS_PATH);
88
+ const block = renderResolverBlock(checksum);
89
+ return { content: HEADER + getCore() + '\n\n' + block + '\n', checksum };
90
+ }
72
91
 
73
- function init(ide) {
92
+ function init(ide, opts = {}) {
74
93
  const ideLower = ide.toLowerCase();
75
- const config = IDE_CONFIG[ideLower];
76
-
77
- if (!config) {
94
+ const dest = IDE_DESTINATIONS[ideLower];
95
+ if (!dest) {
78
96
  console.error(chalk.red(`Unknown IDE: ${ide}`));
79
97
  console.log(chalk.dim('Available: cursor, claude-code, windsurf, copilot\n'));
80
98
  process.exit(1);
81
99
  }
82
100
 
83
- // Claude Code has a special setup path
101
+ const { content, checksum } = buildFullContent();
102
+
103
+ // Claude Code: dedicated skill dir
84
104
  if (ideLower === 'claude-code') {
85
105
  const skillDir = path.join(require('os').homedir(), '.claude', 'skills', 'aigis');
86
106
  const skillFile = path.join(skillDir, 'SKILL.md');
87
-
88
- if (!fs.existsSync(skillDir)) {
89
- fs.mkdirSync(skillDir, { recursive: true });
90
- }
91
-
92
- fs.writeFileSync(skillFile, config.content);
93
- console.log(chalk.green(`\n✓ Created ${skillFile}\n`));
94
- console.log(chalk.dim('Claude Code will automatically read this skill file.'));
95
- console.log(chalk.dim('Restart Claude Code for the skill to take effect.\n'));
107
+ if (!fs.existsSync(skillDir)) fs.mkdirSync(skillDir, { recursive: true });
108
+ writeOrRefresh(skillFile, content, checksum, opts.refresh, dest.instruction, ideLower);
96
109
  return;
97
110
  }
98
111
 
99
- // For Copilot, ensure .github directory exists
100
- const targetFile = path.resolve(config.file);
112
+ // Other IDEs
113
+ const targetFile = path.resolve(dest.file);
101
114
  const targetDir = path.dirname(targetFile);
102
- if (!fs.existsSync(targetDir)) {
103
- fs.mkdirSync(targetDir, { recursive: true });
115
+ if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir, { recursive: true });
116
+ writeOrRefresh(targetFile, content, checksum, opts.refresh, dest.instruction, ideLower, dest.file);
117
+ }
118
+
119
+ function writeOrRefresh(targetFile, content, expectedChecksum, refresh, instruction, ideName, displayName) {
120
+ const display = displayName || targetFile;
121
+
122
+ if (!fs.existsSync(targetFile)) {
123
+ fs.writeFileSync(targetFile, content);
124
+ console.log(chalk.green(`\n✓ Created ${display}\n`));
125
+ console.log(chalk.dim(instruction + '\n'));
126
+ return;
104
127
  }
105
128
 
106
- // Append or create
107
- if (fs.existsSync(targetFile)) {
108
- const existing = fs.readFileSync(targetFile, 'utf8');
109
- if (existing.includes('aigis')) {
110
- console.log(chalk.yellow(`\n⚠ ${config.file} already contains aigis configuration.\n`));
111
- console.log(chalk.dim('No changes made. Remove the existing aigis section first if you want to update.\n'));
112
- return;
113
- }
114
- fs.appendFileSync(targetFile, '\n\n' + config.content);
115
- console.log(chalk.green(`\n✓ Appended aigis configuration to ${config.file}\n`));
129
+ const existing = fs.readFileSync(targetFile, 'utf8');
130
+ const match = existing.match(RESOLVER_BLOCK_RE);
131
+ const hasCoreMarker = existing.includes('aigis-core');
132
+
133
+ if (!hasCoreMarker && !match) {
134
+ // No previous aigis content. Append.
135
+ fs.appendFileSync(targetFile, '\n\n' + content);
136
+ console.log(chalk.green(`\n✓ Appended aigis core + resolver block to ${display}\n`));
116
137
  console.log(chalk.dim('Your existing rules are preserved.\n'));
117
- } else {
118
- fs.writeFileSync(targetFile, config.content);
119
- console.log(chalk.green(`\n✓ Created ${config.file}\n`));
138
+ console.log(chalk.dim(instruction + '\n'));
139
+ return;
120
140
  }
121
141
 
122
- console.log(chalk.dim(config.instruction + '\n'));
142
+ if (refresh) {
143
+ // Overwrite the entire file (simple + safe for our format). User opted in.
144
+ fs.writeFileSync(targetFile, content);
145
+ console.log(chalk.green(`\n✓ Refreshed ${display} (resolver checksum: ${expectedChecksum.slice(0, 12)}...)\n`));
146
+ console.log(chalk.dim(instruction + '\n'));
147
+ return;
148
+ }
149
+
150
+ // Existing block present. Compare checksums.
151
+ if (match && match[1] === expectedChecksum) {
152
+ console.log(chalk.dim(`\n${display} is up to date (resolver checksum matches).\n`));
153
+ return;
154
+ }
155
+
156
+ // Mismatch (file exists, but checksum is stale or absent).
157
+ console.log(chalk.yellow(`\n⚠ ${display} already contains an aigis section.`));
158
+ if (match) {
159
+ console.log(chalk.dim(` Existing block checksum: ${match[1].slice(0, 12)}...`));
160
+ console.log(chalk.dim(` Current triggers.json: ${expectedChecksum.slice(0, 12)}...`));
161
+ console.log(chalk.dim(' These differ — your aigis content is out of date or has been edited.'));
162
+ } else {
163
+ console.log(chalk.dim(` No resolver block detected, but core marker present.`));
164
+ }
165
+ console.log('');
166
+ console.log('Options:');
167
+ console.log(` ${chalk.green('aigis init ' + ideName + ' --refresh')} overwrite the file with the current Aigis core + resolver block`);
168
+ console.log(` manually remove the existing aigis section, then re-run ${chalk.green('aigis init ' + ideName)}`);
169
+ console.log('');
170
+ process.exit(1);
123
171
  }
124
172
 
125
- module.exports = { init };
173
+ module.exports = { init, buildFullContent, renderResolverBlock };