@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.
Files changed (124) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/SKILL.md +20 -55
  3. package/bin/aigis.js +446 -59
  4. package/cli-python/LICENSE +21 -0
  5. package/cli-python/README.md +32 -0
  6. package/cli-python/aigis_cli/SKILL.md +70 -0
  7. package/cli-python/aigis_cli/__init__.py +3 -0
  8. package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
  9. package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
  10. package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
  11. package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
  12. package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
  13. package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
  14. package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
  15. package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
  16. package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
  17. package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
  18. package/cli-python/aigis_cli/annotate.py +45 -0
  19. package/cli-python/aigis_cli/auto_verify.py +518 -0
  20. package/cli-python/aigis_cli/build.py +470 -0
  21. package/cli-python/aigis_cli/checksum.py +22 -0
  22. package/cli-python/aigis_cli/classify.py +192 -0
  23. package/cli-python/aigis_cli/cli.py +618 -0
  24. package/cli-python/aigis_cli/content/index/audit-scan.md +217 -0
  25. package/cli-python/aigis_cli/content/index/auto-verify-rules.json +439 -0
  26. package/cli-python/aigis_cli/content/index/context-rules.json +90 -0
  27. package/cli-python/aigis_cli/content/index/frameworks.md +82 -0
  28. package/cli-python/aigis_cli/content/index/guardrails.json +23 -0
  29. package/cli-python/aigis_cli/content/index/taxonomy.md +81 -0
  30. package/cli-python/aigis_cli/content/resolvers/triggers.json +229 -0
  31. package/{content/implement → cli-python/aigis_cli/content/skills/areas}/audit-logging.md +5 -0
  32. package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +200 -0
  33. package/cli-python/aigis_cli/content/skills/areas/input-validation.md +380 -0
  34. package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +189 -0
  35. package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +246 -0
  36. package/cli-python/aigis_cli/content/skills/core.md +62 -0
  37. package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +202 -0
  38. package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +169 -0
  39. package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +167 -0
  40. package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +86 -0
  41. package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +54 -0
  42. package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +39 -0
  43. package/cli-python/aigis_cli/content/templates/risk-characterization.md +34 -0
  44. package/cli-python/aigis_cli/content/templates/third-party-assessment.md +41 -0
  45. package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +13 -0
  46. package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +13 -0
  47. package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +13 -0
  48. package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +12 -0
  49. package/cli-python/aigis_cli/content/verify/checklist-explainability.md +13 -0
  50. package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +13 -0
  51. package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +14 -0
  52. package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +16 -0
  53. package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +13 -0
  54. package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +14 -0
  55. package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +14 -0
  56. package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +13 -0
  57. package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +12 -0
  58. package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +13 -0
  59. package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +13 -0
  60. package/cli-python/aigis_cli/fetch.py +232 -0
  61. package/cli-python/aigis_cli/init_ide.py +159 -0
  62. package/cli-python/aigis_cli/keywords.py +73 -0
  63. package/cli-python/aigis_cli/search.py +69 -0
  64. package/cli-python/aigis_cli.egg-info/PKG-INFO +59 -0
  65. package/cli-python/aigis_cli.egg-info/SOURCES.txt +56 -0
  66. package/cli-python/aigis_cli.egg-info/dependency_links.txt +1 -0
  67. package/cli-python/aigis_cli.egg-info/entry_points.txt +2 -0
  68. package/cli-python/aigis_cli.egg-info/requires.txt +6 -0
  69. package/cli-python/aigis_cli.egg-info/top_level.txt +1 -0
  70. package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
  71. package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
  72. package/cli-python/pyproject.toml +49 -0
  73. package/content/index/audit-scan.md +21 -207
  74. package/content/index/auto-verify-rules.json +439 -0
  75. package/content/index/context-rules.json +90 -0
  76. package/content/resolvers/triggers.json +229 -0
  77. package/content/skills/areas/audit-logging.md +176 -0
  78. package/content/skills/areas/bias-monitoring.md +172 -0
  79. package/content/skills/areas/confidence-scoring.md +180 -0
  80. package/content/skills/areas/data-integrity.md +257 -0
  81. package/content/skills/areas/explainability.md +174 -0
  82. package/content/skills/areas/fallback-patterns.md +200 -0
  83. package/content/skills/areas/human-oversight.md +220 -0
  84. package/content/skills/areas/input-validation.md +380 -0
  85. package/content/skills/areas/monitoring.md +207 -0
  86. package/content/skills/areas/output-sanitization.md +183 -0
  87. package/content/skills/areas/pii-handling.md +189 -0
  88. package/content/skills/areas/prompt-security.md +153 -0
  89. package/content/skills/areas/rag-security.md +230 -0
  90. package/content/skills/areas/rate-limiting.md +246 -0
  91. package/content/skills/areas/supply-chain.md +193 -0
  92. package/content/skills/core.md +62 -0
  93. package/content/skills/infrastructure/logging.md +202 -0
  94. package/content/skills/infrastructure/rate-limiting.md +169 -0
  95. package/content/skills/infrastructure/secrets.md +167 -0
  96. package/content/skills/workflows/fastapi-llm.md +86 -0
  97. package/docs/resolvers.md +114 -0
  98. package/lib/auto-verify.js +378 -0
  99. package/lib/build.js +629 -0
  100. package/lib/checksum.js +39 -0
  101. package/lib/fetch.js +164 -9
  102. package/lib/init.js +141 -93
  103. package/lib/keywords.js +92 -130
  104. package/lib/special-recognizers.js +370 -0
  105. package/package.json +6 -2
  106. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  107. package/scripts/bootstrap-step-6-bench.js +85 -0
  108. package/scripts/check-content-sync.js +91 -0
  109. package/scripts/triggers.schema.json +50 -0
  110. package/scripts/validate-triggers.js +176 -0
  111. package/content/implement/fallback-patterns.md +0 -190
  112. package/content/implement/input-validation.md +0 -212
  113. package/content/implement/pii-handling.md +0 -207
  114. package/content/implement/rate-limiting.md +0 -217
  115. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/bias-monitoring.md +0 -0
  116. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/confidence-scoring.md +0 -0
  117. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/data-integrity.md +0 -0
  118. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/explainability.md +0 -0
  119. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/human-oversight.md +0 -0
  120. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/monitoring.md +0 -0
  121. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/output-sanitization.md +0 -0
  122. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/prompt-security.md +0 -0
  123. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/rag-security.md +0 -0
  124. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/supply-chain.md +0 -0
package/lib/keywords.js CHANGED
@@ -1,139 +1,101 @@
1
- const KEYWORD_MAP = {
2
- 'uses-llm': [
3
- 'llm', 'language model', 'gpt', 'claude', 'chatbot', 'chat bot', 'bot',
4
- 'generative ai', 'gen ai', 'genai', 'openai', 'anthropic', 'gemini',
5
- 'mistral', 'cohere', 'completion', 'prompt', 'chat completion',
6
- 'text generation', 'natural language', 'nlp',
7
- ],
8
- 'uses-rag': [
9
- 'rag', 'retrieval', 'vector', 'embedding', 'knowledge base', 'knowledgebase',
10
- 'pinecone', 'weaviate', 'chromadb', 'chroma', 'qdrant', 'pgvector',
11
- 'faiss', 'milvus', 'semantic search', 'document search', 'vector db',
12
- 'vector database', 'vector store',
13
- ],
14
- 'uses-finetuned': [
15
- 'fine-tune', 'finetune', 'fine tune', 'custom model', 'trained model',
16
- 'lora', 'qlora', 'peft', 'sft', 'custom trained', 'training data',
17
- 'fine-tuning',
18
- ],
19
- 'uses-thirdparty-api': [
20
- 'openai api', 'anthropic api', 'api key', 'third party', 'third-party',
21
- 'external model', 'model provider', 'hosted model', 'api provider',
22
- 'cloud model', 'model api',
23
- ],
24
- 'is-agentic': [
25
- 'agent', 'agentic', 'autonomous', 'auto-execute', 'takes actions',
26
- 'tool use', 'function calling', 'tool calling', 'writes to database',
27
- 'sends email', 'executes code', 'multi-step', 'self-directed',
28
- 'langchain agent', 'autogen', 'crewai',
29
- ],
30
- 'is-multimodal': [
31
- 'multimodal', 'multi-modal', 'image', 'audio', 'video', 'vision',
32
- 'speech', 'voice', 'text-to-speech', 'speech-to-text', 'ocr',
33
- 'image generation', 'dall-e', 'stable diffusion', 'whisper',
34
- ],
35
- 'processes-pii': [
36
- 'pii', 'personal data', 'personally identifiable', 'names', 'emails',
37
- 'email address', 'phone number', 'ssn', 'social security', 'address',
38
- 'date of birth', 'user data', 'customer data', 'gdpr', 'personal information',
39
- ],
40
- 'handles-financial': [
41
- 'financial', 'finance', 'banking', 'payment', 'credit', 'debit',
42
- 'transaction', 'insurance', 'claim', 'policy', 'lending', 'loan',
43
- 'mortgage', 'investment', 'trading', 'fintech', 'account balance',
44
- 'credit card', 'credit score',
45
- ],
46
- 'handles-health': [
47
- 'health', 'medical', 'clinical', 'patient', 'diagnosis', 'prescription',
48
- 'hipaa', 'healthcare', 'hospital', 'doctor', 'treatment', 'symptom',
49
- 'disease', 'medication', 'ehr', 'electronic health', 'pharma',
50
- 'pharmaceutical',
51
- ],
52
- 'handles-proprietary': [
53
- 'proprietary', 'trade secret', 'confidential', 'internal only',
54
- 'competitive', 'intellectual property', 'ip', 'source code analysis',
55
- 'strategy', 'classified',
56
- ],
57
- 'handles-minors': [
58
- 'children', 'child', 'minor', 'kid', 'student', 'school', 'coppa',
59
- 'under 13', 'under 16', 'parental', 'youth', 'teen', 'education',
60
- 'k-12', 'k12',
61
- ],
62
- 'influences-decisions': [
63
- 'decision', 'approve', 'deny', 'reject', 'score', 'rank', 'filter',
64
- 'hiring', 'recruitment', 'credit decision', 'loan decision',
65
- 'eligibility', 'assessment', 'evaluation', 'grading', 'sentencing',
66
- 'recommendation', 'determines', 'affects people',
67
- ],
68
- 'accepts-user-input': [
69
- 'user input', 'user text', 'chat', 'message', 'form', 'text area',
70
- 'text input', 'free text', 'user query', 'search box', 'prompt input',
71
- 'customer message', 'user message', 'text field',
72
- ],
73
- 'is-external': [
74
- 'customer', 'public', 'external', 'user-facing', 'customer-facing',
75
- 'consumer', 'website', 'app', 'saas', 'product', 'end user',
76
- 'client-facing',
77
- ],
78
- 'is-internal': [
79
- 'internal', 'employee', 'staff only', 'back office', 'internal tool',
80
- 'admin only', 'intranet', 'corporate only',
81
- ],
82
- 'is-high-volume': [
83
- 'high volume', 'production', 'scale', 'thousands', 'millions',
84
- 'high traffic', 'load balancer', 'auto-scaling', 'enterprise',
85
- 'at scale', 'high throughput',
86
- ],
87
- 'generates-code': [
88
- 'generates code', 'code generation', 'sql generation', 'writes code',
89
- 'code execution', 'executes code', 'eval', 'exec', 'coding assistant',
90
- 'code interpreter',
91
- ],
92
- 'generates-content': [
93
- 'generates content', 'content generation', 'marketing copy', 'blog post',
94
- 'email generation', 'social media', 'article', 'report generation',
95
- 'publish', 'customer email', 'notification',
96
- ],
97
- 'multi-model-pipeline': [
98
- 'pipeline', 'chain', 'multi-model', 'multi model', 'sequential',
99
- 'model chain', 'orchestration', 'workflow', 'first model',
100
- 'second model', 'feeds into',
101
- ],
102
- 'jurisdiction-eu': [
103
- 'eu', 'european', 'europe', 'gdpr', 'eu ai act', 'ai act',
104
- 'european union', 'germany', 'france', 'brussels',
105
- ],
106
- 'jurisdiction-us-regulated': [
107
- 'hipaa', 'fcra', 'ferpa', 'fedramp', 'soc2', 'regulated',
108
- 'compliance', 'banking regulation', 'sec', 'finra', 'occ',
109
- 'us regulated', 'federal',
110
- ],
111
- 'jurisdiction-global': [
112
- 'global', 'worldwide', 'international', 'multi-country', 'multi country',
113
- 'cross-border', 'multiple countries', 'global deployment',
114
- ],
115
- };
1
+ /**
2
+ * Resolver: maps natural-language descriptions to traits via the trigger map
3
+ * defined in content/resolvers/triggers.json.
4
+ *
5
+ * Two tiers (per the locked tier rule in triggers.json):
6
+ * high_confidence: phrase implies traits unconditionally → auto-apply.
7
+ * low_confidence: phrase implies traits only sometimes → return as a
8
+ * suggestion with a confirmation_prompt; the caller decides
9
+ * whether to add the trait based on user input.
10
+ *
11
+ * Matching: case-insensitive substring match against the input text. Multi-word
12
+ * phrases match contiguously. The same source file is read by the CLI here AND
13
+ * embedded into IDE rules files by `aigis init` (see lib/init.js), so agents
14
+ * and the CLI use the exact same map.
15
+ */
116
16
 
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ const TRIGGERS_PATH = path.join(__dirname, '..', 'content', 'resolvers', 'triggers.json');
21
+
22
+ let _cache = null;
23
+ function loadTriggers() {
24
+ if (!_cache) _cache = JSON.parse(fs.readFileSync(TRIGGERS_PATH, 'utf8'));
25
+ return _cache;
26
+ }
27
+
28
+ /**
29
+ * Scan `text` against the high-confidence trigger map. Returns:
30
+ * {
31
+ * high_confidence_matches: [
32
+ * { phrase: 'chatbot', traits: ['uses-llm', 'accepts-user-input'] },
33
+ * ...
34
+ * ],
35
+ * low_confidence_matches: [
36
+ * { id: '1', phrase: 'personalization', traits: ['processes-pii'],
37
+ * confirmation_prompt: '...', notes: '...' },
38
+ * ...
39
+ * ],
40
+ * traits_auto_applied: ['uses-llm', 'accepts-user-input', ...] // unique union
41
+ * }
42
+ *
43
+ * The caller is responsible for handling the low_confidence_matches array
44
+ * (interactive prompt, --confirm/--reject flags, default-reject in non-TTY).
45
+ */
117
46
  function detectTraitsFromText(text) {
47
+ const triggers = loadTriggers();
118
48
  const textLower = text.toLowerCase();
119
- const detected = [];
120
- const seen = new Set();
121
49
 
122
- for (const [trait, keywords] of Object.entries(KEYWORD_MAP)) {
123
- for (const keyword of keywords) {
124
- if (textLower.includes(keyword) && !seen.has(trait)) {
125
- seen.add(trait);
126
- detected.push({
127
- trait,
128
- keyword,
129
- confidence: keyword.length > 4 ? 'high' : 'medium',
130
- });
131
- break;
132
- }
50
+ const highMatches = [];
51
+ const autoTraits = new Set();
52
+ for (const [phrase, entry] of Object.entries(triggers.high_confidence)) {
53
+ if (textLower.includes(phrase.toLowerCase())) {
54
+ highMatches.push({ phrase, traits: entry.traits.slice() });
55
+ for (const t of entry.traits) autoTraits.add(t);
133
56
  }
134
57
  }
135
58
 
136
- return detected;
59
+ const lowMatches = [];
60
+ let nextId = 1;
61
+ for (const [phrase, entry] of Object.entries(triggers.low_confidence)) {
62
+ if (textLower.includes(phrase.toLowerCase())) {
63
+ lowMatches.push({
64
+ id: String(nextId++),
65
+ phrase,
66
+ traits: entry.traits.slice(),
67
+ confirmation_prompt: entry.confirmation_prompt,
68
+ notes: entry.notes,
69
+ });
70
+ }
71
+ }
72
+
73
+ return {
74
+ high_confidence_matches: highMatches,
75
+ low_confidence_matches: lowMatches,
76
+ traits_auto_applied: [...autoTraits],
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Resolve a list of low-confidence suggestions against user decisions.
82
+ * decisions = { '1': 'yes' | 'no' | 'unsure', ... } (id-keyed)
83
+ * Returns the union of high-confidence + confirmed low-confidence traits.
84
+ */
85
+ function applyConfirmations(detection, decisions = {}) {
86
+ const final = new Set(detection.traits_auto_applied);
87
+ const userDecisions = [];
88
+ for (const sug of detection.low_confidence_matches) {
89
+ const decision = (decisions[sug.id] || 'no').toLowerCase();
90
+ userDecisions.push({ ...sug, user_decision: decision });
91
+ if (decision === 'yes' || decision === 'y') {
92
+ for (const t of sug.traits) final.add(t);
93
+ }
94
+ }
95
+ return {
96
+ final_traits: [...final].sort(),
97
+ low_confidence_decisions: userDecisions,
98
+ };
137
99
  }
138
100
 
139
- module.exports = { detectTraitsFromText, KEYWORD_MAP };
101
+ module.exports = { detectTraitsFromText, applyConfirmations, loadTriggers, TRIGGERS_PATH };
@@ -0,0 +1,370 @@
1
+ /**
2
+ * Special recognizers for overclaim patterns that can't be expressed as
3
+ * "match-any-regex" rules. Called from auto-verify.js when a checklist has
4
+ * an `overclaim` entry naming the recognizer.
5
+ *
6
+ * Each recognizer receives:
7
+ * - files: array of { path, content } pre-loaded by the scanner
8
+ * - ctx: { rootDir, areaId, checkId }
9
+ *
10
+ * Each returns:
11
+ * { flagged: boolean, evidence: [ { file, line, snippet } ], notes: string }
12
+ *
13
+ * These are heuristics. Goal is to catch the common overclaim pattern, not
14
+ * to be a full static analyzer. False negatives are acceptable; loud false
15
+ * positives are not — when in doubt, return flagged=false with a note
16
+ * explaining what was inconclusive.
17
+ */
18
+
19
+ /**
20
+ * kill_switch_restart_latched
21
+ *
22
+ * Baseline evidence: all three runs built env-var kill switches that meet
23
+ * the literal "env variable" wording of V3 but are read only at module
24
+ * load. Flipping them in production requires a restart, which defeats the
25
+ * incident-response intent.
26
+ *
27
+ * Structural signals (any one = flag):
28
+ * (a) `@lru_cache` decorator on a function that returns Settings / settings
29
+ * (b) `settings = Settings()` or similar module-level instantiation AND
30
+ * the kill-switch flag is referenced as `settings.<flag>` in a
31
+ * handler (i.e. read from the cached object, not re-fetched per request)
32
+ * (c) A bare `KILL_SWITCH = os.getenv(...)` at module scope (value
33
+ * frozen at import)
34
+ */
35
+ function killSwitchRestartLatched(files, ctx) {
36
+ const evidence = [];
37
+ const flagReasons = [];
38
+
39
+ const killSwitchTokens = [
40
+ /ai_system_enabled/i,
41
+ /kill_switch/i,
42
+ /KILL_SWITCH/,
43
+ /feature_flag/i,
44
+ /ai_enabled/i,
45
+ ];
46
+
47
+ // Signal (a): @lru_cache on a Settings-returning function
48
+ for (const { path, content } of files) {
49
+ const lines = content.split('\n');
50
+ for (let i = 0; i < lines.length; i++) {
51
+ if (/@lru_cache\b/.test(lines[i])) {
52
+ // Look at the next 5 lines for a function that returns Settings
53
+ const follow = lines.slice(i + 1, i + 6).join('\n');
54
+ if (/def\s+(get_)?settings\b|->\s*Settings\b|return\s+Settings\s*\(/.test(follow)) {
55
+ evidence.push({
56
+ file: path,
57
+ line: i + 1,
58
+ snippet: lines.slice(i, Math.min(i + 4, lines.length)).join('\n'),
59
+ });
60
+ flagReasons.push('@lru_cache on Settings retrieval (pydantic-settings cached at first call)');
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ // Signal (b): module-level `settings = Settings()` AND a flag is read from it in a handler
67
+ const moduleSettingsFiles = [];
68
+ for (const { path, content } of files) {
69
+ if (/^settings\s*=\s*Settings\s*\(\s*\)/m.test(content)) {
70
+ moduleSettingsFiles.push(path);
71
+ }
72
+ }
73
+ if (moduleSettingsFiles.length > 0) {
74
+ // Check if any handler uses `settings.<kill_switch_flag>`
75
+ for (const { path, content } of files) {
76
+ const lines = content.split('\n');
77
+ for (let i = 0; i < lines.length; i++) {
78
+ const line = lines[i];
79
+ if (/settings\.(ai_system_enabled|kill_switch|ai_enabled|feature_flag)/.test(line)
80
+ && /^\s*if\s+not\s+settings\./.test(line) === false
81
+ || /if\s+not\s+settings\.(ai_system_enabled|kill_switch|ai_enabled|feature_flag)/.test(line)) {
82
+ evidence.push({
83
+ file: path,
84
+ line: i + 1,
85
+ snippet: line.trim(),
86
+ });
87
+ flagReasons.push('Module-level `settings = Settings()` read inside handler (frozen at import)');
88
+ break;
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ // Signal (c): bare module-level os.getenv for a kill-switch variable
95
+ for (const { path, content } of files) {
96
+ const lines = content.split('\n');
97
+ for (let i = 0; i < lines.length; i++) {
98
+ const line = lines[i];
99
+ // Module-level (no leading indent) assignment from os.getenv for a kill-switch-named var
100
+ if (/^(KILL_SWITCH|AI_ENABLED|AI_SYSTEM_ENABLED)\s*=\s*os\.getenv/.test(line)) {
101
+ evidence.push({
102
+ file: path,
103
+ line: i + 1,
104
+ snippet: line.trim(),
105
+ });
106
+ flagReasons.push('Module-level `<FLAG> = os.getenv(...)` (value frozen at import)');
107
+ }
108
+ }
109
+ }
110
+
111
+ // If the codebase has evidence of re-reading env per-request, partial exoneration
112
+ let rereadsPerRequest = false;
113
+ for (const { content } of files) {
114
+ // Heuristic: os.getenv called inside a function whose body contains `async def` or a route decorator nearby
115
+ // Keep simple: did we see any os.getenv inside a function body that looks like a handler?
116
+ if (/@app\.(get|post|put|delete)|@router\.(get|post|put|delete)/.test(content)
117
+ && /^(?!\s*#).*os\.getenv\s*\(\s*['"](?:AI_SYSTEM_ENABLED|KILL_SWITCH|AI_ENABLED)/m.test(content)) {
118
+ rereadsPerRequest = true;
119
+ }
120
+ }
121
+
122
+ const flagged = evidence.length > 0 && !rereadsPerRequest;
123
+ return {
124
+ flagged,
125
+ evidence,
126
+ notes: flagged
127
+ ? `Kill switch appears restart-latched. Reasons: ${[...new Set(flagReasons)].join('; ')}. This meets Aigis V3 literal wording ("env variable") but cannot be toggled during a live incident without a process restart. Verify manually; if confirmed, mark PARTIAL rather than PASS.`
128
+ : (evidence.length > 0
129
+ ? 'Restart-latched signals present but counter-signals (per-request env reads) also found. Manual review recommended.'
130
+ : 'No restart-latched signals detected (no @lru_cache on Settings, no bare module-level env reads of kill-switch var).'),
131
+ };
132
+ }
133
+
134
+ /**
135
+ * injection_log_only
136
+ *
137
+ * Baseline evidence: all three runs implemented an injection-pattern
138
+ * detector whose callsite set a flag or logged, but continued execution
139
+ * to the LLM call without blocking. That meets Aigis V5 literal wording
140
+ * ("even if just logging") but is a logging feature, not a security
141
+ * feature.
142
+ *
143
+ * Detection approach:
144
+ * 1. Find the detector function name (regex for common names +
145
+ * SUSPICIOUS_PATTERNS module-level list).
146
+ * 2. Find every callsite of that function.
147
+ * 3. For each callsite, look at the next N lines up to a suitable
148
+ * boundary. If we see a control-flow break (raise, return,
149
+ * HTTPException, reject) that depends on the detector's return
150
+ * value BEFORE we see evidence of the LLM call continuing, the
151
+ * detector blocks — unflagged. Otherwise flag as log-only.
152
+ */
153
+ function injectionLogOnly(files, ctx) {
154
+ const evidence = [];
155
+ const callsiteLog = [];
156
+
157
+ // Matches common detector names: check_injection, detect_injection,
158
+ // scan_injection, scan_prompt_injection, _scan_prompt_injection,
159
+ // injection_check, injection_detect, run_injection_scan, etc.
160
+ // Also matches direct uses of INJECTION_PATTERN.search / .match / .test / .exec.
161
+ const detectorNameRegex = /\b_?(?:check|detect|scan|run|test|is)_?(?:prompt_?)?injection[a-z_]*\b|INJECTION_PATTERN\s*\.\s*(?:search|match|test|exec)/;
162
+
163
+ for (const { path, content } of files) {
164
+ const lines = content.split('\n');
165
+ for (let i = 0; i < lines.length; i++) {
166
+ const line = lines[i];
167
+ // Skip the definition of the detector itself
168
+ if (/^\s*def\s+/.test(line) && detectorNameRegex.test(line)) continue;
169
+ // Callsite: the detector is referenced (not as `def`)
170
+ if (detectorNameRegex.test(line) && !/^\s*def\s+/.test(line) && !/^\s*from\s+|^\s*import\s+/.test(line)) {
171
+ // This is a callsite. Inspect next 20 lines for block/continue pattern.
172
+ const window = lines.slice(i, Math.min(i + 20, lines.length)).join('\n');
173
+ // Strong signals the detector blocks on detection:
174
+ // - `raise HTTPException` / `raise ValueError` inside an `if ...flagged` / `if ...inj` block
175
+ // - `return <non-llm>` under `if ...flagged`
176
+ // - `reject`, `block` keywords
177
+ const blockPatterns = [
178
+ /if\s+(?:injection|inj|result|flagged|inject[a-z_]*)[\s\S]{0,120}?(?:raise|return|HTTPException|abort|reject|block)/i,
179
+ /if\s+[^\n]*\[[\"']flagged[\"']\][\s\S]{0,120}?(?:raise|return|HTTPException|abort|reject|block)/i,
180
+ /if\s+[^\n]*\.flagged[\s\S]{0,120}?(?:raise|return|HTTPException|abort)/i,
181
+ ];
182
+ let blocks = false;
183
+ for (const pat of blockPatterns) {
184
+ if (pat.test(window)) {
185
+ blocks = true;
186
+ break;
187
+ }
188
+ }
189
+
190
+ callsiteLog.push({
191
+ file: path,
192
+ line: i + 1,
193
+ snippet: line.trim(),
194
+ blocks,
195
+ });
196
+
197
+ if (!blocks) {
198
+ evidence.push({
199
+ file: path,
200
+ line: i + 1,
201
+ snippet: line.trim() + ` // next 20 lines do not contain a control-flow break based on the detection result`,
202
+ });
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ const flagged = callsiteLog.length > 0 && callsiteLog.every((c) => !c.blocks);
209
+ const partiallyFlagged = callsiteLog.some((c) => !c.blocks) && callsiteLog.some((c) => c.blocks);
210
+
211
+ let notes;
212
+ if (callsiteLog.length === 0) {
213
+ notes = 'No injection detector callsites found (the detector may not be invoked, or the scanner could not identify it).';
214
+ } else if (flagged) {
215
+ notes = `${callsiteLog.length} callsite(s) of the injection detector found; none branch on the result. Meets Aigis V5 literal wording ("even if just logging") but the LLM call still runs on flagged inputs. Verify manually; if confirmed, mark PARTIAL rather than PASS.`;
216
+ } else if (partiallyFlagged) {
217
+ notes = `Some callsites block on detection, others do not. Review the non-blocking ones.`;
218
+ } else {
219
+ notes = 'All callsites of the injection detector branch on the result (raise/return/reject). No log-only pattern detected.';
220
+ }
221
+
222
+ return {
223
+ flagged: flagged || partiallyFlagged,
224
+ evidence,
225
+ notes,
226
+ };
227
+ }
228
+
229
+ /**
230
+ * pii_incomplete_classes
231
+ *
232
+ * Baseline evidence: all three runs implemented PII redaction that
233
+ * covered only 3-4 of the 5 required classes (typically missing
234
+ * `address`, sometimes missing `credit_card` or `phone`). The literal
235
+ * Aigis V1 wording ("is PII detected and redacted before being sent to
236
+ * the LLM") is satisfied as long as a redactor exists, but the redactor
237
+ * leaks any class it doesn't know about.
238
+ *
239
+ * Detection approach: look at PII pattern definitions in the codebase
240
+ * (either as a dict keyed by class name, or as discrete regex variables)
241
+ * and check which of the required 5 classes are represented.
242
+ */
243
+ function piiIncompleteClasses(files, ctx) {
244
+ const REQUIRED = ['ssn', 'email', 'phone', 'credit_card', 'address'];
245
+ // Acceptable name variants per class (lowercased)
246
+ const CLASS_TOKENS = {
247
+ ssn: ['ssn', 'social_security', 'socialsecurity', 'socsec'],
248
+ email: ['email', 'e_mail', 'e-mail'],
249
+ phone: ['phone', 'phone_number', 'telephone', 'mobile'],
250
+ credit_card: ['credit_card', 'creditcard', 'card', 'card_number', 'cardnumber', 'pan', 'cc_number', 'payment_card'],
251
+ address: ['address', 'street', 'postal_address', 'mailing_address'],
252
+ };
253
+ const present = {};
254
+ const evidence = [];
255
+
256
+ for (const cls of REQUIRED) present[cls] = false;
257
+
258
+ for (const { path, content } of files) {
259
+ for (const cls of REQUIRED) {
260
+ if (present[cls]) continue;
261
+ for (const token of CLASS_TOKENS[cls]) {
262
+ const upper = token.toUpperCase();
263
+ const patterns = [
264
+ // Dict keys: "ssn": or 'ssn':
265
+ new RegExp('["\'`]' + token + '["\'`]\\s*:', 'g'),
266
+ // Named variable: SSN_PATTERN = re.compile or ssn = re.compile
267
+ new RegExp('\\b' + token + '\\s*[:=]\\s*re\\.compile', 'gi'),
268
+ new RegExp('\\b' + upper + '_PATTERN', 'g'),
269
+ // Replacement strings: [SSN_REDACTED], [REDACTED_SSN], <SSN>
270
+ new RegExp('\\[' + upper + '_REDACTED\\]', 'g'),
271
+ new RegExp('\\[REDACTED_' + upper + '\\]', 'g'),
272
+ // Function names: redact_ssn, redactSsn
273
+ new RegExp('\\b(?:redact|mask|scrub)_' + token + '\\b', 'gi'),
274
+ ];
275
+ for (const re of patterns) {
276
+ re.lastIndex = 0;
277
+ const m = re.exec(content);
278
+ if (m) {
279
+ present[cls] = true;
280
+ const line = (content.slice(0, m.index).match(/\n/g) || []).length + 1;
281
+ evidence.push({
282
+ file: path,
283
+ line,
284
+ snippet: `${cls}: ` + (content.split('\n')[line - 1] || '').trim().slice(0, 120),
285
+ });
286
+ break;
287
+ }
288
+ }
289
+ }
290
+ }
291
+ }
292
+
293
+ const missing = REQUIRED.filter((c) => !present[c]);
294
+ const flagged = missing.length > 0;
295
+ const notes = flagged
296
+ ? `PII redactor is missing pattern coverage for: ${missing.join(', ')}. `
297
+ + `Aigis V1 literal wording ("redaction called") is met, but inputs containing `
298
+ + `${missing.join(' or ')} will reach the LLM (and logs) unredacted. `
299
+ + `Add all 5 required classes: ${REQUIRED.join(', ')}.`
300
+ : `All 5 required PII classes detected in the code.`;
301
+ return { flagged, evidence, notes };
302
+ }
303
+
304
+ /**
305
+ * rate_limit_no_retry_after
306
+ *
307
+ * Baseline evidence: every run built rate limiting that returned 429 on
308
+ * block but without a Retry-After header. Well-behaved clients (every
309
+ * major LLM SDK) read that header to drive retry backoff. Absent
310
+ * Retry-After, clients either retry immediately (making the problem
311
+ * worse) or give up entirely.
312
+ *
313
+ * Detection approach: find every 429 response construction and check
314
+ * whether a Retry-After header is set on or near it (within ~15 lines).
315
+ */
316
+ function rateLimitNoRetryAfter(files, ctx) {
317
+ const evidence = [];
318
+ const siteLog = [];
319
+
320
+ // Match common 429 construction patterns
321
+ const responseSiteRe = /(?:status_code\s*=\s*429|HTTPException\s*\(\s*(?:status_code\s*=\s*)?429|status\(429\)|response\.status\s*=\s*429)/g;
322
+ const retryAfterRe = /Retry-After|retry_after|retryAfter/i;
323
+
324
+ for (const { path, content } of files) {
325
+ const lines = content.split('\n');
326
+ let m;
327
+ responseSiteRe.lastIndex = 0;
328
+ while ((m = responseSiteRe.exec(content)) !== null) {
329
+ const line = (content.slice(0, m.index).match(/\n/g) || []).length + 1;
330
+ // Look at a window around the site: 5 lines before, 15 lines after
331
+ const start = Math.max(0, line - 6);
332
+ const end = Math.min(lines.length, line + 15);
333
+ const window = lines.slice(start, end).join('\n');
334
+ const hasHeader = retryAfterRe.test(window);
335
+ siteLog.push({ file: path, line, hasHeader });
336
+ if (!hasHeader) {
337
+ evidence.push({
338
+ file: path,
339
+ line,
340
+ snippet: (lines[line - 1] || '').trim() + ' // no Retry-After within surrounding 20 lines',
341
+ });
342
+ }
343
+ }
344
+ }
345
+
346
+ const flagged = siteLog.length > 0 && siteLog.every((s) => !s.hasHeader);
347
+ const partial = siteLog.some((s) => !s.hasHeader) && siteLog.some((s) => s.hasHeader);
348
+ let notes;
349
+ if (siteLog.length === 0) {
350
+ notes = 'No 429 response sites found.';
351
+ } else if (flagged) {
352
+ notes = `${siteLog.length} site(s) returning 429 found; none set a Retry-After header. `
353
+ + `Aigis V1 literal wording ("per-user rate limit") is met, but clients have no retry-backoff signal. `
354
+ + `Add Retry-After computed from the actual bucket TTL.`;
355
+ } else if (partial) {
356
+ notes = 'Some 429 sites set Retry-After, others do not. Review the ones without.';
357
+ } else {
358
+ notes = 'All 429 response sites set a Retry-After header.';
359
+ }
360
+ return { flagged: flagged || partial, evidence, notes };
361
+ }
362
+
363
+ const REGISTRY = {
364
+ kill_switch_restart_latched: killSwitchRestartLatched,
365
+ injection_log_only: injectionLogOnly,
366
+ pii_incomplete_classes: piiIncompleteClasses,
367
+ rate_limit_no_retry_after: rateLimitNoRetryAfter,
368
+ };
369
+
370
+ module.exports = { REGISTRY };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aigis-ai/cli",
3
- "version": "1.0.2",
3
+ "version": "2.0.1",
4
4
  "description": "AI governance guardrails for coding agents. Framework-aligned security and compliance patterns from NIST AI RMF, OWASP Top 10 for LLMs, and ISO/IEC 42001.",
5
5
  "main": "bin/aigis.js",
6
6
  "bin": {
@@ -22,7 +22,11 @@
22
22
  "license": "MIT",
23
23
  "repository": {
24
24
  "type": "git",
25
- "url": "git+https://github.com/aigis-ai/aigis.git"
25
+ "url": "git+https://github.com/NayanKanaparthi/aigis.git"
26
+ },
27
+ "homepage": "https://github.com/NayanKanaparthi/aigis#readme",
28
+ "bugs": {
29
+ "url": "https://github.com/NayanKanaparthi/aigis/issues"
26
30
  },
27
31
  "engines": {
28
32
  "node": ">=18"
@@ -0,0 +1,30 @@
1
+ # Aigis AI Governance
2
+ # Added by: aigis init cursor
3
+ # Docs: https://github.com/aigis-ai/aigis
4
+
5
+ When building any AI or LLM feature, use the aigis CLI for governance patterns:
6
+
7
+ 1. Before writing LLM code, classify the system:
8
+ Run: aigis classify --traits <relevant-traits> --json
9
+
10
+ 2. For EACH recommended file in implement_files, work one at a time:
11
+ a) Fetch one file:
12
+ Run: aigis get <file-id>
13
+ b) Implement the patterns in code
14
+ c) Verify that same file:
15
+ Run: aigis verify <file-id>
16
+ d) Fix FAIL/PARTIAL items until all checks pass
17
+ e) Move to the next file
18
+
19
+ 3. After all files pass, generate compliance docs:
20
+ Run: aigis template <template-id>
21
+
22
+ 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.
23
+
24
+ 4. To audit an existing project:
25
+ Run: aigis audit --scan
26
+
27
+ 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
28
+
29
+ Run "aigis search --list" to see all available governance patterns.
30
+ Run "aigis traits" to see trait descriptions.