@aigis-ai/cli 1.0.2 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +53 -0
- package/SKILL.md +20 -55
- package/bin/aigis.js +446 -59
- package/cli-python/LICENSE +21 -0
- package/cli-python/README.md +32 -0
- package/cli-python/aigis_cli/SKILL.md +70 -0
- package/cli-python/aigis_cli/__init__.py +3 -0
- package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/annotate.py +45 -0
- package/cli-python/aigis_cli/auto_verify.py +518 -0
- package/cli-python/aigis_cli/build.py +470 -0
- package/cli-python/aigis_cli/checksum.py +22 -0
- package/cli-python/aigis_cli/classify.py +192 -0
- package/cli-python/aigis_cli/cli.py +618 -0
- package/cli-python/aigis_cli/content/index/audit-scan.md +217 -0
- package/cli-python/aigis_cli/content/index/auto-verify-rules.json +439 -0
- package/cli-python/aigis_cli/content/index/context-rules.json +90 -0
- package/cli-python/aigis_cli/content/index/frameworks.md +82 -0
- package/cli-python/aigis_cli/content/index/guardrails.json +23 -0
- package/cli-python/aigis_cli/content/index/taxonomy.md +81 -0
- package/cli-python/aigis_cli/content/resolvers/triggers.json +229 -0
- package/{content/implement → cli-python/aigis_cli/content/skills/areas}/audit-logging.md +5 -0
- package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +200 -0
- package/cli-python/aigis_cli/content/skills/areas/input-validation.md +380 -0
- package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +189 -0
- package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +246 -0
- package/cli-python/aigis_cli/content/skills/core.md +62 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +202 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +169 -0
- package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +167 -0
- package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +86 -0
- package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +54 -0
- package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +39 -0
- package/cli-python/aigis_cli/content/templates/risk-characterization.md +34 -0
- package/cli-python/aigis_cli/content/templates/third-party-assessment.md +41 -0
- package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +12 -0
- package/cli-python/aigis_cli/content/verify/checklist-explainability.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +16 -0
- package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +14 -0
- package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +12 -0
- package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +13 -0
- package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +13 -0
- package/cli-python/aigis_cli/fetch.py +232 -0
- package/cli-python/aigis_cli/init_ide.py +159 -0
- package/cli-python/aigis_cli/keywords.py +73 -0
- package/cli-python/aigis_cli/search.py +69 -0
- package/cli-python/aigis_cli.egg-info/PKG-INFO +59 -0
- package/cli-python/aigis_cli.egg-info/SOURCES.txt +56 -0
- package/cli-python/aigis_cli.egg-info/dependency_links.txt +1 -0
- package/cli-python/aigis_cli.egg-info/entry_points.txt +2 -0
- package/cli-python/aigis_cli.egg-info/requires.txt +6 -0
- package/cli-python/aigis_cli.egg-info/top_level.txt +1 -0
- package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
- package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
- package/cli-python/pyproject.toml +49 -0
- package/content/index/audit-scan.md +21 -207
- package/content/index/auto-verify-rules.json +439 -0
- package/content/index/context-rules.json +90 -0
- package/content/resolvers/triggers.json +229 -0
- package/content/skills/areas/audit-logging.md +176 -0
- package/content/skills/areas/bias-monitoring.md +172 -0
- package/content/skills/areas/confidence-scoring.md +180 -0
- package/content/skills/areas/data-integrity.md +257 -0
- package/content/skills/areas/explainability.md +174 -0
- package/content/skills/areas/fallback-patterns.md +200 -0
- package/content/skills/areas/human-oversight.md +220 -0
- package/content/skills/areas/input-validation.md +380 -0
- package/content/skills/areas/monitoring.md +207 -0
- package/content/skills/areas/output-sanitization.md +183 -0
- package/content/skills/areas/pii-handling.md +189 -0
- package/content/skills/areas/prompt-security.md +153 -0
- package/content/skills/areas/rag-security.md +230 -0
- package/content/skills/areas/rate-limiting.md +246 -0
- package/content/skills/areas/supply-chain.md +193 -0
- package/content/skills/core.md +62 -0
- package/content/skills/infrastructure/logging.md +202 -0
- package/content/skills/infrastructure/rate-limiting.md +169 -0
- package/content/skills/infrastructure/secrets.md +167 -0
- package/content/skills/workflows/fastapi-llm.md +86 -0
- package/docs/resolvers.md +114 -0
- package/lib/auto-verify.js +378 -0
- package/lib/build.js +629 -0
- package/lib/checksum.js +39 -0
- package/lib/fetch.js +164 -9
- package/lib/init.js +141 -93
- package/lib/keywords.js +92 -130
- package/lib/special-recognizers.js +370 -0
- package/package.json +6 -2
- package/scripts/baseline-cursorrules.snapshot.txt +30 -0
- package/scripts/bootstrap-step-6-bench.js +85 -0
- package/scripts/check-content-sync.js +91 -0
- package/scripts/triggers.schema.json +50 -0
- package/scripts/validate-triggers.js +176 -0
- package/content/implement/fallback-patterns.md +0 -190
- package/content/implement/input-validation.md +0 -212
- package/content/implement/pii-handling.md +0 -207
- package/content/implement/rate-limiting.md +0 -217
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/bias-monitoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/confidence-scoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/data-integrity.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/explainability.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/human-oversight.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/monitoring.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/output-sanitization.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/prompt-security.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/rag-security.md +0 -0
- /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/supply-chain.md +0 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Populates step-6-resolvers/{baseline,step-6}/run-{1,2}/D{1..10}/ with:
|
|
4
|
+
* - description.txt (the per-description prompt content)
|
|
5
|
+
* - prompt.txt (the instruction to paste into Cursor)
|
|
6
|
+
* - .cursorrules (condition-appropriate: baseline copies v1.0.3 rules
|
|
7
|
+
* from a snapshot; step-6 runs `aigis init cursor`)
|
|
8
|
+
*
|
|
9
|
+
* Run this AFTER `aigis init` would produce the v2-step-6 .cursorrules content
|
|
10
|
+
* (i.e., when `aigis` resolves to the v2-step-6 branch via npm link). The
|
|
11
|
+
* baseline rules are read from a snapshot file in this repo so we can populate
|
|
12
|
+
* baseline directories regardless of which version is currently linked.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const fs = require('fs');
|
|
16
|
+
const path = require('path');
|
|
17
|
+
|
|
18
|
+
const REPO_ROOT = path.join(__dirname, '..');
|
|
19
|
+
const BENCH = '/Users/nayankanaparthi/Desktop/aigis-benchmarks/step-6-resolvers';
|
|
20
|
+
const DESCRIPTIONS_PATH = path.join(BENCH, 'descriptions.json');
|
|
21
|
+
const BASELINE_RULES_SNAPSHOT = path.join(__dirname, 'baseline-cursorrules.snapshot.txt');
|
|
22
|
+
|
|
23
|
+
const PROMPT_TEXT = `Read the description in description.txt. Use Aigis to figure out which traits apply to this system, then run \`aigis classify --traits <comma-separated> --json\` to get the recommended files. Save the trait list (one per line) to traits.txt and the classify JSON to classify.json. Do NOT implement any code. Just produce the trait list.\n`;
|
|
24
|
+
|
|
25
|
+
function generateStepSixCursorRules() {
|
|
26
|
+
// Use the in-repo init logic to render the same content `aigis init cursor` would write.
|
|
27
|
+
const { buildFullContent } = require(path.join(REPO_ROOT, 'lib', 'init'));
|
|
28
|
+
const HEADER = `# Aigis core skill — installed by \`aigis init\`\n# Re-run \`aigis init <ide>\` to refresh this file when Aigis updates.\n# Area + workflow skills load on demand via the aigis CLI; they are NOT in this file.\n\n`;
|
|
29
|
+
const { content } = buildFullContent();
|
|
30
|
+
// buildFullContent already includes HEADER; just return content.
|
|
31
|
+
return content;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function getBaselineCursorRules() {
|
|
35
|
+
if (!fs.existsSync(BASELINE_RULES_SNAPSHOT)) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
`Baseline rules snapshot missing at ${BASELINE_RULES_SNAPSHOT}.\n` +
|
|
38
|
+
`Capture it once with: \n` +
|
|
39
|
+
` npm install -g @aigis-ai/cli@1.0.3\n` +
|
|
40
|
+
` TMPDIR=$(mktemp -d) && (cd $TMPDIR && aigis init cursor && cp .cursorrules ${BASELINE_RULES_SNAPSHOT})\n`
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
return fs.readFileSync(BASELINE_RULES_SNAPSHOT, 'utf8');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function ensureDir(p) {
|
|
47
|
+
fs.mkdirSync(p, { recursive: true });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function populate(dir, descText, rulesContent) {
|
|
51
|
+
ensureDir(dir);
|
|
52
|
+
fs.writeFileSync(path.join(dir, 'description.txt'), descText + '\n');
|
|
53
|
+
fs.writeFileSync(path.join(dir, 'prompt.txt'), PROMPT_TEXT);
|
|
54
|
+
fs.writeFileSync(path.join(dir, '.cursorrules'), rulesContent);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function main() {
|
|
58
|
+
if (!fs.existsSync(DESCRIPTIONS_PATH)) {
|
|
59
|
+
console.error(`descriptions.json missing at ${DESCRIPTIONS_PATH}`);
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
const { descriptions } = JSON.parse(fs.readFileSync(DESCRIPTIONS_PATH, 'utf8'));
|
|
63
|
+
if (!Array.isArray(descriptions) || descriptions.length !== 10) {
|
|
64
|
+
console.error(`Expected exactly 10 descriptions; got ${descriptions ? descriptions.length : 0}`);
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const baselineRules = getBaselineCursorRules();
|
|
69
|
+
const stepSixRules = generateStepSixCursorRules();
|
|
70
|
+
|
|
71
|
+
let count = 0;
|
|
72
|
+
for (const condition of ['baseline', 'step-6']) {
|
|
73
|
+
const rules = condition === 'baseline' ? baselineRules : stepSixRules;
|
|
74
|
+
for (const run of ['run-1', 'run-2']) {
|
|
75
|
+
for (const desc of descriptions) {
|
|
76
|
+
const dir = path.join(BENCH, condition, run, desc.id);
|
|
77
|
+
populate(dir, desc.text, rules);
|
|
78
|
+
count++;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
console.log(`✓ Populated ${count} per-description directories under ${BENCH}/`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (require.main === module) main();
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Verify cli-python/aigis_cli/content/ is byte-identical to canonical content/.
|
|
4
|
+
*
|
|
5
|
+
* The Python package ships a copy of the content tree (see
|
|
6
|
+
* cli-python/pyproject.toml [tool.setuptools.package-data]). It is a copy, not
|
|
7
|
+
* a symlink, so sdist/wheel builds can include it. That copy drifted four
|
|
8
|
+
* steps behind canonical between Step 5 and Step 7 without detection because
|
|
9
|
+
* nothing forced parity.
|
|
10
|
+
*
|
|
11
|
+
* This script enforces parity. Run it locally before commit (or via the
|
|
12
|
+
* content-sync workflow on every PR touching either tree) and any byte-level
|
|
13
|
+
* divergence — missing files, extra files, modified bytes — fails the check
|
|
14
|
+
* with a list of offending paths.
|
|
15
|
+
*
|
|
16
|
+
* Exit 0: trees match. Exit 1: drift detected; sync with
|
|
17
|
+
* rm -rf cli-python/aigis_cli/content && cp -R content cli-python/aigis_cli/content
|
|
18
|
+
* then re-run this script.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const fs = require('fs');
|
|
22
|
+
const path = require('path');
|
|
23
|
+
const crypto = require('crypto');
|
|
24
|
+
|
|
25
|
+
const ROOT = path.resolve(__dirname, '..');
|
|
26
|
+
const CANONICAL = path.join(ROOT, 'content');
|
|
27
|
+
const PYTHON = path.join(ROOT, 'cli-python', 'aigis_cli', 'content');
|
|
28
|
+
|
|
29
|
+
function walk(root) {
|
|
30
|
+
const out = new Map();
|
|
31
|
+
function recurse(dir, relBase) {
|
|
32
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
33
|
+
const full = path.join(dir, entry.name);
|
|
34
|
+
const rel = path.join(relBase, entry.name);
|
|
35
|
+
if (entry.isDirectory()) recurse(full, rel);
|
|
36
|
+
else if (entry.isFile()) {
|
|
37
|
+
const buf = fs.readFileSync(full);
|
|
38
|
+
out.set(rel, crypto.createHash('sha256').update(buf).digest('hex'));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
recurse(root, '');
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!fs.existsSync(CANONICAL)) {
|
|
47
|
+
console.error(`Canonical content tree not found: ${CANONICAL}`);
|
|
48
|
+
process.exit(2);
|
|
49
|
+
}
|
|
50
|
+
if (!fs.existsSync(PYTHON)) {
|
|
51
|
+
console.error(`Python content tree not found: ${PYTHON}`);
|
|
52
|
+
console.error('Sync with: cp -R content cli-python/aigis_cli/content');
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const canonical = walk(CANONICAL);
|
|
57
|
+
const python = walk(PYTHON);
|
|
58
|
+
|
|
59
|
+
const missing = []; // in canonical, not in python
|
|
60
|
+
const extra = []; // in python, not in canonical
|
|
61
|
+
const modified = []; // in both, hash differs
|
|
62
|
+
|
|
63
|
+
for (const [rel, hash] of canonical) {
|
|
64
|
+
if (!python.has(rel)) missing.push(rel);
|
|
65
|
+
else if (python.get(rel) !== hash) modified.push(rel);
|
|
66
|
+
}
|
|
67
|
+
for (const rel of python.keys()) {
|
|
68
|
+
if (!canonical.has(rel)) extra.push(rel);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (missing.length === 0 && extra.length === 0 && modified.length === 0) {
|
|
72
|
+
console.log(`✓ content/ and cli-python/aigis_cli/content/ are byte-identical (${canonical.size} files).`);
|
|
73
|
+
process.exit(0);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
console.error('✗ Content drift detected between content/ and cli-python/aigis_cli/content/');
|
|
77
|
+
if (missing.length > 0) {
|
|
78
|
+
console.error(`\n Missing from Python copy (${missing.length}):`);
|
|
79
|
+
for (const f of missing) console.error(` - ${f}`);
|
|
80
|
+
}
|
|
81
|
+
if (extra.length > 0) {
|
|
82
|
+
console.error(`\n Extra in Python copy / removed from canonical (${extra.length}):`);
|
|
83
|
+
for (const f of extra) console.error(` - ${f}`);
|
|
84
|
+
}
|
|
85
|
+
if (modified.length > 0) {
|
|
86
|
+
console.error(`\n Bytes differ (${modified.length}):`);
|
|
87
|
+
for (const f of modified) console.error(` - ${f}`);
|
|
88
|
+
}
|
|
89
|
+
console.error('\nFix: rm -rf cli-python/aigis_cli/content && cp -R content cli-python/aigis_cli/content');
|
|
90
|
+
console.error('Then re-run: node scripts/check-content-sync.js');
|
|
91
|
+
process.exit(1);
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"title": "Aigis triggers.json schema",
|
|
4
|
+
"type": "object",
|
|
5
|
+
"required": ["version", "tier_rule", "high_confidence", "low_confidence"],
|
|
6
|
+
"additionalProperties": false,
|
|
7
|
+
"properties": {
|
|
8
|
+
"version": { "type": "string", "pattern": "^\\d+\\.\\d+$" },
|
|
9
|
+
"tier_rule": { "type": "string", "minLength": 50 },
|
|
10
|
+
"high_confidence": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"additionalProperties": { "$ref": "#/definitions/high_entry" }
|
|
13
|
+
},
|
|
14
|
+
"low_confidence": {
|
|
15
|
+
"type": "object",
|
|
16
|
+
"additionalProperties": { "$ref": "#/definitions/low_entry" }
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"definitions": {
|
|
20
|
+
"high_entry": {
|
|
21
|
+
"type": "object",
|
|
22
|
+
"required": ["traits", "confidence", "notes"],
|
|
23
|
+
"additionalProperties": false,
|
|
24
|
+
"properties": {
|
|
25
|
+
"traits": { "type": "array", "minItems": 1, "items": { "type": "string" } },
|
|
26
|
+
"confidence": { "type": "string", "enum": ["high"] },
|
|
27
|
+
"notes": { "type": "string", "minLength": 1 },
|
|
28
|
+
"context_filter": {
|
|
29
|
+
"type": "array",
|
|
30
|
+
"items": { "type": "string", "enum": ["web", "agentic", "rag", "batch"] }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"low_entry": {
|
|
35
|
+
"type": "object",
|
|
36
|
+
"required": ["traits", "confidence", "confirmation_prompt", "notes"],
|
|
37
|
+
"additionalProperties": false,
|
|
38
|
+
"properties": {
|
|
39
|
+
"traits": { "type": "array", "minItems": 1, "items": { "type": "string" } },
|
|
40
|
+
"confidence": { "type": "string", "enum": ["low"] },
|
|
41
|
+
"confirmation_prompt": { "type": "string", "minLength": 20 },
|
|
42
|
+
"notes": { "type": "string", "minLength": 1 },
|
|
43
|
+
"context_filter": {
|
|
44
|
+
"type": "array",
|
|
45
|
+
"items": { "type": "string", "enum": ["web", "agentic", "rag", "batch"] }
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Validates content/resolvers/triggers.json against four checks:
|
|
4
|
+
* --schema JSON shape valid (uses scripts/triggers.schema.json)
|
|
5
|
+
* --traits every trait used appears in lib/classify.js ALL_TRAITS
|
|
6
|
+
* --prompts every low-confidence entry has a confirmation_prompt
|
|
7
|
+
* --ordering entries are alphabetical (case-insensitive) within each tier
|
|
8
|
+
*
|
|
9
|
+
* No flags: run all four. Exits non-zero on first failure with a clear message
|
|
10
|
+
* pointing at the offending entry.
|
|
11
|
+
*
|
|
12
|
+
* Used by .github/workflows/triggers-validation.yml on PRs touching the file.
|
|
13
|
+
* Also runs locally: `node scripts/validate-triggers.js`.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const fs = require('fs');
|
|
17
|
+
const path = require('path');
|
|
18
|
+
|
|
19
|
+
const ROOT = path.join(__dirname, '..');
|
|
20
|
+
const TRIGGERS_PATH = path.join(ROOT, 'content', 'resolvers', 'triggers.json');
|
|
21
|
+
const SCHEMA_PATH = path.join(__dirname, 'triggers.schema.json');
|
|
22
|
+
const { ALL_TRAITS } = require(path.join(ROOT, 'lib', 'classify.js'));
|
|
23
|
+
|
|
24
|
+
function loadTriggers() {
|
|
25
|
+
return JSON.parse(fs.readFileSync(TRIGGERS_PATH, 'utf8'));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ── --schema ───────────────────────────────────────────────────────────
|
|
29
|
+
// Minimal hand-rolled JSON Schema validator (subset sufficient for our schema).
|
|
30
|
+
// Avoids pulling in ajv as a runtime dep; the schema file remains useful as a
|
|
31
|
+
// reference for editors/contributors regardless.
|
|
32
|
+
function validateSchema() {
|
|
33
|
+
const t = loadTriggers();
|
|
34
|
+
const errors = [];
|
|
35
|
+
|
|
36
|
+
if (!t.version || typeof t.version !== 'string' || !/^\d+\.\d+$/.test(t.version)) {
|
|
37
|
+
errors.push('version: missing or not in N.N format');
|
|
38
|
+
}
|
|
39
|
+
if (!t.tier_rule || typeof t.tier_rule !== 'string' || t.tier_rule.length < 50) {
|
|
40
|
+
errors.push('tier_rule: missing or shorter than 50 chars');
|
|
41
|
+
}
|
|
42
|
+
if (!t.high_confidence || typeof t.high_confidence !== 'object') {
|
|
43
|
+
errors.push('high_confidence: missing or not an object');
|
|
44
|
+
}
|
|
45
|
+
if (!t.low_confidence || typeof t.low_confidence !== 'object') {
|
|
46
|
+
errors.push('low_confidence: missing or not an object');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const allowedHighKeys = new Set(['traits', 'confidence', 'notes', 'context_filter']);
|
|
50
|
+
const allowedLowKeys = new Set(['traits', 'confidence', 'confirmation_prompt', 'notes', 'context_filter']);
|
|
51
|
+
const allowedContexts = new Set(['web', 'agentic', 'rag', 'batch']);
|
|
52
|
+
|
|
53
|
+
function checkEntry(tier, key, entry, allowed, expectedConfidence) {
|
|
54
|
+
const where = `${tier}.${key}`;
|
|
55
|
+
if (!entry || typeof entry !== 'object') {
|
|
56
|
+
errors.push(`${where}: not an object`); return;
|
|
57
|
+
}
|
|
58
|
+
for (const k of Object.keys(entry)) {
|
|
59
|
+
if (!allowed.has(k)) errors.push(`${where}: unknown key '${k}'`);
|
|
60
|
+
}
|
|
61
|
+
if (!Array.isArray(entry.traits) || entry.traits.length === 0) {
|
|
62
|
+
errors.push(`${where}: traits must be a non-empty array`);
|
|
63
|
+
}
|
|
64
|
+
if (entry.confidence !== expectedConfidence) {
|
|
65
|
+
errors.push(`${where}: confidence must be '${expectedConfidence}'`);
|
|
66
|
+
}
|
|
67
|
+
if (!entry.notes || typeof entry.notes !== 'string') {
|
|
68
|
+
errors.push(`${where}: notes required`);
|
|
69
|
+
}
|
|
70
|
+
if (entry.context_filter !== undefined) {
|
|
71
|
+
if (!Array.isArray(entry.context_filter)) {
|
|
72
|
+
errors.push(`${where}: context_filter must be an array`);
|
|
73
|
+
} else {
|
|
74
|
+
for (const c of entry.context_filter) {
|
|
75
|
+
if (!allowedContexts.has(c)) errors.push(`${where}: unknown context '${c}'`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
for (const [k, v] of Object.entries(t.high_confidence || {})) {
|
|
82
|
+
checkEntry('high_confidence', k, v, allowedHighKeys, 'high');
|
|
83
|
+
}
|
|
84
|
+
for (const [k, v] of Object.entries(t.low_confidence || {})) {
|
|
85
|
+
checkEntry('low_confidence', k, v, allowedLowKeys, 'low');
|
|
86
|
+
}
|
|
87
|
+
return errors;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ── --traits ──────────────────────────────────────────────────────────
|
|
91
|
+
function validateTraits() {
|
|
92
|
+
const t = loadTriggers();
|
|
93
|
+
const errors = [];
|
|
94
|
+
const valid = new Set(ALL_TRAITS);
|
|
95
|
+
function check(tier, entries) {
|
|
96
|
+
for (const [phrase, entry] of Object.entries(entries || {})) {
|
|
97
|
+
for (const trait of (entry.traits || [])) {
|
|
98
|
+
if (!valid.has(trait)) {
|
|
99
|
+
errors.push(`${tier}.${phrase}: unknown trait '${trait}'. Must be one of: ${ALL_TRAITS.join(', ')}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
check('high_confidence', t.high_confidence);
|
|
105
|
+
check('low_confidence', t.low_confidence);
|
|
106
|
+
return errors;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ── --prompts ─────────────────────────────────────────────────────────
|
|
110
|
+
function validatePrompts() {
|
|
111
|
+
const t = loadTriggers();
|
|
112
|
+
const errors = [];
|
|
113
|
+
for (const [phrase, entry] of Object.entries(t.low_confidence || {})) {
|
|
114
|
+
if (!entry.confirmation_prompt || typeof entry.confirmation_prompt !== 'string' || entry.confirmation_prompt.length < 20) {
|
|
115
|
+
errors.push(`low_confidence.${phrase}: confirmation_prompt missing or shorter than 20 chars`);
|
|
116
|
+
} else if (!/\(yes\s*\/\s*no\s*\/\s*unsure\)/i.test(entry.confirmation_prompt)) {
|
|
117
|
+
errors.push(`low_confidence.${phrase}: confirmation_prompt must end with '(yes / no / unsure)'`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return errors;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── --ordering ────────────────────────────────────────────────────────
|
|
124
|
+
function validateOrdering() {
|
|
125
|
+
const t = loadTriggers();
|
|
126
|
+
const errors = [];
|
|
127
|
+
function check(tier, entries) {
|
|
128
|
+
const keys = Object.keys(entries || {});
|
|
129
|
+
const sorted = [...keys].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
130
|
+
for (let i = 0; i < keys.length; i++) {
|
|
131
|
+
if (keys[i] !== sorted[i]) {
|
|
132
|
+
errors.push(`${tier}: entries not alphabetical (case-insensitive). First mismatch at index ${i}: got '${keys[i]}', expected '${sorted[i]}'.`);
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
check('high_confidence', t.high_confidence);
|
|
138
|
+
check('low_confidence', t.low_confidence);
|
|
139
|
+
return errors;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ── runner ────────────────────────────────────────────────────────────
|
|
143
|
+
function main() {
|
|
144
|
+
const args = process.argv.slice(2);
|
|
145
|
+
const flags = args.length > 0 ? args : ['--schema', '--traits', '--prompts', '--ordering'];
|
|
146
|
+
const checks = {
|
|
147
|
+
'--schema': ['Schema', validateSchema],
|
|
148
|
+
'--traits': ['Trait validity', validateTraits],
|
|
149
|
+
'--prompts': ['Confirmation prompts', validatePrompts],
|
|
150
|
+
'--ordering': ['Alphabetical ordering', validateOrdering],
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
let totalErrors = 0;
|
|
154
|
+
for (const flag of flags) {
|
|
155
|
+
if (!checks[flag]) {
|
|
156
|
+
console.error(`Unknown flag: ${flag}`);
|
|
157
|
+
process.exit(2);
|
|
158
|
+
}
|
|
159
|
+
const [name, fn] = checks[flag];
|
|
160
|
+
const errors = fn();
|
|
161
|
+
if (errors.length === 0) {
|
|
162
|
+
console.log(`✓ ${name} OK`);
|
|
163
|
+
} else {
|
|
164
|
+
console.log(`✗ ${name} (${errors.length}):`);
|
|
165
|
+
for (const e of errors) console.log(` ${e}`);
|
|
166
|
+
totalErrors += errors.length;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (totalErrors > 0) {
|
|
171
|
+
console.error(`\n${totalErrors} validation error(s).`);
|
|
172
|
+
process.exit(1);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (require.main === module) main();
|
|
@@ -1,190 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
id: fallback-patterns
|
|
3
|
-
title: Fallback and safe failure patterns
|
|
4
|
-
controls:
|
|
5
|
-
owasp: []
|
|
6
|
-
nist: [MEASURE-2.6, MANAGE-2.3, MANAGE-2.4]
|
|
7
|
-
iso42001: [Clause-8.2]
|
|
8
|
-
min_risk_tier: medium
|
|
9
|
-
system_traits: [is-agentic, is-high-volume, influences-decisions, multi-model-pipeline]
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
## What this addresses
|
|
13
|
-
|
|
14
|
-
NIST MEASURE 2.6 requires that AI systems fail safely. MANAGE 2.4 requires mechanisms to disengage systems with inconsistent performance. This file covers graceful degradation, circuit breakers, kill switches, and safe default behaviors.
|
|
15
|
-
|
|
16
|
-
## Implementation patterns
|
|
17
|
-
|
|
18
|
-
### Pattern 1: Default safe response
|
|
19
|
-
|
|
20
|
-
```python
|
|
21
|
-
def default_safe_response() -> dict:
|
|
22
|
-
"""Return a safe, neutral response when the LLM fails or output is invalid."""
|
|
23
|
-
return {
|
|
24
|
-
"severity_score": 5, # Middle of range, not extreme in either direction
|
|
25
|
-
"recommendation": "standard", # Routes to normal human review
|
|
26
|
-
"confidence": 0.0, # Zero confidence flags for human review
|
|
27
|
-
"fallback": True,
|
|
28
|
-
"message": "Unable to generate AI assessment. Routed to standard review."
|
|
29
|
-
}
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
```javascript
|
|
33
|
-
function defaultSafeResponse() {
|
|
34
|
-
return {
|
|
35
|
-
severityScore: 5,
|
|
36
|
-
recommendation: 'standard',
|
|
37
|
-
confidence: 0.0,
|
|
38
|
-
fallback: true,
|
|
39
|
-
message: 'Unable to generate AI assessment. Routed to standard review.',
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
### Pattern 2: Circuit breaker
|
|
46
|
-
|
|
47
|
-
```python
|
|
48
|
-
class CircuitBreaker:
|
|
49
|
-
def __init__(self, failure_threshold: int = 5, reset_timeout: int = 60):
|
|
50
|
-
self.failure_count = 0
|
|
51
|
-
self.failure_threshold = failure_threshold
|
|
52
|
-
self.reset_timeout = reset_timeout
|
|
53
|
-
self.state = "closed" # closed = normal, open = failing, half-open = testing
|
|
54
|
-
self.last_failure_time = None
|
|
55
|
-
|
|
56
|
-
def call(self, func, *args, **kwargs):
|
|
57
|
-
if self.state == "open":
|
|
58
|
-
if time.time() - self.last_failure_time > self.reset_timeout:
|
|
59
|
-
self.state = "half-open"
|
|
60
|
-
else:
|
|
61
|
-
log_event("circuit_breaker_open")
|
|
62
|
-
return default_safe_response()
|
|
63
|
-
|
|
64
|
-
try:
|
|
65
|
-
result = func(*args, **kwargs)
|
|
66
|
-
if self.state == "half-open":
|
|
67
|
-
self.state = "closed"
|
|
68
|
-
self.failure_count = 0
|
|
69
|
-
return result
|
|
70
|
-
except Exception as e:
|
|
71
|
-
self.failure_count += 1
|
|
72
|
-
self.last_failure_time = time.time()
|
|
73
|
-
if self.failure_count >= self.failure_threshold:
|
|
74
|
-
self.state = "open"
|
|
75
|
-
log_event("circuit_breaker_tripped", failures=self.failure_count)
|
|
76
|
-
alert_ops_team("Circuit breaker tripped for LLM service")
|
|
77
|
-
return default_safe_response()
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
```javascript
|
|
81
|
-
class CircuitBreaker {
|
|
82
|
-
constructor(failureThreshold = 5, resetTimeout = 60000) {
|
|
83
|
-
this.failureCount = 0;
|
|
84
|
-
this.failureThreshold = failureThreshold;
|
|
85
|
-
this.resetTimeout = resetTimeout;
|
|
86
|
-
this.state = 'closed';
|
|
87
|
-
this.lastFailureTime = null;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
async call(fn, ...args) {
|
|
91
|
-
if (this.state === 'open') {
|
|
92
|
-
if (Date.now() - this.lastFailureTime > this.resetTimeout)
|
|
93
|
-
this.state = 'half-open';
|
|
94
|
-
else {
|
|
95
|
-
logEvent('circuit_breaker_open');
|
|
96
|
-
return defaultSafeResponse();
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
try {
|
|
100
|
-
const result = await fn(...args);
|
|
101
|
-
if (this.state === 'half-open') { this.state = 'closed'; this.failureCount = 0; }
|
|
102
|
-
return result;
|
|
103
|
-
} catch (e) {
|
|
104
|
-
this.failureCount++;
|
|
105
|
-
this.lastFailureTime = Date.now();
|
|
106
|
-
if (this.failureCount >= this.failureThreshold) {
|
|
107
|
-
this.state = 'open';
|
|
108
|
-
logEvent('circuit_breaker_tripped', { failures: this.failureCount });
|
|
109
|
-
alertOpsTeam('Circuit breaker tripped');
|
|
110
|
-
}
|
|
111
|
-
return defaultSafeResponse();
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
### Pattern 3: Kill switch
|
|
119
|
-
|
|
120
|
-
```python
|
|
121
|
-
class KillSwitch:
|
|
122
|
-
"""Emergency shutdown mechanism. Can be triggered manually or by automated monitoring."""
|
|
123
|
-
|
|
124
|
-
def __init__(self, config_source: str):
|
|
125
|
-
self.config_source = config_source
|
|
126
|
-
|
|
127
|
-
def is_active(self) -> bool:
|
|
128
|
-
# Check external config (e.g., feature flag service, Redis, config file)
|
|
129
|
-
return self.load_config().get("ai_system_enabled", True)
|
|
130
|
-
|
|
131
|
-
def check_automated_triggers(self, metrics: dict) -> bool:
|
|
132
|
-
"""Automatically disable if metrics breach thresholds."""
|
|
133
|
-
if metrics.get("error_rate_7d", 0) > 0.15: # >15% error rate
|
|
134
|
-
self.disable("automated: error_rate exceeded 15%")
|
|
135
|
-
return False
|
|
136
|
-
if metrics.get("override_rate_7d", 0) > 0.40: # >40% human overrides
|
|
137
|
-
self.disable("automated: override_rate exceeded 40%")
|
|
138
|
-
return False
|
|
139
|
-
return True
|
|
140
|
-
|
|
141
|
-
def disable(self, reason: str):
|
|
142
|
-
self.save_config({"ai_system_enabled": False, "disabled_reason": reason})
|
|
143
|
-
alert_ops_team(f"AI system killed: {reason}")
|
|
144
|
-
log_event("kill_switch_activated", reason=reason)
|
|
145
|
-
```
|
|
146
|
-
|
|
147
|
-
```javascript
|
|
148
|
-
class KillSwitch {
|
|
149
|
-
constructor(configSource) {
|
|
150
|
-
this.configSource = configSource;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
async isActive() {
|
|
154
|
-
const config = await this.loadConfig();
|
|
155
|
-
return config.aiSystemEnabled !== false;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
async checkAutomatedTriggers(metrics) {
|
|
159
|
-
if ((metrics.errorRate7d || 0) > 0.15) {
|
|
160
|
-
await this.disable('automated: error_rate exceeded 15%');
|
|
161
|
-
return false;
|
|
162
|
-
}
|
|
163
|
-
if ((metrics.overrideRate7d || 0) > 0.40) {
|
|
164
|
-
await this.disable('automated: override_rate exceeded 40%');
|
|
165
|
-
return false;
|
|
166
|
-
}
|
|
167
|
-
return true;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
async disable(reason) {
|
|
171
|
-
await this.saveConfig({ aiSystemEnabled: false, disabledReason: reason });
|
|
172
|
-
await alertOpsTeam('AI system killed: ' + reason);
|
|
173
|
-
logEvent('kill_switch_activated', { reason });
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
## Anti-patterns
|
|
180
|
-
|
|
181
|
-
- **No fallback behavior defined.** Every AI call must have a defined failure path.
|
|
182
|
-
- **Crashing on LLM errors.** Catch exceptions and return safe defaults.
|
|
183
|
-
- **No kill switch.** There must always be a way to shut the system down quickly.
|
|
184
|
-
- **Kill switch requires code deployment.** Use external config that can be toggled without deploying.
|
|
185
|
-
|
|
186
|
-
## Edge cases
|
|
187
|
-
|
|
188
|
-
- **Partial failures.** The LLM returns valid JSON but the content is nonsensical. Output schema validation catches structural issues; confidence scoring catches content issues.
|
|
189
|
-
- **Cascading failures.** In multi-model pipelines, one model failing can cascade. Each stage needs independent fallback.
|
|
190
|
-
- **Recovery after kill switch.** Define a process for re-enabling: run evaluation suite, gradual rollout, monitoring period.
|