contextos-agents 2.0.0 → 2.1.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 (45) hide show
  1. package/.agents/AGENTS.md +53 -33
  2. package/.agents/adapters/aider/export.js +41 -14
  3. package/.agents/adapters/claude/export.js +1 -1
  4. package/.agents/adapters/copilot/export.js +1 -1
  5. package/.agents/adapters/cursor/export.js +1 -1
  6. package/.agents/adapters/drift-detector.js +80 -7
  7. package/.agents/adapters/gemini/export.js +1 -1
  8. package/.agents/adapters/pure-compiler.js +10 -0
  9. package/.agents/adapters/shared.js +13 -4
  10. package/.agents/adapters/zed/export.js +1 -1
  11. package/.agents/compiled/registry.v2.json +29 -25
  12. package/.agents/compiled/registry.v2.sha256 +1 -1
  13. package/.agents/core/skills/context-os/SKILL.md +34 -37
  14. package/.agents/core/skills/engineering-workflow/SKILL.md +24 -24
  15. package/.agents/core/skills/gemini-precision/EXAMPLES.md +72 -0
  16. package/.agents/core/skills/gemini-precision/SKILL.md +2 -1
  17. package/.agents/core/skills/gemini-precision/TROUBLESHOOTING.md +25 -0
  18. package/.agents/core/skills/gemini-precision/skill.yaml +2 -0
  19. package/.agents/core/skills/gstack-roles/SKILL.md +7 -6
  20. package/.agents/core/skills/security/SKILL.md +44 -16
  21. package/.agents/core/skills/security/skill.yaml +0 -1
  22. package/.agents/ctx.js +16 -10
  23. package/.agents/generated/claude/skills/context-os/SKILL.md +34 -37
  24. package/.agents/generated/claude/skills/engineering-workflow/SKILL.md +24 -24
  25. package/.agents/generated/claude/skills/gemini-precision/SKILL.md +102 -1
  26. package/.agents/generated/claude/skills/gstack-roles/SKILL.md +7 -6
  27. package/.agents/generated/claude/skills/security/SKILL.md +44 -16
  28. package/.agents/generated/gemini/skills/context-os/SKILL.md +34 -37
  29. package/.agents/generated/gemini/skills/engineering-workflow/SKILL.md +24 -24
  30. package/.agents/generated/gemini/skills/gemini-precision/SKILL.md +105 -1
  31. package/.agents/generated/gemini/skills/gstack-roles/SKILL.md +7 -6
  32. package/.agents/generated/gemini/skills/security/SKILL.md +44 -125
  33. package/.agents/plugins.js +5 -4
  34. package/.agents/resolver/canonical-resolver.js +7 -7
  35. package/.agents/validate.js +69 -1
  36. package/README.md +80 -23
  37. package/bin/commands/hook.js +129 -0
  38. package/bin/commands/scan.js +70 -0
  39. package/bin/commands.js +39 -1
  40. package/bin/index.js +144 -33
  41. package/bin/lib/gate.js +171 -0
  42. package/bin/lib/git-snapshot.js +187 -0
  43. package/bin/lib/scan.js +380 -0
  44. package/package.json +4 -2
  45. package/.agents/core/skills/security/security.md +0 -106
@@ -1 +1 @@
1
- sha256:c15f3691d9ed833630152b65959fdef465d88a7cf5bb27d44a086621e20c89c1 registry.v2.json
1
+ sha256:938c5051454535087e03f26af35c434cf194f414d2ec8044b4ae754e8524cf37 registry.v2.json
@@ -8,11 +8,11 @@ description: >-
8
8
 
9
9
  ## Overview
10
10
 
11
- Deterministic context compiler and policy engine for AI coding agents. Standardizes software engineering workflows across requirements, architecture, atomic task planning, implementation, verification, and release.
11
+ Deterministic context compiler and policy engine for AI coding agents. Governs repository policy configuration, skill dependency graphs, profile management, and multi-agent configuration export.
12
12
 
13
13
  ## When to Use
14
14
 
15
- Activate as the root meta-orchestrator across all development phases to ensure role consistency, quality gates, and structured execution.
15
+ Activate when managing project configuration, resolving skill dependencies, compiling rules for editors, or defining repository-level agent standards. (For task-specific file and context budgeting, use `context-manager`).
16
16
 
17
17
  ## Rules & Patterns
18
18
 
@@ -46,10 +46,10 @@ intent:
46
46
  For each required layer, load the skill graph:
47
47
 
48
48
  1. Read `skill.yaml` from each relevant skill directory
49
- 2. Resolve `requires` — load mandatory dependencies
50
- 3. Check `conflicts` — ensure no incompatible skills are loaded
51
- 4. Apply `optional` — suggest but don't force
52
- 5. Respect project profile (if set) — apply rules from `profiles/`
49
+ 2. Resolve `requires` - load mandatory dependencies
50
+ 3. Check `conflicts` - ensure no incompatible skills are loaded
51
+ 4. Apply `optional` - suggest but don't force
52
+ 5. Respect project profile (if set) - apply rules from `profiles/`
53
53
 
54
54
  **Dependency resolution example:**
55
55
 
@@ -67,48 +67,45 @@ Suggested: [tailwind, prisma, next-auth]
67
67
 
68
68
  Assemble context from three levels:
69
69
 
70
- **Level 1 — Vision (always available):**
70
+ **Level 1 - Vision (always available):**
71
71
 
72
- - `docs/PRD.md` — what are we building
73
- - `docs/ROADMAP.md` — where are we going
74
- - `docs/PROJECT_GRAPH.md` — project structure
72
+ - `docs/PRD.md` - what are we building
73
+ - `docs/ROADMAP.md` - where are we going
74
+ - `docs/PROJECT_GRAPH.md` - project structure
75
+ - `docs/API.md` - API specification (optional, when backend API layer is present)
76
+ - `docs/UI.md` - UI/UX specification (optional, when UI layer is present)
75
77
 
76
- **Level 2 — Architecture (load when needed):**
78
+ **Level 2 - Architecture (load when needed):**
77
79
 
78
- - `docs/ARCHITECTURE.md` — system design
79
- - `docs/DATABASE.md` — data model
80
- - `docs/API.md` — API contracts
81
- - `docs/decisions/` — prior decisions
80
+ - `docs/ARCHITECTURE.md` - system design and boundaries
81
+ - `docs/decisions/` - architecture decision records (ADRs)
82
+ - `docs/PRODUCT_BOUNDARIES.md` - maturity boundaries and non-promises
83
+ - `references/context-rules.md` - dynamic context selection and compilation rules
82
84
 
83
- **Level 3 — Development (load per task):**
85
+ **Level 3 - Task-Specific Context (load per task):**
84
86
 
85
- - Relevant skill `.md` files
86
- - `docs/UI.md` — for frontend tasks
87
- - `docs/TASKS.md` — current sprint
87
+ - Relevant skill documents from `.agents/skills/`
88
+ - Target code and test files within planned blast radius
88
89
 
89
- **Context Filtering Rules:**
90
- See `references/context-rules.md` for the full mapping of task types to required documents.
90
+ ### Stage 4: Focused Context Selection
91
91
 
92
- ### Stage 4: Prompt Optimization
92
+ Before sending context to the AI coding assistant:
93
93
 
94
- Before sending to the AI agent:
94
+ 1. Select only skills relevant to the task domain and touched files
95
+ 2. Prioritize: task goal > architectural constraints > project conventions
96
+ 3. Include active Decision Records that affect the target component
97
+ 4. Enforce quality guardrails and verification criteria
95
98
 
96
- 1. Remove sections not relevant to the current task
97
- 2. Prioritize: current task context > architecture > vision
98
- 3. Include recent Decision Records that affect the current task
99
- 4. Add coding rules from the loaded skills
100
-
101
- ## Commands
99
+ ## Core CLI Commands
102
100
 
103
101
  | Command | Action |
104
102
  | --- | --- |
105
- | `ctx init` | Analyze project idea, generate all docs |
106
- | `ctx plan` | Generate development plan from PRD |
107
- | `ctx compile` | Compile context for a specific task |
108
- | `ctx update` | Update changed documents |
109
- | `ctx graph` | Show/update Project Graph |
110
- | `ctx doctor` | Validate skill dependencies, check for conflicts |
111
- | `ctx explain` | Explain why specific context was loaded |
103
+ | `contextos init` | Initialize `.agents/` folder and bootstrap profiles |
104
+ | `contextos export <agent>` | Compile skills for target agent (`gemini`, `claude`, `cursor`, `copilot`, `aider`, `zed`, `all`) |
105
+ | `contextos resolve "<task>"` | Dynamically resolve relevant skills, rules, and risk level for task |
106
+ | `contextos validate` | Validate skill schemas, dependencies, and detect configuration drift |
107
+ | `contextos doctor` | Pre-flight diagnostics for skills, profiles, and compiler synchronization |
108
+ | `contextos watch` | Background file watcher for continuous auto-compilation |
112
109
 
113
110
  ## Project Initialization Flow
114
111
 
@@ -126,7 +123,7 @@ When user says something like "Сделай CRM для стоматологии"
126
123
  3. **Select profile** (startup/enterprise/mvp/hackathon)
127
124
  4. **Resolve skills** (Stage 2)
128
125
  5. **Generate all documents** using `generators/` skill
129
- 6. **Create Project Graph** — the master map of modules → features → tasks → files → skills
126
+ 6. **Create Project Graph** - the master map of modules -> features -> tasks -> files -> skills
130
127
  7. **Output agent config** using `adapters/` skill
131
128
 
132
129
  ## Skill Discovery
@@ -45,7 +45,7 @@ Inspired by [addyosmani/agent-skills](https://github.com/addyosmani/agent-skills
45
45
 
46
46
  ---
47
47
 
48
- ### Phase 1: DEFINE — /spec
48
+ ### Phase 1: DEFINE - /spec
49
49
 
50
50
  **Auto-activates → `[ROLE: Product Manager]`**
51
51
 
@@ -79,8 +79,8 @@ Before writing the spec, if there is ambiguity, high blast radius, or multiple a
79
79
  ### Technical Approach
80
80
  [Read the relevant code. Understand what changes where.]
81
81
  Files affected:
82
- - `src/X.js` — [what changes]
83
- - `src/Y.js` — [what changes]
82
+ - `src/X.js` - [what changes]
83
+ - `src/Y.js` - [what changes]
84
84
 
85
85
  ### Acceptance Criteria
86
86
  - [ ] Given [context], when [action], then [result]
@@ -93,7 +93,7 @@ Files affected:
93
93
 
94
94
  ---
95
95
 
96
- ### Phase 2: PLAN — /plan
96
+ ### Phase 2: PLAN - /plan
97
97
 
98
98
  **Auto-activates → `[ROLE: Architect]`**
99
99
 
@@ -111,7 +111,7 @@ Organize tasks as **Thin Vertical Slices** rather than horizontal layers:
111
111
  - Each task must be **completable in < 2 hours** of focused work.
112
112
  - Each task must be **independently testable**.
113
113
  - Tasks must be **ordered by dependency** (blocking tasks first).
114
- - Each task gets a **test requirement** — no task without a test.
114
+ - Each task gets a **test requirement** - no task without a test.
115
115
 
116
116
  #### Plan Template
117
117
 
@@ -136,13 +136,13 @@ Organize tasks as **Thin Vertical Slices** rather than horizontal layers:
136
136
  - [Risk 1]: [Mitigation]
137
137
  - [Risk 2]: [Mitigation]
138
138
 
139
- ### STOP — Awaiting Approval
139
+ ### STOP - Awaiting Approval
140
140
  Do not proceed to BUILD until this plan is approved.
141
141
  ```
142
142
 
143
143
  ---
144
144
 
145
- ### Phase 3: BUILD — /build
145
+ ### Phase 3: BUILD - /build
146
146
 
147
147
  **Auto-activates → `[ROLE: Senior Developer]`**
148
148
 
@@ -150,12 +150,12 @@ Implement one task at a time. Commit after each task.
150
150
 
151
151
  #### Build Rules
152
152
 
153
- 1. **One task per commit** — atomic, descriptive commit messages.
154
- 2. **Write the test FIRST** (TDD — red-green-refactor).
155
- 3. **No dead code** — if it's not tested, it's not shipped.
156
- 4. **No TODOs in committed code** — resolve or create a tracked issue.
157
- 5. **Read before writing** — understand the surrounding code before changing it.
158
- 6. **Limit the blast radius** — modify ONLY the files explicitly listed in the current task's plan. Do NOT rewrite adjacent components, hooks, or utilities unless strictly required AND approved.
153
+ 1. **One task per commit** - atomic, descriptive commit messages.
154
+ 2. **Write the test FIRST** (TDD - red-green-refactor).
155
+ 3. **No dead code** - if it's not tested, it's not shipped.
156
+ 4. **No TODOs in committed code** - resolve or create a tracked issue.
157
+ 5. **Read before writing** - understand the surrounding code before changing it.
158
+ 6. **Limit the blast radius** - modify ONLY the files explicitly listed in the current task's plan. Do NOT rewrite adjacent components, hooks, or utilities unless strictly required AND approved.
159
159
 
160
160
  #### Commit Message Format
161
161
 
@@ -172,7 +172,7 @@ Types: `feat`, `fix`, `refactor`, `test`, `docs`, `chore`
172
172
 
173
173
  ---
174
174
 
175
- ### Phase 4: VERIFY — /test
175
+ ### Phase 4: VERIFY - /test
176
176
 
177
177
  **Auto-activates → `[ROLE: QA Lead]`**
178
178
 
@@ -193,7 +193,7 @@ Tests are proof, not an afterthought.
193
193
 
194
194
  For complex React components, prioritize testing _user behavior_ over internal state:
195
195
 
196
- - Use **React Testing Library** (`userEvent`, `screen.getByRole`) — test what the user sees.
196
+ - Use **React Testing Library** (`userEvent`, `screen.getByRole`) - test what the user sees.
197
197
  - Use **Playwright** for critical user flows (login, checkout, form submit).
198
198
  - Do NOT test implementation details (internal state, private methods, component structure).
199
199
  - Focus on: "When user clicks X, does Y appear?" not "Does `useState` hold the right value?"
@@ -220,7 +220,7 @@ Before moving to Review, verify:
220
220
 
221
221
  ---
222
222
 
223
- ### Phase 5: REVIEW — /review
223
+ ### Phase 5: REVIEW - /review
224
224
 
225
225
  **Auto-activates → `[ROLE: Staff Engineer]` + `[ROLE: Senior Designer]` for UI tasks**
226
226
 
@@ -240,7 +240,7 @@ Inspired by [obra/superpowers](https://github.com/obra/superpowers):
240
240
 
241
241
  ---
242
242
 
243
- ### Phase 5.5: SIMPLIFY — /simplify
243
+ ### Phase 5.5: SIMPLIFY - /simplify
244
244
 
245
245
  **Auto-activates → `[ROLE: Staff Engineer]` (Ponytail Mindset)**
246
246
 
@@ -253,7 +253,7 @@ Before merging, ruthlessly simplify:
253
253
 
254
254
  ---
255
255
 
256
- ### Phase 6: SHIP — /ship
256
+ ### Phase 6: SHIP - /ship
257
257
 
258
258
  **Auto-activates → `[ROLE: Release Engineer]`**
259
259
 
@@ -267,8 +267,7 @@ Only ship when all gates are green.
267
267
  - [ ] Docs updated (README, API docs, changelogs)
268
268
  - [ ] Breaking changes documented
269
269
  - [ ] Rollback plan exists
270
- - [ ] Vercel Preview Deployment is successful and manually verified
271
- - [ ] Core Web Vitals pass in preview (LCP < 2.5s, CLS < 0.1, INP < 200ms)
270
+ - [ ] Preview / staging deployment verified (if applicable, e.g. Vercel Preview and Core Web Vitals for frontend deployments)
272
271
 
273
272
  #### Operational Self-Improvement
274
273
 
@@ -311,6 +310,7 @@ export async function POST(req) {
311
310
  - [ ] Implementation plan broken down into vertical tasks < 2 hours each.
312
311
  - [ ] Tests written before implementation (TDD/BDD).
313
312
  - [ ] Code reviewed against correctness, security, performance, and design gates.
313
+ - [ ] Staged security and quality check passes (`contextos scan --staged --enforce`).
314
314
  - [ ] Simplification ladder executed before shipping.
315
315
 
316
316
  ---
@@ -337,7 +337,7 @@ export async function POST(req) {
337
337
 
338
338
  When completing a task or workflow, you must explicitly report your final status as the last part of your output:
339
339
 
340
- - **DONE** — completed with evidence.
341
- - **DONE_WITH_CONCERNS** — completed, but list concerns.
342
- - **BLOCKED** — cannot proceed; state blocker and what was tried.
343
- - **NEEDS_CONTEXT** — missing info; state exactly what is needed.
340
+ - **DONE** - completed with evidence.
341
+ - **DONE_WITH_CONCERNS** - completed, but list concerns.
342
+ - **BLOCKED** - cannot proceed; state blocker and what was tried.
343
+ - **NEEDS_CONTEXT** - missing info; state exactly what is needed.
@@ -0,0 +1,72 @@
1
+ # gemini-precision Examples - Anti-patterns vs ContextOS Standard
2
+
3
+ ## Example 1: Read-Before-Write Invariant (Zero Assumptions)
4
+
5
+ ### Anti-pattern: Hallucinated Import and Signature
6
+
7
+ ```typescript
8
+ // BAD: Assuming the module exists and export is a default function
9
+ import hashPassword from 'src/utils/crypto';
10
+ const hash = hashPassword(password);
11
+ ```
12
+
13
+ ### Best practice: ContextOS Standard (Inspected Active Codebase First)
14
+
15
+ ```typescript
16
+ // GOOD: Inspected src/lib/auth.ts via view_file before writing code
17
+ import { hashSecret, ARGON2_CONFIG } from '../lib/auth.js';
18
+ const hash = await hashSecret(password, ARGON2_CONFIG);
19
+ ```
20
+
21
+ ---
22
+
23
+ ## Example 2: Zero-Placeholder Invariant (Complete Code Only)
24
+
25
+ ### Anti-pattern: Lazy Stubs and Ellipsis Comments
26
+
27
+ ```typescript
28
+ // BAD: Emitting incomplete code with TODOs and ellipsis
29
+ export function processTransaction(tx: Transaction) {
30
+ // TODO: validate transaction balance
31
+ // ... rest of implementation stays here ...
32
+ return { status: 'ok' };
33
+ }
34
+ ```
35
+
36
+ ### Best practice: ContextOS Standard (100% Drop-in Compilable)
37
+
38
+ ```typescript
39
+ // GOOD: Fully implemented logic with complete error handling
40
+ export function processTransaction(tx: Transaction): TransactionResult {
41
+ if (!tx.amount || tx.amount <= 0) {
42
+ throw new ValidationError('Transaction amount must be positive');
43
+ }
44
+ if (tx.senderBalance < tx.amount) {
45
+ throw new InsufficientFundsError(tx.senderId, tx.amount);
46
+ }
47
+ return {
48
+ status: 'ok',
49
+ transactionId: tx.id,
50
+ newBalance: tx.senderBalance - tx.amount,
51
+ };
52
+ }
53
+ ```
54
+
55
+ ---
56
+
57
+ ## Example 3: Mandatory Proof-of-Work Invariant
58
+
59
+ ### Anti-pattern: Claiming Task Complete Without Evidence
60
+
61
+ ```text
62
+ BAD: "I have updated the authentication handler. The code looks correct and is ready to merge."
63
+ ```
64
+
65
+ ### Best practice: ContextOS Standard (Verified with Automated Gates)
66
+
67
+ ```bash
68
+ # GOOD: Run test suite, staged scanner, and consistency checks
69
+ npm test
70
+ contextos scan --staged --enforce
71
+ node .agents/ctx.js validate
72
+ ```
@@ -51,6 +51,7 @@ Activate whenever:
51
51
  1. Run the project validator or compiler (`node .agents/ctx.js validate`, `tsc --noEmit`, etc.).
52
52
  2. Run unit and integration tests (`npm test`, `pytest`, etc.).
53
53
  3. Run linter and formatting checks (`npm run lint:md`, `eslint`, etc.).
54
+ 4. Run staged security and quality scanner (`contextos scan --staged --enforce`).
54
55
  - If a test or validation fails, do not guess: read the exact error trace, fix the root cause, and re-run until green.
55
56
 
56
57
  ### 4. Surgical Blast Radius Containment
@@ -86,7 +87,7 @@ Activate whenever:
86
87
  **Eliminate the "black box" by narrating technical decisions.**
87
88
 
88
89
  - Avoid executing long, silent chains of tool calls without user visibility.
89
- - Provide a concise 1–2 sentence transparent status update before key operations:
90
+ - Provide a concise 1-2 sentence transparent status update before key operations:
90
91
  - State what was inspected or verified from the code.
91
92
  - State the architectural decision made and the immediate next action.
92
93
  - Keep narration crisp and actionable without excessive verbosity.
@@ -0,0 +1,25 @@
1
+ # gemini-precision Troubleshooting & Common Failure Modes
2
+
3
+ ## 1. Test Failure Investigation (No Guesswork)
4
+
5
+ - **Symptom**: Test fails during `npm test` after code modifications.
6
+ - **Root Cause**: Trying to patch the code without reading the exact assertion diff.
7
+ - **Fix**: Never guess the fix. View the test file line where assertion failed, inspect expected vs actual output, and resolve the root discrepancy.
8
+
9
+ ## 2. Accidental Staged Secrets or Placeholders
10
+
11
+ - **Symptom**: `contextos scan --staged --enforce` fails with exit code 1.
12
+ - **Root Cause**: Committed temporary `.env` file or left an unfinished `// TODO: implement later` stub in added lines.
13
+ - **Fix**: Remove or redact the secret before committing. Fully implement the logic or replace the placeholder with an explicit tracked issue rather than committed code stubs.
14
+
15
+ ## 3. Scope Creep and Excessive Blast Radius
16
+
17
+ - **Symptom**: Unrelated files reformatted or imports reordered across the repository.
18
+ - **Root Cause**: Full-file rewrite instead of targeted surgical replacement.
19
+ - **Fix**: Use targeted chunks that touch only the lines specified in the task plan. Avoid modifying unrelated styling or formatting.
20
+
21
+ ## 4. Forbidden Long Dashes
22
+
23
+ - **Symptom**: Linter or compliance check flags unicode dashes in text.
24
+ - **Root Cause**: Using typography dashes (`\u2014` or `\u2013`) instead of standard ASCII hyphens.
25
+ - **Fix**: Replace all em-dashes and en-dashes with standard ASCII hyphens (` - `) or appropriate punctuation (parentheses, commas, colons).
@@ -4,5 +4,7 @@ type: instruction-only
4
4
  description: High-precision engineering and execution guardrails optimized for Google Gemini models. Enforces zero-assumption file inspection, complete non-lazy implementations, surgical blast-radius containment, and mandatory proof-of-work execution.
5
5
  version: 1.0.0
6
6
  resources:
7
+ - EXAMPLES.md
7
8
  - SKILL.md
9
+ - TROUBLESHOOTING.md
8
10
  - VALIDATION.json
@@ -17,7 +17,7 @@ Activate on every task to declare explicit specialist role and mindset before be
17
17
 
18
18
  ## Rules & Patterns
19
19
 
20
- Inspired by [Garry Tan's gstack](https://github.com/garrytan/gstack) — shipping 810× more logical code than a solo dev in 2013.
20
+ Inspired by [Garry Tan's gstack](https://github.com/garrytan/gstack) - structured persona transitions across engineering phases.
21
21
 
22
22
  ## Core Principle
23
23
 
@@ -25,13 +25,14 @@ Inspired by [Garry Tan's gstack](https://github.com/garrytan/gstack) — shippin
25
25
 
26
26
  ## Role Identification Protocol
27
27
 
28
- At the start of each task or major phase switch, declare your role:
28
+ At the start of each task or major phase switch, declare your role using the ContextOS standard format:
29
29
 
30
- ```
31
- [ROLE: <Role Name>] — <One-line description of your mandate for this task>
30
+ ```text
31
+ [DOMAIN: <Domain>] [PHASE: <Phase>] [ROLE: <Role Name>]
32
+ Skills loaded: <skill-1>, <skill-2>
32
33
  ```
33
34
 
34
- > **Anti-Spam Invariant**: Declare this role **strictly once per phase**. Never prefix intermediate tool calls, file operations, or step updates with role tags.
35
+ > **Anti-Spam Invariant**: Declare this role header **strictly once per phase**. Never prefix intermediate tool calls, file operations, or step updates with role tags.
35
36
 
36
37
  Then execute ONLY within the constraints of that role.
37
38
 
@@ -110,7 +111,7 @@ THINK PLAN BUILD REVIEW TEST SHIP
110
111
  2. **One role at a time.** Don't mix QA and implementation in the same response.
111
112
  3. **Declare before acting.** Always state `[ROLE: X]` before switching modes.
112
113
  4. **Escalate correctly.** If a QA finds an architectural problem → escalate to Architect role.
113
- 5. **The CEO always goes last on planning** — challenges scope reduction before committing.
114
+ 5. **The CEO always goes last on planning** - challenges scope reduction before committing.
114
115
 
115
116
  ## Example Usage
116
117
 
@@ -32,7 +32,7 @@ Activate whenever writing authentication, authorization, session management, dat
32
32
 
33
33
  #### 1. Injection (SQL, NoSQL, Command)
34
34
 
35
- - Always use parameterized queries — never concatenate user input into SQL or shell commands.
35
+ - Always use parameterized queries - never concatenate user input into SQL or shell commands.
36
36
  - Use ORMs (Prisma, Drizzle, SQLAlchemy) with strict schema validation.
37
37
  - Validate and sanitize all user input before processing.
38
38
 
@@ -81,14 +81,20 @@ When building AI workflows, tools, or MCP servers:
81
81
  - Never allow untrusted content to override system instructions or tool execution permissions.
82
82
  2. **Tool Execution Boundaries**:
83
83
  - Destructive operations (database drops, file deletions, payment triggers) MUST require explicit user confirmation.
84
- - Restrict file system tools to the workspace root — block directory traversal (`../`).
84
+ - Restrict file system tools to the workspace root - block directory traversal (`../`).
85
85
  3. **Secret Masking & Output Sanitization**:
86
86
  - Scrub API keys (`sk-...`, `Bearer ...`), tokens, and credentials before writing to agent logs or step summaries.
87
+ 4. **Sandbox Execution & Write Isolation (Supply-Chain Defense)**:
88
+ - Target code is inspected strictly read-only; never execute target-controlled builds or tests with write access to the repository root.
89
+ - Restrict process write boundaries strictly to an isolated temporary `scratch/` directory.
90
+ - Enforce zero outbound external network access during security audits to prevent secret exfiltration via malicious scripts or dependencies.
91
+ - Promote verified non-secret results to retained `artifacts/` only via trusted parent-side inspection code.
87
92
 
88
93
  ---
89
94
 
90
95
  ## Code Examples
91
96
 
97
+
92
98
  ### Timing-Safe Secret Verification
93
99
 
94
100
  ```javascript
@@ -104,28 +110,50 @@ export function verifyWebhookSignature(payload, signature, secret) {
104
110
  }
105
111
  ```
106
112
 
107
- ### Safe SSRF Prevention Wrapper
113
+ ### SSRF Prevention Requirements (OWASP Compliant)
108
114
 
109
- ```typescript
110
- import dns from 'node:dns/promises';
115
+ Per [OWASP SSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html), naive application-level DNS pre-checks followed by standard `fetch(url)` are fundamentally flawed due to DNS rebinding (TOCTOU) and unvalidated HTTP 3xx redirects.
116
+
117
+ #### Mandatory Architectural Controls
111
118
 
112
- export async function validateSafeUrl(urlString: string): Promise<URL> {
119
+ 1. **Network-Layer Defense (Primary)**: For user-supplied arbitrary webhooks or URLs, route all outbound traffic through an isolated egress forward proxy (e.g., Smokescreen, Envoy, Squid) configured with firewall-level IP filters blocking RFC 1918, RFC 6598, link-local (`169.254.169.254`), loopback, and IPv6 local addresses at the socket handshake level.
120
+ 2. **Positive Destination Allowlist**: If fetching from known external partners, validate destination hostname against a strict positive allowlist.
121
+ 3. **Disable Automatic Redirects**: Always set `redirect: 'error'` or `'manual'`. Never follow HTTP redirects automatically without re-validating the target URL against allowlist rules.
122
+ 4. **Protocol & Credential Restrictions**: Enforce `https:` exclusively; reject embedded credentials (`user:pass@host`) and non-standard ports.
123
+
124
+ ```typescript
125
+ /**
126
+ * Verified Allowlist-based HTTP Client (OWASP SSRF Prevention)
127
+ * Enforces HTTPS, strict destination allowlist, and rejects HTTP redirects.
128
+ */
129
+ export async function fetchFromAllowlist(
130
+ urlString: string,
131
+ allowedHostnames: ReadonlySet<string>,
132
+ options: RequestInit = {}
133
+ ): Promise<Response> {
113
134
  const parsed = new URL(urlString);
135
+
136
+ // 1. Enforce HTTPS only
114
137
  if (parsed.protocol !== 'https:') {
115
- throw new Error('Only HTTPS protocol is permitted');
138
+ throw new Error(`SSRF blocked: protocol "${parsed.protocol}" is not permitted; HTTPS required`);
139
+ }
140
+
141
+ // 2. Reject credentials in URL
142
+ if (parsed.username || parsed.password) {
143
+ throw new Error('SSRF blocked: URL credentials (user:password@host) are prohibited');
116
144
  }
117
145
 
118
- const { address } = await dns.lookup(parsed.hostname);
119
- if (
120
- address.startsWith('127.') ||
121
- address.startsWith('10.') ||
122
- address.startsWith('192.168.') ||
123
- address === '169.254.169.254'
124
- ) {
125
- throw new Error('Access to private/metadata IP addresses is blocked');
146
+ // 3. Strict positive destination allowlist (prevents internal network probing)
147
+ const normalizedHost = parsed.hostname.toLowerCase();
148
+ if (!allowedHostnames.has(normalizedHost)) {
149
+ throw new Error(`SSRF blocked: destination host "${normalizedHost}" is not in the approved allowlist`);
126
150
  }
127
151
 
128
- return parsed;
152
+ // 4. Disable automatic redirects to prevent redirection to private IPs or metadata endpoints
153
+ return fetch(urlString, {
154
+ ...options,
155
+ redirect: 'error'
156
+ });
129
157
  }
130
158
  ```
131
159
 
@@ -12,7 +12,6 @@ resources:
12
12
  - SKILL.md
13
13
  - TROUBLESHOOTING.md
14
14
  - VALIDATION.json
15
- - security.md
16
15
  rules:
17
16
  - id: SEC-001
18
17
  level: must
package/.agents/ctx.js CHANGED
@@ -97,25 +97,31 @@ if (command === 'export') {
97
97
  const pureCompiler = require('./adapters/pure-compiler.js');
98
98
  const driftDetector = require('./adapters/drift-detector.js');
99
99
 
100
+ const isCheck = args.includes('--check');
101
+ const isDiff = args.includes('--diff');
102
+ const isDryRun = args.includes('--dry-run');
103
+ const asJson = args.includes('--json');
104
+
100
105
  const profileFlagIdx = args.indexOf('--profile');
101
106
  let overrideProfile = null;
102
107
  if (profileFlagIdx !== -1 && args[profileFlagIdx + 1]) {
103
108
  const profiles = require('./profiles.js');
104
109
  overrideProfile = args[profileFlagIdx + 1];
105
110
  try {
106
- profiles.applyProfile(overrideProfile);
107
- console.log(`[PROFILE] Applied profile '${overrideProfile}' for this export.\n`);
111
+ const prof = profiles.getProfile(overrideProfile, process.cwd());
112
+ if (!prof) {
113
+ throw new Error(`Profile '${overrideProfile}' not found`);
114
+ }
115
+ if (!isCheck && !isDryRun && !isDiff) {
116
+ profiles.applyProfile(overrideProfile);
117
+ console.log(`[PROFILE] Applied profile '${overrideProfile}' for this export.\n`);
118
+ }
108
119
  } catch (err) {
109
120
  console.error(`[ERROR] ${err.message}`);
110
- process.exit(1);
121
+ process.exit(2);
111
122
  }
112
123
  }
113
124
 
114
- const isCheck = args.includes('--check');
115
- const isDiff = args.includes('--diff');
116
- const isDryRun = args.includes('--dry-run');
117
- const asJson = args.includes('--json');
118
-
119
125
  const rawTarget = args[1] && !args[1].startsWith('--') ? args[1] : 'all';
120
126
 
121
127
  // 1. Drift Check Mode (--check)
@@ -125,7 +131,7 @@ if (command === 'export') {
125
131
  console.log(JSON.stringify(drift, null, 2));
126
132
  } else {
127
133
  console.log('\nContextOS — Adapter Output Drift Check\n');
128
- if (!drift.hasDrift) {
134
+ if (!drift.hasDrift && !drift.hasError) {
129
135
  console.log(`✓ No adapter drift detected. All ${drift.projectedCount} output artifacts are synchronized.`);
130
136
  } else {
131
137
  console.log(`! Drift detected (${drift.totalFindings} finding(s)):\n`);
@@ -146,7 +152,7 @@ if (command === 'export') {
146
152
  console.log('\nRun: node .agents/ctx.js export all to synchronize outputs with source skills.\n');
147
153
  }
148
154
  }
149
- process.exit(drift.hasDrift ? 1 : 0);
155
+ process.exit(drift.code !== undefined ? drift.code : (drift.hasDrift ? 1 : 0));
150
156
  }
151
157
 
152
158
  // 2. Diff Preview Mode (--diff)