@jalvarezsamayoa/factory 0.0.0-stage → 0.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.
@@ -0,0 +1,273 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ export async function createWorkspace(options) {
4
+ const name = options.name?.trim() || "default";
5
+ const slug = slugify(name);
6
+ const directory = join(options.target, "factory", "workspaces", slug);
7
+ const now = new Date().toISOString();
8
+ const files = {
9
+ "brief.md": briefTemplate(name),
10
+ "plan.md": planTemplate(),
11
+ "contract.md": contractTemplate(),
12
+ "reviews/software.md": softwareReviewTemplate(),
13
+ "reviews/security.md": securityReviewTemplate(),
14
+ "bugs/README.md": bugsTemplate(),
15
+ "state.json": `${JSON.stringify({
16
+ name,
17
+ slug,
18
+ phase: "intake",
19
+ createdAt: now,
20
+ updatedAt: now,
21
+ }, null, 2)}\n`,
22
+ };
23
+ const result = { directory, files: [] };
24
+ const rootReadme = join(options.target, "factory", "README.md");
25
+ const rootStatus = await writeIfChanged(rootReadme, factoryReadmeTemplate(), options.force === true);
26
+ if (rootStatus !== "unchanged") {
27
+ result.files.push({ path: rootReadme, status: rootStatus });
28
+ }
29
+ for (const [relativePath, content] of Object.entries(files)) {
30
+ const path = join(directory, relativePath);
31
+ const status = await writeIfChanged(path, content, options.force === true);
32
+ result.files.push({ path, status });
33
+ }
34
+ return result;
35
+ }
36
+ export function describeWorkspace(result, target) {
37
+ const created = result.files.filter((file) => file.status === "created").length;
38
+ const updated = result.files.filter((file) => file.status === "updated").length;
39
+ const skipped = result.files.filter((file) => file.status === "skipped").length;
40
+ const lines = [
41
+ `Factory workspace ready: ${result.directory}`,
42
+ "",
43
+ `${created} created, ${updated} updated, ${skipped} skipped.`,
44
+ "",
45
+ "Next steps:",
46
+ ` 1. Fill in ${join(result.directory, "brief.md")}.`,
47
+ " 2. Ask the contrarian agent to challenge the brief.",
48
+ " 3. Write the plan and contract before implementation.",
49
+ " 4. Delegate the build to the contractor, then run both reviewers.",
50
+ ];
51
+ if (skipped > 0) {
52
+ lines.push("", "Skipped existing files. Re-run with --force to overwrite them.");
53
+ }
54
+ return lines.join("\n");
55
+ }
56
+ function slugify(value) {
57
+ const slug = value
58
+ .toLowerCase()
59
+ .trim()
60
+ .replace(/[^a-z0-9]+/g, "-")
61
+ .replace(/^-+|-+$/g, "");
62
+ return slug || "default";
63
+ }
64
+ async function writeIfChanged(target, content, force) {
65
+ let existing;
66
+ try {
67
+ existing = await readFile(target, "utf8");
68
+ }
69
+ catch (error) {
70
+ if (error.code !== "ENOENT")
71
+ throw error;
72
+ }
73
+ if (existing === content)
74
+ return "unchanged";
75
+ if (existing !== undefined && !force)
76
+ return "skipped";
77
+ await mkdir(dirname(target), { recursive: true });
78
+ await writeFile(target, content, "utf8");
79
+ return existing === undefined ? "created" : "updated";
80
+ }
81
+ function factoryReadmeTemplate() {
82
+ return `# Factory
83
+
84
+ This directory holds the artifacts for factory workspaces. Each change gets
85
+ one workspace under \`workspaces/<name>/\`:
86
+
87
+ \`\`\`text
88
+ factory/
89
+ └── workspaces/
90
+ └── default/
91
+ ├── brief.md Problem, goals, constraints
92
+ ├── plan.md Approach, steps, risks, decisions
93
+ ├── contract.md Deliverables and acceptance criteria
94
+ ├── reviews/
95
+ │ ├── software.md Software review findings
96
+ │ └── security.md Security review findings
97
+ ├── bugs/ Reproduction notes and failing tests
98
+ └── state.json Current phase
99
+ \`\`\`
100
+
101
+ ## Phases
102
+
103
+ 1. **Intake** — write the brief.
104
+ 2. **Challenge** — the contrarian agent stress-tests the brief and plan.
105
+ 3. **Contract** — write the plan and acceptance criteria.
106
+ 4. **Build** — the contractor agent implements the contract.
107
+ 5. **Review** — software-reviewer and security-reviewer review independently.
108
+ 6. **Harden** — the bug-hunter agent reproduces and fixes failures.
109
+ 7. **Ship** — verify the contract and close the workspace.
110
+
111
+ Create a workspace with \`/factory workspace <name>\` or \`factory workspace <name>\`.
112
+ `;
113
+ }
114
+ function briefTemplate(name) {
115
+ return `# Brief: ${name}
116
+
117
+ ## Change
118
+
119
+ <!-- One paragraph. What are we changing and why now? -->
120
+
121
+ ## Problem
122
+
123
+ <!-- What is broken, missing, or expensive today? Include evidence. -->
124
+
125
+ ## Goals
126
+
127
+ -
128
+
129
+ ## Non-goals
130
+
131
+ -
132
+
133
+ ## Constraints
134
+
135
+ - Technical:
136
+ - Product:
137
+ - Time and budget:
138
+
139
+ ## Users and impact
140
+
141
+ <!-- Who is affected, and how do we know? -->
142
+
143
+ ## Success signals
144
+
145
+ <!-- Observable outcomes, not activities. -->
146
+
147
+ ## Open questions
148
+
149
+ -
150
+ `;
151
+ }
152
+ function planTemplate() {
153
+ return `# Plan
154
+
155
+ ## Approach
156
+
157
+ <!-- The chosen approach in a few sentences. -->
158
+
159
+ ## Alternatives considered
160
+
161
+ | Option | Why not |
162
+ | --- | --- |
163
+ | | |
164
+
165
+ ## Steps
166
+
167
+ 1.
168
+ 2.
169
+ 3.
170
+
171
+ ## Risks
172
+
173
+ | Risk | Likelihood | Impact | Mitigation |
174
+ | --- | --- | --- | --- |
175
+ | | | | |
176
+
177
+ ## Rollback
178
+
179
+ <!-- How do we undo this safely? -->
180
+
181
+ ## Decisions
182
+
183
+ <!-- Append dated decisions. Do not rewrite history. -->
184
+ `;
185
+ }
186
+ function contractTemplate() {
187
+ return `# Contract
188
+
189
+ ## Deliverables
190
+
191
+ - [ ]
192
+ - [ ]
193
+
194
+ ## Acceptance criteria
195
+
196
+ <!-- Use Given/When/Then. Every criterion must be checkable. -->
197
+
198
+ - **Given**
199
+ **When**
200
+ **Then**
201
+
202
+ ## Quality gates
203
+
204
+ - [ ] Unit tests cover the new behavior.
205
+ - [ ] Relevant integration or end-to-end tests pass.
206
+ - [ ] Software review has no blocking findings.
207
+ - [ ] Security review has no blocking findings.
208
+ - [ ] Documentation is updated when behavior changes.
209
+ - [ ] Rollback is documented and tested where practical.
210
+
211
+ ## Out of scope
212
+
213
+ -
214
+ `;
215
+ }
216
+ function softwareReviewTemplate() {
217
+ return `# Software review
218
+
219
+ Status: pending
220
+
221
+ ## Blocking findings
222
+
223
+ <!-- file:line, problem, why it blocks, concrete fix -->
224
+
225
+ ## Non-blocking findings
226
+
227
+ ## Test gaps
228
+
229
+ ## Verdict
230
+
231
+ <!-- approve | approve with follow-ups | request changes -->
232
+ `;
233
+ }
234
+ function securityReviewTemplate() {
235
+ return `# Security review
236
+
237
+ Status: pending
238
+
239
+ ## Threat model
240
+
241
+ <!-- Assets, trust boundaries, attacker capabilities. -->
242
+
243
+ ## Blocking findings
244
+
245
+ <!-- severity, CWE/OWASP, exploit scenario, remediation -->
246
+
247
+ ## Non-blocking findings
248
+
249
+ ## Verdict
250
+
251
+ <!-- approve | approve with follow-ups | request changes -->
252
+ `;
253
+ }
254
+ function bugsTemplate() {
255
+ return `# Bugs
256
+
257
+ Record each defect in its own file, for example \`BUG-001.md\`:
258
+
259
+ \`\`\`md
260
+ # BUG-001: <short title>
261
+
262
+ ## Reproduction
263
+ 1.
264
+
265
+ ## Expected
266
+ ## Actual
267
+ ## Root cause
268
+ ## Failing test
269
+ ## Fix
270
+ ## Regression risk
271
+ \`\`\`
272
+ `;
273
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@jalvarezsamayoa/factory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Agents, skills, and tools for an AI software development factory.",
5
+ "type": "module",
6
+ "license": "GPL-3.0-only",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/jalvarezsamayoa/ai-factory-skills.git"
10
+ },
11
+ "homepage": "https://github.com/jalvarezsamayoa/ai-factory-skills#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/jalvarezsamayoa/ai-factory-skills/issues"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "bin": {
22
+ "factory": "dist/cli.js"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "agents",
27
+ "skills",
28
+ "commands",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.json",
34
+ "clean": "rm -rf dist",
35
+ "test": "node --test test/*.test.js",
36
+ "prepublishOnly": "npm run clean && npm run build && npm test",
37
+ "release": "semantic-release",
38
+ "typecheck": "tsc -p tsconfig.json --noEmit"
39
+ },
40
+ "dependencies": {
41
+ "@opencode/plugin": "^2.3.2"
42
+ },
43
+ "devDependencies": {
44
+ "@semantic-release/changelog": "^7.0.0",
45
+ "@semantic-release/git": "^11.0.1",
46
+ "@types/node": "^22.10.0",
47
+ "semantic-release": "^25.0.9",
48
+ "typescript": "^5.7.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=22"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "keywords": [
57
+ "opencode",
58
+ "opencode-plugin",
59
+ "claude",
60
+ "antigravity",
61
+ "agents",
62
+ "skills",
63
+ "software-factory"
64
+ ]
65
+ }
@@ -0,0 +1,92 @@
1
+ ---
2
+ name: bug-hunting
3
+ description: Use when the user asks to hunt for bugs, audit a codebase or module for functional or security defects, prove or reproduce a suspected bug, or run bug-hunting. Uses a 5-phase methodology, A->B sibling cluster hunting, and a 7-Question Gate for codebase bug hunting, requiring every reported bug to be proven with executable evidence in the test suite, tmp/bug-hunter/, or an isolated git worktree.
4
+ ---
5
+
6
+ # Bug Hunting
7
+
8
+ Hunt for functional, logic, concurrency, and security bugs in a codebase using empirical, execution-backed verification.
9
+
10
+ ## Core Rule: Proof Over Suspicion
11
+
12
+ Reading source code and suspecting a defect never produces a finding; it produces a **hypothesis**.
13
+
14
+ - **"Could potentially" is not a bug.** Never report a theoretical flaw from static code inspection alone.
15
+ - **Prove it by running code.** Every reported finding must be backed by executable proof captured in this session.
16
+ - **Retract what fails reproduction.** When a hypothesis does not reproduce or fails a guard you missed during initial reading, drop it from findings and log it in the **Retracted Hypotheses** appendix with the disproving evidence.
17
+
18
+ Read `references/validation-gate.md` before reporting any finding, and read `references/hunt-checklists.md` when selecting vulnerability and logic classes to hunt.
19
+
20
+ ## The Verification & Proof Hierarchy
21
+
22
+ Prove every bug hypothesis using the highest-ranked method below that can reach the target path:
23
+
24
+ 1. **Method 1 — Project Test Suite (Preferred):**
25
+ - Write a failing test inside the repository's existing test suite that calls unmodified production code and demonstrates the violated invariant.
26
+ - Run the project's test runner and capture the failing output.
27
+ - Save the test diff to `tmp/bug-hunter/patches/<finding-slug>.patch` before cleaning up the main working tree so the developer can apply it directly when fixing the bug.
28
+ 2. **Method 2 — Standalone Script in `tmp/bug-hunter/`:**
29
+ - When the existing test runner cannot reach the path directly (such as multi-process races, CLI pipelines, or raw protocol checks), write and run a standalone reproduction script under `tmp/bug-hunter/`.
30
+ 3. **Method 3 — Isolated Git Worktree (When Source Edits Are Required):**
31
+ - When proving a bug requires temporary instrumentation, fault injection, or edits to production source files, never modify the main checkout.
32
+ - Create an isolated worktree under `.worktrees/bug-hunter-<slug>` (`git worktree add .worktrees/bug-hunter-<slug> HEAD`), run the reproduction there, save the evidence under `tmp/bug-hunter/` in the main workspace, and remove the worktree before concluding unless the user asked to keep it.
33
+
34
+ Always record `git status --short` before starting. Before finishing, remove any temporary test files added to the main checkout and confirm `git status --short` outside `tmp/` matches the pre-hunt state.
35
+
36
+ ## The 5-Phase Non-Linear Workflow
37
+
38
+ Move freely between phases: if proving a bug in Phase 4 exposes a shared helper or a new trust boundary, return to Phase 2 or Phase 3 immediately.
39
+
40
+ | Phase | Name | Goal | Reference |
41
+ | --- | --- | --- | --- |
42
+ | 1 | Scope & Crown Jewels | Identify the highest-damage failure modes for the target module or service | `references/hunt-checklists.md` |
43
+ | 2 | Map Trust Boundaries & Invariants | Trace entry points, callers, validation layers, state transitions, and persistence | `references/hunt-checklists.md` |
44
+ | 3 | Hunt & A->B Sibling Clustering | Form concrete trigger hypotheses and sweep sibling endpoints/functions | `references/hunt-checklists.md` |
45
+ | 4 | Prove via Execution | Run the Proof Hierarchy and enforce False-Positive Discipline | `references/validation-gate.md` |
46
+ | 5 | Validate (7-Question Gate) & Report | Filter every candidate through the 7-Question Gate and write the report | `references/validation-gate.md` |
47
+
48
+ ### Phase 1: Scope & Crown Jewels
49
+
50
+ Before reading individual lines, define the target's crown jewels:
51
+
52
+ - **Financial / Accounting:** balance calculations, rounding, currency conversion, idempotency, double-spend races, partial-failure rollback.
53
+ - **Auth & Access Control:** cross-tenant object references (IDOR / BOLA), role escalation, signature/token verification, fail-open error handlers.
54
+ - **State & Concurrency:** out-of-order events, replay of terminal states, lock ordering, check-then-act races, stale cache after transaction failure.
55
+ - **Input Parsing & External I/O:** panics/exceptions on malformed input, unbounded allocation, path traversal, SQL/command/template injection, SSRF.
56
+
57
+ ### Phase 2: Map Trust Boundaries & Invariants
58
+
59
+ - Use a code-intelligence graph when available to map callers, callees, and test coverage of the target module.
60
+ - Trace each input from its entry boundary through validation and business logic to database writes or external calls.
61
+ - Spot **developer inconsistencies**: when 4 handlers in a module enforce a guard or transaction boundary and the 5th omits it, that 5th handler is your primary hypothesis.
62
+
63
+ ### Phase 3: Hunt & A->B Sibling Clustering
64
+
65
+ When you confirm **Bug A** in one function or endpoint, immediately run the **A->B Cluster Hunt Protocol**:
66
+
67
+ 1. **Confirm A:** Prove Bug A with executable evidence.
68
+ 2. **Map Siblings:** Find all functions, endpoints, or callers in the same package/controller or sharing the same helper pattern.
69
+ 3. **Test Siblings:** Execute the same reproduction pattern against every sibling.
70
+ 4. **Chain Primitives:** Check whether two lower-severity primitives combine into a critical failure.
71
+
72
+ ### Phase 4: Prove via Execution
73
+
74
+ Execute each hypothesis using the Proof Hierarchy and enforce the four false-positive discipline rules from `references/validation-gate.md`:
75
+
76
+ - **Baseline Diff Rule:** Prove a valid control input passes while the trigger input fails on the target invariant.
77
+ - **Layer-Ordering Rule:** Prove the input reached the target business logic rather than being rejected by an upstream parser or middleware.
78
+ - **Statistical-Sample Rule:** For race conditions or timing claims, run `n >= 10` interleaved trials (or use deterministic barriers / race detectors) rather than relying on a single outlier.
79
+ - **Scripted Iteration Rule:** Use a script or parameterized test instead of shell loops for more than 5 iterations.
80
+
81
+ ### Phase 5: Validate & Report
82
+
83
+ Run every proven candidate through the **7-Question Gate** and **Pre-Severity Gate** in `references/validation-gate.md`.
84
+
85
+ - Save the full report to `tmp/bug-hunter/<target-slug>.md` and test patches to `tmp/bug-hunter/patches/`. In a factory workspace, also record reproduction notes and failing tests in `factory/workspaces/<name>/bugs/`.
86
+ - Include the **Sibling Cluster Sweep**, **Retracted Hypotheses** appendix, and **Workspace Cleanliness Check** (`git status --short`).
87
+
88
+ ## Dispatching the `bug-hunter` Agent
89
+
90
+ - **Single target or module:** Dispatch the `bug-hunter` subagent with the target paths, crown-jewel focus, and any known symptoms or ticket context.
91
+ - **Multi-module codebase hunt:** Map the modules in Phase 1 and Phase 2, then dispatch parallel `bug-hunter` subagents — one per module or bug class — instructing each to use distinct filenames under `tmp/bug-hunter/<module-slug>/` and isolated worktrees (`.worktrees/bug-hunter-<module-slug>`) if source edits are needed.
92
+ - **Fallback when subagents are unavailable:** Read `agents/bug-hunter.md` and execute the hunt, proof hierarchy, and 7-Question Gate inline.
@@ -0,0 +1,91 @@
1
+ # Bug Hunting Checklists & Language Sink Patterns
2
+
3
+ Use these checklists during Phases 1, 2, and 3 to form high-signal hypotheses for source-code and service bug hunting, then prove each hypothesis with executable tests.
4
+
5
+ ## 1. Crown-Jewel Threat Modeling Template
6
+
7
+ Before hunting a module, fill in this 4-line mental model:
8
+
9
+ ```text
10
+ TARGET MODULE: <package / service / controller>
11
+ CROWN JEWELS: 1. <worst data/financial loss> 2. <worst authz/tenant breach> 3. <worst availability/crash>
12
+ ENTRY POINTS: <HTTP/gRPC handlers, queue consumers, scheduled jobs, exported API functions>
13
+ TRUST SEAMS: <where untrusted input is parsed, validated, authorized, and persisted>
14
+ ```
15
+
16
+ ## 2. High-Signal Bug-Class Checklists
17
+
18
+ ### Financial, Accounting, & Business Logic
19
+
20
+ - **Rounding & Precision:** Floating-point math on currency, premature rounding inside loops before summing, division truncation losing remainder cents, negative zero or NaN propagation.
21
+ - **Sign & Boundary Flaws:** Negative amounts, quantities, or pagination offsets flipping a debit into a credit or bypassing a `< limit` check; zero-value inputs dividing by zero or creating empty transactions.
22
+ - **Idempotency & Replay:** Mutating endpoints or job handlers lacking idempotency keys, or checking idempotency before a transaction commits so retries either double-apply or drop operations.
23
+ - **Partial Failure & Rollback:** Multi-step mutations (for example database write + external API call + cache update) where step 2 fails and step 1 is not rolled back, leaving permanently wedged state.
24
+
25
+ ### Concurrency & Race Conditions
26
+
27
+ - **Check-Then-Act (TOCTOU):** Reading a balance, status, or quota in `SELECT`, checking it in application memory, and writing back without `SELECT ... FOR UPDATE`, atomic compare-and-swap, or a uniqueness constraint.
28
+ - **State-Machine Skips:** Concurrent transitions moving an entity from `pending -> cancelled` and `pending -> settled` simultaneously, or replaying a terminal transition twice.
29
+ - **Shared Memory & Map Races:** Concurrent goroutines, threads, or async tasks reading and mutating shared maps, slices, caches, or singleton clients without synchronization.
30
+ - **Resource & Lock Leaks:** Early error returns skipping `defer unlock()`, connection close, context cancellation, or temp-file cleanup, causing deadlocks or exhaustion under error load.
31
+
32
+ ### Authorization & Trust Boundaries (IDOR / BOLA / Auth Bypass)
33
+
34
+ - **Object-Level Authorization (IDOR / BOLA):** Fetching or mutating a record by primary key (`find(params[:id])`, `WHERE id = $1`) without scoping the query to the authenticated caller's tenant/user ID (`WHERE id = $1 AND user_id = $2`).
35
+ - **Sibling Endpoint Inconsistency:** `GET /resource/:id` checks ownership, but `PATCH`, `DELETE`, batch/bulk export, or GraphQL `node(id: ...)` omits the check.
36
+ - **Fail-Open Error Paths:** `catch` / `rescue` / `if err != nil` blocks in auth, permission, or rate-limit helpers that log an error and return `nil` / `true` instead of denying access.
37
+ - **Mass Assignment / Prototype Pollution:** Binding raw request maps directly into models or config objects, allowing callers to overwrite `role`, `tenant_id`, `status`, or `__proto__`.
38
+
39
+ ### Injection, SSRF, & File/Path Handling
40
+
41
+ - **Query & Command Construction:** String concatenation or `fmt.Sprintf` / template interpolation into SQL, NoSQL filters, shell commands, or LDAP/XML queries.
42
+ - **Path Traversal & Archive Extraction:** Joining user-controlled filenames with `path.Join` / `os.path.join` without verifying the resolved path stays inside the base directory (`filepath.Rel` / `realpath` prefix check).
43
+ - **SSRF & Redirect Chains:** Fetching user-supplied webhook or import URLs without blocking loopback (`127.0.0.1`, `[::1]`), link-local cloud metadata (`169.254.169.254`), internal RFC1918 ranges, or HTTP 302 redirects to internal hosts.
44
+
45
+ ---
46
+
47
+ ## 3. A->B Sibling Cluster Chains
48
+
49
+ When you prove **Bug A**, immediately hunt for **Bug B** across sibling code:
50
+
51
+ | Proven Bug A | Sibling Cluster to Sweep (Bug B) | Escalated Impact |
52
+ | --- | --- | --- |
53
+ | Read IDOR on `GET /items/:id` | `PUT`, `PATCH`, `DELETE`, and bulk export on the same controller/store | Cross-tenant data modification or deletion |
54
+ | Missing lock on one balance/quota update | All other mutators touching the same table or Redis key | Double-spend or quota bypass under concurrency |
55
+ | Unchecked error on one external call | Sibling callers of the same client interface across the package | Silent data divergence across workflows |
56
+ | Off-by-one or timezone boundary in one query | Reporting, billing, and expiration queries using the same date helper | Systematic financial or access-window drift |
57
+ | Missing input validation on `/v2/` endpoint | Legacy `/v1/`, internal RPC, or background job consuming the same struct | Full validation bypass via alternate entry point |
58
+
59
+ ---
60
+
61
+ ## 4. Language-Specific High-Risk Sink Patterns
62
+
63
+ Use these patterns to locate candidate sinks during Phase 2, then trace callers before writing a reproduction test:
64
+
65
+ ### Go
66
+
67
+ - **Concurrency & Races:** `go func` capturing loop variables or mutating shared maps/slices without `sync.Mutex` or `atomic`; missing `defer rows.Close()` or `defer cancel()` on error branches.
68
+ - **Slice & Map Traps:** Appending to a sub-slice that aliases backing array memory; nil map writes on uninitialized struct fields; integer conversion truncation (`int32(v)`, `uint(v)` on negative values).
69
+ - **SQL & Command Sinks:** `fmt.Sprintf` inside `db.Query` / `db.Exec`; `exec.Command("sh", "-c", ...)` with untrusted input; `filepath.Join` on untrusted paths without base-prefix verification.
70
+ - **Proof Tip:** Run `go test -race -run TestRepro ./...` to prove data races deterministically.
71
+
72
+ ### Ruby
73
+
74
+ - **Deserialization & Eval:** `YAML.load` (without `safe_load`), `Marshal.load`, `eval`, `send` / `public_send` on user-supplied method names, `constantize` on untrusted strings.
75
+ - **ActiveRecord & Authz:** `Model.find(params[:id])` instead of `current_user.models.find(params[:id])`; string interpolation inside `where("... #{params[:x]}")`, `order`, or `pluck`; `permit!` or overly broad `permit(...)`.
76
+ - **Transaction & Callback Traps:** Sidekiq jobs enqueued *inside* an uncommitted `ActiveRecord::Base.transaction` block (worker runs before commit and sees `RecordNotFound` or stale data); `rescue => e` swallowing `ActiveRecord::Rollback`.
77
+ - **Proof Tip:** Run `bundle exec rspec path/to/spec.rb --example "reproduces..."` to prove the defect against the model or request spec.
78
+
79
+ ### Python
80
+
81
+ - **Execution & Deserialization:** `pickle.loads`, `yaml.load` (without `SafeLoader`), `eval`, `exec`, `subprocess.run(..., shell=True)`.
82
+ - **Mutable Defaults & Async State:** `def fn(items=[])` mutating default list/dict across requests; shared class attributes mutated per instance; unawaited coroutines or blocking I/O inside `async def` handlers.
83
+ - **ORM & Numeric Traps:** Float arithmetic where `Decimal` is required; raw SQL f-strings in `cursor.execute(f"...")`; catching broad `Exception:` and returning a default truthy object.
84
+ - **Proof Tip:** Run `pytest path/to/test_file.py -k test_repro -vv` to capture the exact assertion traceback.
85
+
86
+ ### TypeScript / JavaScript
87
+
88
+ - **Async & Promise Traps:** Floating promises (`async` calls without `await` inside `forEach` or event handlers); `Promise.all` leaving sibling operations partially committed on rejection; race conditions across `await` boundaries (reading state before `await`, writing stale state after `await`).
89
+ - **Object & Type Coercion:** Prototype pollution via recursive `Object.assign` / deep merge with `__proto__` or `constructor.prototype`; `Number(input)` or `parseInt(input)` accepting `NaN`, `Infinity`, or partial strings (`"123abc"`); loose truthiness (`if (!value)`) treating `0` or `""` as missing.
90
+ - **DOM & Execution Sinks:** `dangerouslySetInnerHTML`, `innerHTML`, `eval`, `new Function`, `child_process.exec` with interpolated strings, unanchored regexes (`new RegExp(userInput)`) causing ReDoS.
91
+ - **Proof Tip:** Run `npx vitest run path/to/file.test.ts -t "reproduces..."` or `npm test` to capture the failing assertion.
@@ -0,0 +1,122 @@
1
+ # Validation Gate & False-Positive Discipline
2
+
3
+ Every candidate bug must pass the False-Positive Discipline rules, the 7-Question Gate, and (for Critical/High findings) the Pre-Severity Gate before it appears in a report.
4
+
5
+ ## 1. False-Positive Discipline Rules
6
+
7
+ Most retracted bug claims come from four recurring verification mistakes:
8
+
9
+ ### Baseline Diff Rule
10
+
11
+ A failing test or error code means nothing unless you compare it against a working baseline.
12
+
13
+ - Always run a **baseline control case** with valid inputs alongside the bug-triggering input.
14
+ - If the baseline also fails (due to missing test database setup, uninitialized mocks, or missing environment variables), you have a test-harness error, not a production bug. Fix the harness until the baseline passes, then run the trigger input.
15
+ - When claiming an authorization bypass or state mutation, diff the actual return value or persisted state against the baseline — status codes or log lines alone are insufficient.
16
+
17
+ ### Layer-Ordering Rule
18
+
19
+ A validation error or early rejection does not prove you bypassed an upstream check, and an upstream rejection does not prove downstream logic is broken.
20
+
21
+ - Many stacks run schema parsers, middleware, or input sanitizers before authentication or business logic.
22
+ - When testing whether a guard is missing or a bad input corrupts state, verify with a well-formed request and execution trace that your input actually reached the target function.
23
+
24
+ ### Statistical-Sample Rule (Races, Timing, & Flakes)
25
+
26
+ A single timing outlier or one-off failure is jitter, not proof.
27
+
28
+ - For race conditions, prefer deterministic reproduction (barrier synchronization channels, latches, or language race detectors such as `go test -race`).
29
+ - When statistical or timing reproduction is required, run at least **n >= 10 interleaved trials per group** (control vs trigger) and confirm repeatable failure or a mean shift of at least 2 standard deviations above control.
30
+
31
+ ### Scripted Iteration Rule (Shell-Loop Ban > 5 Iterations)
32
+
33
+ Shell `for` loops over arrays or command outputs can silently drop iterations or swallow non-zero exit codes.
34
+
35
+ - For any fuzzing, boundary sweep, or concurrency test exceeding 5 iterations, write a script (`python`, `node`, or a table-driven test in the project's test suite) that counts iterations explicitly and asserts on every result.
36
+
37
+ ---
38
+
39
+ ## 2. The 7-Question Gate
40
+
41
+ Ask all 7 questions in order for each candidate finding. **One NO = KILL the finding** and move it to the **Retracted Hypotheses** appendix.
42
+
43
+ ### Q1: Do I have executable proof from this session?
44
+
45
+ Complete this checklist:
46
+
47
+ ```text
48
+ 1. Entry Point: <public function / HTTP handler / CLI command / job consumer>
49
+ 2. Trigger Input: <exact arguments, payload, or concurrent call sequence>
50
+ 3. Proof Artifact: <test suite test + patch in tmp/bug-hunter/patches/ OR script in tmp/bug-hunter/>
51
+ 4. Observed Output: <exact failing assertion, panic, corrupted state, or unauthorized data>
52
+ 5. Production Diff: <empty in main checkout; unmodified production code failed>
53
+ ```
54
+
55
+ If you cannot point to a command you ran and its failing output -> **KILL IT**.
56
+
57
+ ### Q2: Does the impact cause real functional, data, or security harm?
58
+
59
+ - **Valid impact:** corrupted state or ledger numbers, silent data loss, unhandled panic/crash on reachable input, cross-tenant data access, privilege escalation, auth bypass, secret leak, infinite loop / memory exhaustion, or violated API contract.
60
+ - **Invalid impact:** style issues, cyclomatic complexity, naming taste, missing comments, or best-practice preferences with no broken behavior -> **KILL IT**.
61
+
62
+ ### Q3: Is the root cause in unmodified, in-scope production code?
63
+
64
+ - Confirm the failure is caused by the repository's production code, not by a flawed test mock, a stale build artifact, or an out-of-scope external dependency.
65
+ - If the failure is inside your test setup -> **KILL IT**.
66
+
67
+ ### Q4: Are the preconditions realistic for a real caller or attacker?
68
+
69
+ - "If an internal caller passes a corrupted struct pointer that violates the type system" -> **KILL IT** unless a real caller actually constructs that value.
70
+ - "If an admin intentionally misconfigures the database URL to an attacker host" -> **KILL IT**.
71
+ - If more than two unlikely external preconditions must coincide simultaneously -> **KILL IT** or downgrade to Low.
72
+
73
+ ### Q5: Is this behavior contradicted by the contract (not intended design)?
74
+
75
+ - Check existing unit tests, docstrings, `README.md`, API specs, and `CHANGELOG.md`.
76
+ - If the behavior is explicitly documented and tested as the intended contract -> **KILL IT**.
77
+
78
+ ### Q6: Did the proof demonstrate the harmful outcome beyond "technically possible"?
79
+
80
+ - Reaching a suspect line of code is not enough; the test must demonstrate the bad outcome (wrong balance persisted, victim record returned, panic thrown, lock wedged).
81
+ - If you only proved a primitive in the middle of a chain without showing end-to-end harm -> **DOWNGRADE severity** or chain it before reporting.
82
+
83
+ ### Q7: Is this absent from the Never-Report List?
84
+
85
+ Never report these as standalone bugs:
86
+
87
+ ```text
88
+ - Formatting, lint, import-order, or naming issues
89
+ - Dead or unreachable internal helpers that no entry point calls
90
+ - Missing defensive checks on internal functions when all callers already validate at the boundary
91
+ - Theoretical timing differences verified with only n=1 sample
92
+ - Verbose error messages on internal-only CLIs with no secret or PII exposure
93
+ - "Admin can perform admin action" without privilege escalation from a lower role
94
+ ```
95
+
96
+ ---
97
+
98
+ ## 3. Pre-Severity Gate (Before Labeling Critical or High)
99
+
100
+ Before marking any finding **🔴 Critical** or **High**, answer all four questions in one concrete sentence each:
101
+
102
+ 1. **Full Chain Validated:** Did my reproduction test execute the entire path from a real entry point to the final harmful outcome, rather than testing an isolated internal helper?
103
+ 2. **Concrete Consequence:** What exact harm occurs in one sentence (for example *"Concurrent refund requests on the same order credit the customer twice while debiting the ledger once"*)?
104
+ 3. **Repeatable Reproduction:** Did I run the reproduction test or script at least twice and observe the same deterministic (or statistically significant) failure?
105
+ 4. **No Upstream Guard Blocking It:** Did I verify that no middleware, transaction lock, database constraint, or caller guard blocks this input in real execution?
106
+
107
+ If any answer is "no", downgrade the finding to **🟠 Medium / Low** until the full chain is proven.
108
+
109
+ ---
110
+
111
+ ## 4. Retracted Hypotheses Appendix Template
112
+
113
+ Never silently delete a hypothesis that you tested and disproved. Documenting retractions proves coverage and saves engineers from re-investigating false leads.
114
+
115
+ ```markdown
116
+ ## Retracted Hypotheses
117
+
118
+ ### Retracted: <Short name of suspected flaw>
119
+ - **Hypothesis:** <What looked like a bug during code reading and at which file:line>
120
+ - **Disproving Evidence:** <The test case or script run that showed the guard held, the database constraint rejected it, or the path was unreachable>
121
+ - **Why It Looked Like a Bug:** <Root cause of the false alarm — e.g., upstream middleware already normalized the input, or integer overflow was bounded by an earlier check>
122
+ ```