@aigis-ai/cli 1.0.0

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -0
  3. package/SKILL.md +74 -0
  4. package/bin/aigis.js +337 -0
  5. package/content/implement/audit-logging.md +171 -0
  6. package/content/implement/bias-monitoring.md +172 -0
  7. package/content/implement/confidence-scoring.md +180 -0
  8. package/content/implement/data-integrity.md +257 -0
  9. package/content/implement/explainability.md +174 -0
  10. package/content/implement/fallback-patterns.md +190 -0
  11. package/content/implement/human-oversight.md +220 -0
  12. package/content/implement/input-validation.md +212 -0
  13. package/content/implement/monitoring.md +207 -0
  14. package/content/implement/output-sanitization.md +183 -0
  15. package/content/implement/pii-handling.md +207 -0
  16. package/content/implement/prompt-security.md +153 -0
  17. package/content/implement/rag-security.md +230 -0
  18. package/content/implement/rate-limiting.md +217 -0
  19. package/content/implement/supply-chain.md +193 -0
  20. package/content/index/audit-scan.md +403 -0
  21. package/content/index/frameworks.md +82 -0
  22. package/content/index/guardrails.json +23 -0
  23. package/content/index/taxonomy.md +81 -0
  24. package/content/templates/ai-impact-assessment.md +54 -0
  25. package/content/templates/intended-purpose-doc.md +39 -0
  26. package/content/templates/risk-characterization.md +34 -0
  27. package/content/templates/third-party-assessment.md +41 -0
  28. package/content/verify/checklist-audit-logging.md +13 -0
  29. package/content/verify/checklist-bias-monitoring.md +13 -0
  30. package/content/verify/checklist-confidence-scoring.md +13 -0
  31. package/content/verify/checklist-data-integrity.md +12 -0
  32. package/content/verify/checklist-explainability.md +13 -0
  33. package/content/verify/checklist-fallback-patterns.md +13 -0
  34. package/content/verify/checklist-human-oversight.md +14 -0
  35. package/content/verify/checklist-input-validation.md +16 -0
  36. package/content/verify/checklist-monitoring.md +13 -0
  37. package/content/verify/checklist-output-sanitization.md +14 -0
  38. package/content/verify/checklist-pii-handling.md +14 -0
  39. package/content/verify/checklist-prompt-security.md +13 -0
  40. package/content/verify/checklist-rag-security.md +12 -0
  41. package/content/verify/checklist-rate-limiting.md +13 -0
  42. package/content/verify/checklist-supply-chain.md +13 -0
  43. package/lib/annotate.js +53 -0
  44. package/lib/classify.js +185 -0
  45. package/lib/fetch.js +112 -0
  46. package/lib/init.js +122 -0
  47. package/lib/keywords.js +139 -0
  48. package/lib/search.js +76 -0
  49. package/package.json +35 -0
@@ -0,0 +1,39 @@
1
+ ---
2
+ id: intended-purpose-doc
3
+ title: Intended Purpose Documentation
4
+ framework: NIST MAP 1.1
5
+ required_when: risk_tier=HIGH OR risk_tier=MEDIUM
6
+ ---
7
+
8
+ # Intended purpose documentation
9
+
10
+ > Maps to NIST AI RMF MAP 1.1. The agent generates this alongside code for medium and high-risk systems.
11
+
12
+ ## System purpose
13
+ - **Primary function:** [Summarize in 1-2 sentences. Focus on WHAT the system does and WHY, not HOW. Example: "Routes insurance claims to appropriate handling tracks based on AI-assessed severity to reduce triage time from 4 hours to under 5 minutes"]
14
+ - **Problem it solves:** [Describe the business problem in user terms, not technical terms. Example: "Manual claim triage is slow and inconsistent across adjusters, causing delays for customers and uneven workloads"]
15
+ - **What it does NOT do:** [limitations, inferred from system type]
16
+
17
+ ## Intended users
18
+ - **Primary users:** [List specific roles, their expertise level, and how they interact with the system. Example: "Claims processors (non-technical, 2+ years claims experience) view AI recommendations in the claims management UI"]
19
+ - **User expertise level:** [Describe the business problem in user terms, not technical terms. Example: "Manual claim triage is slow and inconsistent across adjusters, causing delays for customers and uneven workloads"]
20
+ - **Training required:** [recommended based on system complexity]
21
+
22
+ ## Deployment context
23
+ - **Environment:** [production/staging/internal]
24
+ - **Access scope:** [internal-only / customer-facing / public]
25
+ - **Geographic scope:** [List countries/regions based on jurisdiction traits. If jurisdiction-eu: list EU member states served. If jurisdiction-global: list all regions]
26
+ - **Expected volume:** [If is-high-volume: estimate requests/day and concurrent users. Otherwise: state "Low volume, <1000 requests/day"]
27
+
28
+ ## Known limitations
29
+ - [List 3-5 concrete limitations. Reference known limitations from the model provider. Example: "Cannot verify factual claims in claim descriptions", "Performance degrades below 20-word inputs"]
30
+ - The system should NOT be used for: [generated]
31
+
32
+ ## Legal and regulatory context
33
+ - **Applicable regulations:** [List countries/regions based on jurisdiction traits. If jurisdiction-eu: list EU member states served. If jurisdiction-global: list all regions]
34
+ - **Compliance requirements:** [list of applicable frameworks]
35
+
36
+ ## Stakeholder expectations
37
+ - **Organization:** [alignment with organizational mission — requires human input]
38
+ - **Users:** [what users expect from the system]
39
+ - **Affected individuals:** [what people affected by decisions expect]
@@ -0,0 +1,34 @@
1
+ ---
2
+ id: risk-characterization
3
+ title: Risk Characterization Template
4
+ framework: NIST MAP 5.1
5
+ required_when: risk_tier=HIGH
6
+ ---
7
+
8
+ # Risk characterization
9
+
10
+ > Maps to NIST AI RMF MAP 5.1. Documents likelihood and magnitude of identified impacts.
11
+
12
+ ## Identified risks
13
+
14
+ | # | Risk description | Likelihood | Magnitude | Risk score | Mitigation | Residual risk |
15
+ |---|-----------------|-----------|-----------|------------|------------|---------------|
16
+ | 1 | [Describe one specific failure scenario per row. Be concrete: "LLM assigns severity 2 to a claim that should be 8, causing a legitimate high-severity claim to be fast-tracked instead of escalated"] | 1-5 | 1-5 | L×M | [control reference] | [after mitigation] |
17
+
18
+ ## Risk categories assessed
19
+ - **Accuracy/reliability risks:** [Describe specific ways the system could produce wrong outputs. Example: "Severity score miscalibration on multi-incident claims leads to under-assessment"]
20
+ - **Bias/fairness risks:** [Describe how different groups might receive different outcomes. Example: "Claims written in informal language may receive lower severity scores, correlating with demographic patterns"]
21
+ - **Security risks:** [Describe attack vectors specific to this system. Reference relevant OWASP LLM IDs. Example: "Prompt injection via crafted claim descriptions (LLM01) could manipulate severity scores"]
22
+ - **Privacy risks:** [Describe how sensitive data could be exposed. Example: "Claim descriptions containing medical details could be leaked via LLM output or logs"]
23
+ - **Safety risks:** [Describe how system failures could cause harm. Example: "Under-assessed high-severity claims delay critical payouts, causing financial hardship"]
24
+ - **Transparency risks:** [Describe situations where decisions cannot be explained. Example: "LLM scoring rationale is opaque — adjusters cannot explain to customers why a score was assigned"]
25
+
26
+ ## Impact assessment
27
+ - **Individual impact:** [Describe the concrete harm to one person if the system fails. Example: "A customer with a legitimate $50K claim experiences a 2-week delay and financial stress because the AI routed it to fast-track instead of escalation"]
28
+ - **Group impact:** [Describe how a class of people could be systematically affected. Example: "Non-native English speakers may consistently receive lower severity scores due to writing style bias in the LLM"]
29
+ - **Organizational impact:** [Describe business consequences. Example: "Systematic under-assessment could trigger regulatory investigation, class-action litigation, and reputational damage estimated at $X"]
30
+ - **Societal impact:** [Describe broader effects if this system's pattern were widespread. Example: "Algorithmic bias in insurance claim assessment could deepen existing inequities in financial services access"]
31
+
32
+ ## Risk tolerance
33
+ - **Acceptable risk level:** [This requires human input — state the organization's risk appetite. Example: "False negative rate (under-assessed severe claims) must be below 2%. False positive rate (over-escalated minor claims) acceptable up to 15%."]
34
+ - **Go/no-go recommendation:** [Based on the residual risk analysis above: recommend proceed, proceed with conditions, or do not proceed. State the specific conditions if conditional. Example: "Proceed with conditions: mandatory human review for all claims over $25K, quarterly bias audit, 90-day pilot before full rollout"]
@@ -0,0 +1,41 @@
1
+ ---
2
+ id: third-party-assessment
3
+ title: Third-Party AI Assessment
4
+ framework: NIST GOVERN 6 / OWASP LLM03
5
+ required_when: uses-thirdparty-api AND (risk_tier=HIGH OR risk_tier=MEDIUM)
6
+ ---
7
+
8
+ # Third-party AI assessment
9
+
10
+ > Maps to NIST GOVERN 6.1/6.2 and OWASP LLM03. Documents risks of third-party AI dependencies.
11
+
12
+ ## Provider information
13
+ - **Provider:** [Extract from the import statements or API client initialization in the code. Example: "Anthropic (Claude API)"]
14
+ - **Model:** [Extract from the model parameter in the API call. Example: "claude-sonnet-4-20250514"]
15
+ - **API version:** [auto-fill]
16
+ - **Client library version:** [Read from the dependency file. Example: "anthropic==0.39.0 (from requirements.txt)"]
17
+
18
+ ## Dependency risks
19
+ | Risk | Likelihood | Impact | Mitigation |
20
+ |------|-----------|--------|------------|
21
+ | Model behavior changes on update | Medium | High | Version pinning (supply-chain.md P1) |
22
+ | Provider outage | Low | High | Fallback provider (supply-chain.md P4) |
23
+ | Terms of service change | Low | Medium | Contract review, alternative evaluation |
24
+ | Data residency non-compliance | [check] | High | Verify provider data routing |
25
+ | Model deprecation | Medium | Medium | Migration plan, regression test suite |
26
+
27
+ ## Data handling
28
+ - **Data sent to provider:** [Enumerate every field included in the messages array. Example: "claim_description (redacted), claim_type, date_filed. No PII sent — redacted by pii-handling.md P1"]
29
+ - **PII sent:** Yes/No [should be No — see pii-handling.md]
30
+ - **Data retention by provider:** [Look up the provider's data retention policy. Example: "Anthropic: zero retention on API by default. OpenAI: 30-day retention unless opted out via API"]
31
+ - **Provider's data used for training:** Yes/No [check provider's terms]
32
+
33
+ ## Contingency plan
34
+ - **Fallback provider:** [from supply-chain.md P4]
35
+ - **Fallback behavior:** [from fallback-patterns.md]
36
+ - **Maximum acceptable downtime:** [requires human input]
37
+ - **Migration estimated effort:** [days/weeks]
38
+
39
+ ## Review schedule
40
+ - **Next review date:** [quarterly recommended for high-risk]
41
+ - **Trigger for immediate review:** provider update, incident, terms change
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-audit-logging
3
+ implements: audit-logging
4
+ ---
5
+ # Verification: Audit logging
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Does every LLM interaction produce a structured log entry with trace ID? | MANAGE-4.1/P1 | [ ] | |
10
+ | V2 | Is the trace ID propagated across all system components? | MANAGE-4.1/P2 | [ ] | |
11
+ | V3 | Are AI-influenced decisions logged with full context? | MANAGE-4.1/P3 | [ ] | |
12
+ | V4 | Confirm: no raw PII in log entries. | Anti-pattern | [ ] | |
13
+ | V5 | Confirm: all interactions logged, not just errors. | Anti-pattern | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-bias-monitoring
3
+ implements: bias-monitoring
4
+ ---
5
+ # Verification: Bias monitoring
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Does the logging schema include fairness-enabling metadata fields? | MEASURE-2.11/P1 | [ ] | |
10
+ | V2 | Is there output distribution monitoring across demographic segments? | MEASURE-2.11/P2 | [ ] | |
11
+ | V3 | Is there a periodic fairness report generation mechanism? | MEASURE-2.11/P3 | [ ] | |
12
+ | V4 | Confirm: protected characteristics are NOT collected directly. | Anti-pattern | [ ] | |
13
+ | V5 | Are human override patterns analyzed for bias signals? | Edge case | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-confidence-scoring
3
+ implements: confidence-scoring
4
+ ---
5
+ # Verification: Confidence scoring
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Does every AI response include structured confidence metadata? | LLM09/P1 | [ ] | |
10
+ | V2 | Is there a grounding verification step for RAG-based responses? | LLM09/P2 | [ ] | |
11
+ | V3 | Is AI output framed as recommendation (not fact) in user-facing displays? | LLM09/P3 | [ ] | |
12
+ | V4 | Confirm: no "The AI determined..." framing. Uses "suggests" or "recommends". | Anti-pattern | [ ] | |
13
+ | V5 | Are low-confidence outputs flagged for human review? | Edge case | [ ] | |
@@ -0,0 +1,12 @@
1
+ ---
2
+ id: checklist-data-integrity
3
+ implements: data-integrity
4
+ ---
5
+ # Verification: Data integrity
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is data provenance tracked (source, checksum, ingestion date)? | LLM04/P1 | [ ] | |
10
+ | V2 | Is data validated before entering the vector store / training pipeline? | LLM04/P2 | [ ] | |
11
+ | V3 | Are training/fine-tuning datasets checksummed and versioned? | LLM04/P3 | [ ] | |
12
+ | V4 | Confirm: no unverified external data sources ingested without validation. | Anti-pattern | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-explainability
3
+ implements: explainability
4
+ ---
5
+ # Verification: Explainability
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Does the system generate human-readable explanations for decisions? | MEASURE-2.9/P1 | [ ] | |
10
+ | V2 | Is there a model card documenting purpose, limitations, and performance? | MEASURE-2.9/P2 | [ ] | |
11
+ | V3 | Are decision records stored in an audit-friendly format? | Clause-9.1/P3 | [ ] | |
12
+ | V4 | Confirm: explanations use plain language, not technical jargon. | Anti-pattern | [ ] | |
13
+ | V5 | Is appeal/review information included in decision outputs? | Edge case | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-fallback-patterns
3
+ implements: fallback-patterns
4
+ ---
5
+ # Verification: Fallback patterns
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is there a defined default safe response for LLM failures? | MEASURE-2.6/P1 | [ ] | |
10
+ | V2 | Is there a circuit breaker that trips on repeated failures? | MANAGE-2.4/P2 | [ ] | |
11
+ | V3 | Is there a kill switch that can be toggled without code deployment? | MANAGE-2.4/P3 | [ ] | |
12
+ | V4 | Confirm: no crashes on LLM errors (all exceptions caught). | Anti-pattern | [ ] | |
13
+ | V5 | Is there a defined recovery process after kill switch activation? | Edge case | [ ] | |
@@ -0,0 +1,14 @@
1
+ ---
2
+ id: checklist-human-oversight
3
+ implements: human-oversight
4
+ ---
5
+ # Verification: Human oversight
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Are LLM tools defined as an explicit allowlist (not blocklist)? | LLM06/P1 | [ ] | |
10
+ | V2 | Do write/mutating operations require human approval? | LLM06/P2 | [ ] | |
11
+ | V3 | Is there action rate limiting for LLM-initiated actions? | LLM06/P3 | [ ] | |
12
+ | V4 | Does every AI-influenced response include an override mechanism? | LLM06/P4 | [ ] | |
13
+ | V5 | Is there an audit trail for every LLM-initiated action? | Anti-pattern | [ ] | |
14
+ | V6 | For low-confidence outputs, is human review required? | Edge case | [ ] | |
@@ -0,0 +1,16 @@
1
+ ---
2
+ id: checklist-input-validation
3
+ implements: input-validation
4
+ ---
5
+ # Verification: Input validation
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is there a maximum input length check (characters and/or tokens) before the LLM call? | LLM01/P1 | [ ] | |
10
+ | V2 | Does the code use API native role separation (system vs user messages), not string concatenation? | LLM01/P2 | [ ] | |
11
+ | V3 | Is there a sanitization function stripping control characters and zero-width Unicode before the LLM call? | LLM01/P3 | [ ] | |
12
+ | V4 | Is LLM output validated against a defined schema before downstream use? | LLM01/P4 | [ ] | |
13
+ | V5 | Is there an injection pattern detection layer (even if advisory/logging-only)? | LLM01/P5 | [ ] | |
14
+ | V6 | Confirm: no string concatenation or f-strings used to build prompts. | Anti-pattern | [ ] | |
15
+ | V7 | Confirm: input exceeding length limits returns an error, not silent truncation. | Anti-pattern | [ ] | |
16
+ | V8 | If system processes documents/files: is extracted text sanitized with same pipeline as direct input? | Edge case | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-monitoring
3
+ implements: monitoring
4
+ ---
5
+ # Verification: Monitoring
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Are key metrics (latency, error rate, override rate, cost) tracked? | MANAGE-4.1/P1 | [ ] | |
10
+ | V2 | Is there output drift detection comparing recent to baseline? | MANAGE-4.1/P2 | [ ] | |
11
+ | V3 | Is there a user feedback mechanism (agree/disagree/escalate)? | MANAGE-4.2/P3 | [ ] | |
12
+ | V4 | Is there structured incident logging? | MANAGE-4.3/P4 | [ ] | |
13
+ | V5 | Confirm: monitoring is active from day one, not added later. | Anti-pattern | [ ] | |
@@ -0,0 +1,14 @@
1
+ ---
2
+ id: checklist-output-sanitization
3
+ implements: output-sanitization
4
+ ---
5
+ # Verification: Output sanitization
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is LLM output encoded/escaped before rendering in HTML? | LLM05/P2 | [ ] | |
10
+ | V2 | Are database operations using parameterized queries, not string interpolation with LLM output? | LLM05/P3 | [ ] | |
11
+ | V3 | If LLM generates code for execution, is it sandboxed? | LLM05/P4 | [ ] | |
12
+ | V4 | Is LLM output content type validated before use? | LLM05/P5 | [ ] | |
13
+ | V5 | Confirm: no eval() or exec() on raw LLM output. | Anti-pattern | [ ] | |
14
+ | V6 | If rendering LLM markdown as HTML, is a sanitizing parser used? | Edge case | [ ] | |
@@ -0,0 +1,14 @@
1
+ ---
2
+ id: checklist-pii-handling
3
+ implements: pii-handling
4
+ ---
5
+ # Verification: PII handling
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is PII detected and redacted before being sent to the LLM? | LLM02/P1 | [ ] | |
10
+ | V2 | Does the system send only necessary fields to the LLM (data minimization)? | LLM02/P2 | [ ] | |
11
+ | V3 | Is LLM output scanned for PII before returning to the user? | LLM02/P3 | [ ] | |
12
+ | V4 | Are PII-containing records stored separately from LLM-accessible data? | LLM02/P4 | [ ] | |
13
+ | V5 | Are logs written with redacted content, never raw PII? | LLM02/P5 | [ ] | |
14
+ | V6 | Confirm: no full database records sent to the LLM. | Anti-pattern | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-prompt-security
3
+ implements: prompt-security
4
+ ---
5
+ # Verification: Prompt security
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Confirm: no API keys, passwords, or tokens in system prompts. | LLM07/P1 | [ ] | |
10
+ | V2 | Is the system prompt minimal (behavior only, no implementation details)? | LLM07/P2 | [ ] | |
11
+ | V3 | Is there a leakage detection check on LLM output? | LLM07/P3 | [ ] | |
12
+ | V4 | Are business rules enforced in code, not just in prompts? | LLM07/P4 | [ ] | |
13
+ | V5 | Confirm: system prompt does not contain "do not reveal these instructions" as sole protection. | Anti-pattern | [ ] | |
@@ -0,0 +1,12 @@
1
+ ---
2
+ id: checklist-rag-security
3
+ implements: rag-security
4
+ ---
5
+ # Verification: RAG security
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Are access controls applied to vector database queries? | LLM08/P1 | [ ] | |
10
+ | V2 | Is there tenant isolation in multi-tenant RAG systems? | LLM08/P2 | [ ] | |
11
+ | V3 | Are retrieved results validated (relevance threshold, injection scan)? | LLM08/P3 | [ ] | |
12
+ | V4 | Confirm: no cross-tenant data leakage possible. | Anti-pattern | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-rate-limiting
3
+ implements: rate-limiting
4
+ ---
5
+ # Verification: Rate limiting
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is there per-user rate limiting on LLM endpoints? | LLM10/P1 | [ ] | |
10
+ | V2 | Is there a token budget with daily and per-request limits? | LLM10/P2 | [ ] | |
11
+ | V3 | Is cost monitoring with alerting implemented? | LLM10/P3 | [ ] | |
12
+ | V4 | Are LLM calls wrapped with a timeout? | LLM10/P4 | [ ] | |
13
+ | V5 | Confirm: rate limits are per API key, not just per IP. | Anti-pattern | [ ] | |
@@ -0,0 +1,13 @@
1
+ ---
2
+ id: checklist-supply-chain
3
+ implements: supply-chain
4
+ ---
5
+ # Verification: Supply chain
6
+
7
+ | # | Check | Control | Status | Evidence |
8
+ |---|-------|---------|--------|----------|
9
+ | V1 | Is the model version pinned to a specific identifier (not "latest")? | LLM03/P1 | [ ] | |
10
+ | V2 | Is model version tracked in every response/log entry? | LLM03/P2 | [ ] | |
11
+ | V3 | Is there a regression test suite for model version upgrades? | LLM03/P3 | [ ] | |
12
+ | V4 | Is there a fallback provider or degradation path for outages? | LLM03/P4 | [ ] | |
13
+ | V5 | Confirm: client library versions are also pinned. | Anti-pattern | [ ] | |
@@ -0,0 +1,53 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+
5
+ const AIGIS_DIR = path.join(os.homedir(), '.aigis');
6
+ const ANNOTATIONS_FILE = path.join(AIGIS_DIR, 'annotations.json');
7
+
8
+ function ensureDir() {
9
+ if (!fs.existsSync(AIGIS_DIR)) {
10
+ fs.mkdirSync(AIGIS_DIR, { recursive: true });
11
+ }
12
+ }
13
+
14
+ function loadAnnotations() {
15
+ if (!fs.existsSync(ANNOTATIONS_FILE)) return {};
16
+ try {
17
+ return JSON.parse(fs.readFileSync(ANNOTATIONS_FILE, 'utf8'));
18
+ } catch {
19
+ return {};
20
+ }
21
+ }
22
+
23
+ function saveAnnotations(data) {
24
+ ensureDir();
25
+ fs.writeFileSync(ANNOTATIONS_FILE, JSON.stringify(data, null, 2));
26
+ }
27
+
28
+ function annotate(fileId, note) {
29
+ const data = loadAnnotations();
30
+ if (!data[fileId]) data[fileId] = [];
31
+ data[fileId].push({
32
+ note,
33
+ date: new Date().toISOString().split('T')[0],
34
+ });
35
+ saveAnnotations(data);
36
+ }
37
+
38
+ function getAnnotations(fileId) {
39
+ const data = loadAnnotations();
40
+ return data[fileId] || [];
41
+ }
42
+
43
+ function listAnnotations() {
44
+ return loadAnnotations();
45
+ }
46
+
47
+ function clearAnnotation(fileId) {
48
+ const data = loadAnnotations();
49
+ delete data[fileId];
50
+ saveAnnotations(data);
51
+ }
52
+
53
+ module.exports = { annotate, getAnnotations, listAnnotations, clearAnnotation };
@@ -0,0 +1,185 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const ALL_TRAITS = [
5
+ 'uses-llm', 'uses-rag', 'uses-finetuned', 'uses-thirdparty-api', 'is-agentic', 'is-multimodal',
6
+ 'processes-pii', 'handles-financial', 'handles-health', 'handles-proprietary', 'handles-minors',
7
+ 'influences-decisions', 'accepts-user-input', 'is-external', 'is-internal', 'is-high-volume',
8
+ 'generates-code', 'generates-content', 'multi-model-pipeline',
9
+ 'jurisdiction-eu', 'jurisdiction-us-regulated', 'jurisdiction-global',
10
+ ];
11
+
12
+ const TRAIT_FILES = {
13
+ 'uses-llm': ['input-validation', 'output-sanitization', 'prompt-security', 'audit-logging', 'monitoring'],
14
+ 'uses-rag': ['rag-security', 'data-integrity'],
15
+ 'uses-finetuned': ['data-integrity', 'supply-chain'],
16
+ 'uses-thirdparty-api': ['supply-chain'],
17
+ 'is-agentic': ['human-oversight', 'rate-limiting', 'fallback-patterns', 'audit-logging'],
18
+ 'is-multimodal': ['input-validation', 'output-sanitization', 'pii-handling'],
19
+ 'processes-pii': ['pii-handling', 'audit-logging'],
20
+ 'handles-financial': ['pii-handling', 'audit-logging', 'bias-monitoring'],
21
+ 'handles-health': ['pii-handling', 'audit-logging', 'bias-monitoring', 'explainability'],
22
+ 'handles-proprietary': ['pii-handling', 'prompt-security'],
23
+ 'handles-minors': ['pii-handling', 'bias-monitoring', 'human-oversight'],
24
+ 'influences-decisions': ['bias-monitoring', 'confidence-scoring', 'human-oversight', 'explainability'],
25
+ 'accepts-user-input': ['input-validation', 'output-sanitization'],
26
+ 'is-external': ['rate-limiting', 'confidence-scoring'],
27
+ 'is-internal': [],
28
+ 'is-high-volume': ['rate-limiting', 'monitoring', 'fallback-patterns'],
29
+ 'generates-code': ['output-sanitization', 'human-oversight', 'fallback-patterns'],
30
+ 'generates-content': ['confidence-scoring', 'bias-monitoring', 'audit-logging'],
31
+ 'multi-model-pipeline': ['audit-logging', 'monitoring', 'fallback-patterns', 'data-integrity'],
32
+ 'jurisdiction-eu': [],
33
+ 'jurisdiction-us-regulated': [],
34
+ 'jurisdiction-global': [],
35
+ };
36
+
37
+ const FILE_CONTROLS = {
38
+ 'input-validation': { owasp: ['LLM01'], nist: ['MEASURE-2.7', 'MANAGE-1.3'], iso: ['Clause-8.2', 'Annex-A.6'] },
39
+ 'output-sanitization': { owasp: ['LLM05'], nist: ['MEASURE-2.6', 'MEASURE-2.7'], iso: ['Clause-8.2'] },
40
+ 'pii-handling': { owasp: ['LLM02'], nist: ['MAP-2.1', 'MEASURE-2.10'], iso: ['Annex-A.7', 'Annex-A.4'] },
41
+ 'prompt-security': { owasp: ['LLM07'], nist: ['MEASURE-2.7', 'MEASURE-2.8'], iso: ['Clause-8.2'] },
42
+ 'human-oversight': { owasp: ['LLM06'], nist: ['MAP-3.5', 'MANAGE-1.3', 'MANAGE-4.1'], iso: ['Annex-A.9', 'Clause-8.4'] },
43
+ 'supply-chain': { owasp: ['LLM03'], nist: ['GOVERN-6.1', 'GOVERN-6.2', 'MANAGE-3.1', 'MANAGE-3.2'], iso: ['Annex-A.10'] },
44
+ 'data-integrity': { owasp: ['LLM04'], nist: ['MAP-2.3', 'MEASURE-2.6'], iso: ['Annex-A.7'] },
45
+ 'rag-security': { owasp: ['LLM08'], nist: ['MEASURE-2.7'], iso: ['Clause-8.2', 'Annex-A.7'] },
46
+ 'confidence-scoring': { owasp: ['LLM09'], nist: ['MAP-2.2', 'MEASURE-2.5', 'MEASURE-2.9'], iso: ['Annex-A.8'] },
47
+ 'rate-limiting': { owasp: ['LLM10'], nist: ['MEASURE-2.6', 'MANAGE-2.4'], iso: ['Clause-8.2'] },
48
+ 'audit-logging': { owasp: [], nist: ['MEASURE-2.8', 'MANAGE-4.1', 'MANAGE-4.3'], iso: ['Clause-9.1', 'Annex-A.6'] },
49
+ 'bias-monitoring': { owasp: [], nist: ['MAP-2.3', 'MEASURE-2.11', 'MEASURE-3.1'], iso: ['Clause-6.1', 'Annex-C'] },
50
+ 'fallback-patterns': { owasp: [], nist: ['MEASURE-2.6', 'MANAGE-2.3', 'MANAGE-2.4'], iso: ['Clause-8.2'] },
51
+ 'monitoring': { owasp: [], nist: ['MEASURE-2.4', 'MEASURE-3.1', 'MANAGE-4.1', 'MANAGE-4.2'], iso: ['Clause-9.1', 'Clause-10'] },
52
+ 'explainability': { owasp: [], nist: ['MEASURE-2.8', 'MEASURE-2.9'], iso: ['Annex-A.8', 'Clause-7.4'] },
53
+ };
54
+
55
+ function classify(traitList) {
56
+ const ts = new Set(traitList);
57
+ const warnings = [];
58
+
59
+ // Validate traits
60
+ const invalid = traitList.filter(t => !ALL_TRAITS.includes(t));
61
+ if (invalid.length > 0) {
62
+ throw new Error(`Unknown traits: ${invalid.join(', ')}. Run "aigis traits" to see available traits.`);
63
+ }
64
+
65
+ // Constraint C1: is-internal + is-external
66
+ if (ts.has('is-internal') && ts.has('is-external')) {
67
+ warnings.push('Both is-internal and is-external selected. Treating as is-external (stricter).');
68
+ ts.delete('is-internal');
69
+ }
70
+
71
+ // Step 1: Trait-based file selection
72
+ const files = new Set();
73
+ for (const t of ts) {
74
+ for (const f of (TRAIT_FILES[t] || [])) {
75
+ files.add(f);
76
+ }
77
+ }
78
+
79
+ // Step 2: Risk tier
80
+ const sensData = ts.has('processes-pii') || ts.has('handles-financial') || ts.has('handles-health') || ts.has('handles-proprietary') || ts.has('handles-minors');
81
+
82
+ let tier = 'LOW';
83
+ let reason = 'no high/medium triggers';
84
+
85
+ if (ts.has('influences-decisions')) { tier = 'HIGH'; reason = 'influences-decisions'; }
86
+ else if (ts.has('handles-health')) { tier = 'HIGH'; reason = 'handles-health'; }
87
+ else if (ts.has('handles-financial') && ts.has('accepts-user-input')) { tier = 'HIGH'; reason = 'handles-financial + accepts-user-input'; }
88
+ else if (ts.has('handles-minors')) { tier = 'HIGH'; reason = 'handles-minors'; }
89
+ else if ((ts.has('jurisdiction-eu') || ts.has('jurisdiction-global')) && sensData) { tier = 'HIGH'; reason = 'jurisdiction-eu + sensitive data'; }
90
+ else if (ts.has('generates-code') && ts.has('is-external')) { tier = 'HIGH'; reason = 'generates-code + is-external'; }
91
+ else if (ts.has('generates-code') && ts.has('is-agentic')) { tier = 'HIGH'; reason = 'generates-code + is-agentic'; }
92
+ else if (ts.has('processes-pii')) { tier = 'MEDIUM'; reason = 'processes-pii'; }
93
+ else if (ts.has('is-external')) { tier = 'MEDIUM'; reason = 'is-external'; }
94
+ else if (ts.has('is-agentic')) { tier = 'MEDIUM'; reason = 'is-agentic'; }
95
+ else if (ts.has('handles-proprietary')) { tier = 'MEDIUM'; reason = 'handles-proprietary'; }
96
+ else if (ts.has('generates-content')) { tier = 'MEDIUM'; reason = 'generates-content'; }
97
+ else if (ts.has('multi-model-pipeline')) { tier = 'MEDIUM'; reason = 'multi-model-pipeline'; }
98
+ else if (ts.has('jurisdiction-us-regulated')) { tier = 'MEDIUM'; reason = 'jurisdiction-us-regulated'; }
99
+ else if (ts.has('generates-code')) { tier = 'MEDIUM'; reason = 'generates-code'; }
100
+
101
+ // Jurisdiction modifier
102
+ if ((ts.has('jurisdiction-eu') || ts.has('jurisdiction-global')) && tier !== 'HIGH') {
103
+ const oldTier = tier;
104
+ tier = tier === 'LOW' ? 'MEDIUM' : 'HIGH';
105
+ reason += ` (elevated from ${oldTier} by EU/global jurisdiction)`;
106
+ }
107
+
108
+ // Step 3: Guardrails
109
+ const guardrailsFired = [];
110
+
111
+ const guardrails = [
112
+ { id: 'G1', cond: () => sensData && !files.has('audit-logging'), file: 'audit-logging', rationale: 'Sensitive data requires traceability' },
113
+ { id: 'G2', cond: () => ts.has('handles-health') && !files.has('bias-monitoring'), file: 'bias-monitoring', rationale: 'Health data has demographic bias risks' },
114
+ { id: 'G3', cond: () => ts.has('handles-financial') && ts.has('influences-decisions') && !files.has('fallback-patterns'), file: 'fallback-patterns', rationale: 'Financial decisions need safe failure' },
115
+ { id: 'G4', cond: () => ts.has('is-agentic') && !files.has('human-oversight'), file: 'human-oversight', rationale: 'Autonomous systems need oversight' },
116
+ { id: 'G5', cond: () => ts.has('generates-code') && !files.has('output-sanitization'), file: 'output-sanitization', rationale: 'Generated code is execution risk' },
117
+ { id: 'G6', cond: () => ts.has('jurisdiction-eu') && !files.has('explainability'), file: 'explainability', rationale: 'EU AI Act requires explainability' },
118
+ { id: 'G7', cond: () => ts.has('jurisdiction-eu') && !files.has('bias-monitoring'), file: 'bias-monitoring', rationale: 'EU AI Act mandates non-discrimination' },
119
+ { id: 'G8', cond: () => ts.has('handles-minors') && !files.has('human-oversight'), file: 'human-oversight', rationale: 'Systems affecting children require review' },
120
+ { id: 'G9', cond: () => ts.has('multi-model-pipeline') && !files.has('monitoring'), file: 'monitoring', rationale: 'Multi-model compounding failures' },
121
+ { id: 'G10', cond: () => tier === 'HIGH' && !files.has('monitoring'), file: 'monitoring', rationale: 'High-risk systems need monitoring' },
122
+ { id: 'G11', cond: () => tier === 'HIGH' && !files.has('fallback-patterns'), file: 'fallback-patterns', rationale: 'High-risk systems must fail safely' },
123
+ { id: 'G13', cond: () => ts.has('jurisdiction-us-regulated') && !files.has('audit-logging'), file: 'audit-logging', rationale: 'US regulated industries need audit trails' },
124
+ { id: 'G14', cond: () => ts.has('jurisdiction-us-regulated') && !files.has('human-oversight'), file: 'human-oversight', rationale: 'US regulated industries need human review' },
125
+ { id: 'G15', cond: () => ts.has('generates-code') && !files.has('human-oversight'), file: 'human-oversight', rationale: 'Code generation needs human review' },
126
+ ];
127
+
128
+ // Removal guardrail
129
+ if (ts.has('uses-llm') && !ts.has('uses-thirdparty-api') && files.has('supply-chain')) {
130
+ files.delete('supply-chain');
131
+ guardrailsFired.push({ id: 'G12', action: 'REMOVE supply-chain', rationale: 'Self-hosted models skip third-party controls' });
132
+ }
133
+
134
+ for (const g of guardrails) {
135
+ if (g.cond()) {
136
+ files.add(g.file);
137
+ guardrailsFired.push({ id: g.id, action: `ADD ${g.file}`, rationale: g.rationale });
138
+ }
139
+ }
140
+
141
+ // Step 4: Templates
142
+ const templates = [];
143
+ if (tier === 'HIGH' || ts.has('jurisdiction-eu') || ts.has('jurisdiction-global') || ts.has('influences-decisions')) {
144
+ templates.push('ai-impact-assessment', 'intended-purpose-doc', 'risk-characterization');
145
+ } else if (tier === 'MEDIUM' || ts.has('jurisdiction-us-regulated')) {
146
+ templates.push('intended-purpose-doc');
147
+ }
148
+ if (ts.has('uses-thirdparty-api') && tier !== 'LOW') {
149
+ templates.push('third-party-assessment');
150
+ }
151
+ // Jurisdiction overrides
152
+ if (ts.has('jurisdiction-us-regulated') && !templates.includes('ai-impact-assessment')) {
153
+ templates.unshift('ai-impact-assessment');
154
+ }
155
+
156
+ // Step 5: Collect control IDs
157
+ const allOwasp = new Set();
158
+ const allNist = new Set();
159
+ const allIso = new Set();
160
+ for (const f of files) {
161
+ const c = FILE_CONTROLS[f];
162
+ if (c) {
163
+ c.owasp.forEach(x => allOwasp.add(x));
164
+ c.nist.forEach(x => allNist.add(x));
165
+ c.iso.forEach(x => allIso.add(x));
166
+ }
167
+ }
168
+
169
+ return {
170
+ risk_tier: tier,
171
+ reason,
172
+ traits: [...ts],
173
+ implement_files: [...files].sort(),
174
+ templates: [...new Set(templates)],
175
+ guardrails_fired: guardrailsFired,
176
+ warnings,
177
+ controls: {
178
+ owasp: [...allOwasp].sort(),
179
+ nist: [...allNist].sort(),
180
+ iso: [...allIso].sort(),
181
+ },
182
+ };
183
+ }
184
+
185
+ module.exports = { classify, ALL_TRAITS };