draht-codex 2026.10.20 → 2026.10.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +16 -0
- package/agents/advisor.md +2 -2
- package/agents/architect.md +10 -71
- package/agents/debugger.md +12 -82
- package/agents/git-committer.md +10 -52
- package/agents/implementer.md +15 -63
- package/agents/investigator.md +11 -63
- package/agents/reviewer.md +15 -65
- package/agents/security-auditor.md +12 -105
- package/agents/spec-reviewer.md +12 -53
- package/agents/verifier.md +13 -54
- package/commands/atomic-commit.md +9 -9
- package/commands/create-verification-skill.md +8 -48
- package/commands/discuss-phase.md +5 -9
- package/commands/execute-phase.md +17 -47
- package/commands/fix.md +16 -130
- package/commands/grill.md +6 -51
- package/commands/init-project.md +10 -14
- package/commands/map-codebase.md +2 -2
- package/commands/new-project.md +9 -14
- package/commands/next-milestone.md +3 -7
- package/commands/orchestrate-loop.md +12 -12
- package/commands/orchestrate.md +12 -11
- package/commands/pause-work.md +1 -1
- package/commands/plan-phase.md +16 -38
- package/commands/quick.md +9 -78
- package/commands/resolve-conflicts.md +2 -15
- package/commands/triage.md +3 -14
- package/commands/verify-work.md +17 -106
- package/commands/why.md +18 -118
- package/hooks/hooks.json +10 -0
- package/package.json +4 -4
- package/scripts/checks-runtime.cjs +215 -0
- package/scripts/git-safety-hook.cjs +21 -0
- package/scripts/git-safety.cjs +198 -0
- package/scripts/gsd-post-task.cjs +78 -39
- package/scripts/gsd-quality-gate.cjs +206 -120
- package/scripts/prompt-context.cjs +40 -6
- package/scripts/session-start.cjs +6 -4
- package/scripts/stop-quality-gate.cjs +55 -25
- package/skills/atomic-commit/command.md +9 -9
- package/skills/atomic-reasoning/SKILL.md +6 -105
- package/skills/blast-radius/SKILL.md +1 -1
- package/skills/brainstorming/SKILL.md +8 -126
- package/skills/create-verification-skill/SKILL.md +1 -1
- package/skills/create-verification-skill/command.md +8 -48
- package/skills/ddd-workflow/SKILL.md +8 -101
- package/skills/debugging-workflow/SKILL.md +12 -122
- package/skills/discuss-phase/SKILL.md +1 -0
- package/skills/discuss-phase/agents/openai.yaml +2 -0
- package/skills/discuss-phase/command.md +5 -9
- package/skills/draht/SKILL.md +18 -14
- package/skills/epistemics/SKILL.md +12 -87
- package/skills/execute-phase/SKILL.md +1 -0
- package/skills/execute-phase/agents/openai.yaml +2 -0
- package/skills/execute-phase/command.md +17 -47
- package/skills/explainers/SKILL.md +1 -1
- package/skills/fix/SKILL.md +2 -1
- package/skills/fix/agents/openai.yaml +2 -0
- package/skills/fix/command.md +16 -130
- package/skills/grill/SKILL.md +1 -1
- package/skills/grill/command.md +6 -51
- package/skills/gsd-workflow/SKILL.md +37 -21
- package/skills/gsd-workflow/agents/openai.yaml +2 -0
- package/skills/init-project/SKILL.md +1 -0
- package/skills/init-project/agents/openai.yaml +2 -0
- package/skills/init-project/command.md +10 -14
- package/skills/loop-workflow/SKILL.md +7 -41
- package/skills/map-codebase/command.md +2 -2
- package/skills/model-tiering/SKILL.md +7 -7
- package/skills/new-project/SKILL.md +1 -0
- package/skills/new-project/agents/openai.yaml +2 -0
- package/skills/new-project/command.md +9 -14
- package/skills/next-milestone/SKILL.md +1 -0
- package/skills/next-milestone/agents/openai.yaml +2 -0
- package/skills/next-milestone/command.md +3 -7
- package/skills/orchestrate/command.md +12 -11
- package/skills/orchestrate-loop/command.md +12 -12
- package/skills/pause-work/SKILL.md +1 -0
- package/skills/pause-work/agents/openai.yaml +2 -0
- package/skills/pause-work/command.md +1 -1
- package/skills/plan-phase/SKILL.md +1 -0
- package/skills/plan-phase/agents/openai.yaml +2 -0
- package/skills/plan-phase/command.md +16 -38
- package/skills/progress/SKILL.md +1 -0
- package/skills/progress/agents/openai.yaml +2 -0
- package/skills/quick/SKILL.md +2 -1
- package/skills/quick/agents/openai.yaml +2 -0
- package/skills/quick/command.md +9 -78
- package/skills/resolve-conflicts/command.md +2 -15
- package/skills/resume-work/SKILL.md +1 -0
- package/skills/resume-work/agents/openai.yaml +2 -0
- package/skills/saga-spawner/SKILL.md +1 -1
- package/skills/tdd-workflow/SKILL.md +15 -104
- package/skills/triage/SKILL.md +2 -1
- package/skills/triage/agents/openai.yaml +2 -0
- package/skills/triage/command.md +3 -14
- package/skills/typescript-discipline/SKILL.md +12 -42
- package/skills/typescript-discipline/references/patterns.md +25 -266
- package/skills/unslop/SKILL.md +14 -105
- package/skills/verification-gate/SKILL.md +16 -76
- package/skills/verify-work/SKILL.md +1 -0
- package/skills/verify-work/agents/openai.yaml +2 -0
- package/skills/verify-work/command.md +17 -106
- package/skills/why/SKILL.md +1 -1
- package/skills/why/command.md +18 -118
package/commands/why.md
CHANGED
|
@@ -6,136 +6,36 @@ allowed-tools: Bash, Read, Task
|
|
|
6
6
|
|
|
7
7
|
# /why
|
|
8
8
|
|
|
9
|
-
Reconstruct why code is the way it is — the design rationale, the history, the rejected alternatives — from the evidence the repository and its surroundings actually carry. The output is a confidence-tiered, citation-backed answer with an explicit coverage map, never a plausible story.
|
|
10
|
-
|
|
11
|
-
## Usage
|
|
12
|
-
```
|
|
13
|
-
/why <file, symbol, or question>
|
|
14
|
-
```
|
|
15
|
-
|
|
16
9
|
Question: $ARGUMENTS
|
|
17
10
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
## Routing
|
|
21
|
-
|
|
22
|
-
`/why` answers intent, history, and forces. Something misbehaving right now is a defect — route it to `/fix`, which is reproduction-gated. A `/why` run that uncovers a live defect hands off to `/fix`; a `/fix` that needs design intent (is this behaviour a decision or an accident?) consults `/why`. For structure and architecture walkthroughs — what the code IS rather than why it is that way — use `/map-codebase`.
|
|
23
|
-
|
|
24
|
-
## Epistemics
|
|
25
|
-
|
|
26
|
-
Every claim in the output follows the `epistemics` skill — five confidence tiers, cite-or-label-as-inference, null results as evidence. Load it before synthesising; the epistemic framing is the product, and de-hedging it to sound authoritative is the exact failure this command exists to prevent.
|
|
27
|
-
|
|
28
|
-
## Steps
|
|
29
|
-
|
|
30
|
-
### 1 — Parse the target and the question archetype
|
|
31
|
-
|
|
32
|
-
Identify what is being asked about (file, symbol, pattern, value) and which archetype the question is: design rationale ("why is this a queue?"), tradeoff-vs-alternative ("why X instead of Y?"), defensive reasoning ("why the triple-check here?"), external forcing function ("why did this change in March?"), dead code ("why does this exist at all?"), or a broad sweep ("why is this module shaped like this?"). If the target is vague, state your best-guess interpretation from context and proceed — do not block on a clarifying question.
|
|
33
|
-
|
|
34
|
-
### 2 — Build the code anchor
|
|
35
|
-
|
|
36
|
-
Cheap, done once by the lead, pasted into every brief:
|
|
37
|
-
|
|
38
|
-
- file paths and line ranges; the key symbols involved
|
|
39
|
-
- `git blame -L <range> <file>` on the target lines
|
|
40
|
-
- `git log --follow --oneline -20 <file>`
|
|
41
|
-
- PR numbers extracted from `(#N)` commit subjects; for each, `gh pr view <n> --json title,body,author,createdAt,mergedAt,labels,closingIssuesReferences,comments,reviews`
|
|
42
|
-
- linked ticket and ADR identifiers found along the way
|
|
43
|
-
- optionally a pasted `draht-tools graph-context <file>` slice for orientation (lead-only; subagents cannot run draht-tools)
|
|
44
|
-
|
|
45
|
-
### 3 — Probe the evidence map
|
|
46
|
-
|
|
47
|
-
Five categories. Probe availability before dispatching; each row is the assigned investigator's playbook.
|
|
48
|
-
|
|
49
|
-
| Category | Availability probe | What it uniquely surfaces + playbook |
|
|
50
|
-
|---|---|---|
|
|
51
|
-
| Git history | Always available | Pickaxe (`git log -S`/`-G`), blame, `git show`; test names encoding edge cases; `red:`/`green:`/`refactor:` and `docs:` prefixes as semantic signal. Pitfalls: squash flatlands → fall back to the PR record; misleading messages → read the diff; cargo-culted patterns → investigate the origin commit; bot commits carry no motivation. |
|
|
52
|
-
| Review record | `git remote` + `gh auth status` | PR bodies, review threads, linked issues — the argument that happened before merge, including rejected alternatives. |
|
|
53
|
-
| Planning record | `.planning/` exists | `STATE.md` `## Decisions` (dated, attributed) and `## Lessons`; `phases/NN-*/` PLAN, SUMMARY, VERIFICATION, and UAT files (observed/derived/assumed labels); `specs/`; `quick/`; `loop/PROGRESS.md`; `CONTINUE-HERE.md`. Probe before assuming `.planning/decisions/` and `.planning/tickets/` — they exist only when a grill chose that output. |
|
|
54
|
-
| Decision records | `docs/adr/` and `CHANGELOG.md` files exist | ADR titles are decisions; dated Update blocks cite forcing commits; per-package changelogs date user-visible shifts. |
|
|
55
|
-
| External systems | A registered extension tool only | Tracker, chat, observability, error tracking, analytics — the conversational and operational record. Searchable only via a project-registered tool; when none exists, do not dispatch: record one Sources Consulted gap line — "External records: unavailable — no tool registered in this runtime; the conversational and operational record was not searched." |
|
|
56
|
-
|
|
57
|
-
The map is extensible: a project-registered tool adds an investigator with the same brief shape; an unavailable category is a coverage gap, never a silent drop.
|
|
58
|
-
|
|
59
|
-
**Incident overlay**: when the target looks defensive — null guards, retry, timeout, rate limiting, feature flags — instruct every investigator to hunt incident-shaped evidence inside its own category: revert-then-reapply chains, `## Lessons` entries, ADR Update blocks, UAT failure verdicts.
|
|
60
|
-
|
|
61
|
-
### 4 — Dispatch parallel investigators
|
|
62
|
-
|
|
63
|
-
Dispatch one investigator per AVAILABLE category, all in a single assistant turn when the host allows it; if the category count exceeds what the host can dispatch at once, fold overflow into the nearest category. Skip rules:
|
|
64
|
-
|
|
65
|
-
- A skip needs a written justification that surfaces in Sources Consulted. Unavailability is a gap, not a choice.
|
|
66
|
-
- "Provably irrelevant, not just probably" — a build-time script with no runtime path provably cannot appear in runtime error tracking; "it's feature code, error tracking won't have anything" is a guess, so search it.
|
|
67
|
-
|
|
68
|
-
Each brief is standalone:
|
|
69
|
-
|
|
70
|
-
```
|
|
71
|
-
You are investigating ONE evidence category for a why-question. Gather evidence, not narrative — a verbatim quote with a precise citation beats a paragraph of plausible summary.
|
|
72
|
-
|
|
73
|
-
Question: <the question and its archetype>
|
|
74
|
-
|
|
75
|
-
Code anchor:
|
|
76
|
-
<the anchor from Step 2>
|
|
77
|
-
|
|
78
|
-
Your category: <name + the playbook row from Step 3>
|
|
79
|
-
<if the incident overlay applies: hunt incident-shaped evidence inside your category — revert/re-apply chains, Lessons entries, ADR Update blocks, UAT failure verdicts>
|
|
80
|
-
|
|
81
|
-
Report using exactly these sections: Source / What I Searched (queries verbatim) / Direct Evidence Found / Indirect-Circumstantial Evidence (inference chain + alternative readings) / Contradictions / Gaps / Additional Leads.
|
|
82
|
-
|
|
83
|
-
Stay inside your category; record cross-category references under Additional Leads for the owning investigator — never chase them.
|
|
84
|
-
|
|
85
|
-
Do NOT run draht, draht-tools, or pi commands.
|
|
86
|
-
|
|
87
|
-
End with STATUS: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
`NEEDS_CONTEXT` / `BLOCKED` → supply the missing info and re-dispatch. Hard cap: 3 re-dispatches total.
|
|
91
|
-
|
|
92
|
-
### 5 — Synthesize (the lead, in this context)
|
|
11
|
+
Explain historical intent from evidence. Use `epistemics` to distinguish direct statements, supported conclusions, inference, speculation, and unknowns. Current defects belong in `/fix`; a structural walkthrough may use `/map-codebase`.
|
|
93
12
|
|
|
94
|
-
|
|
95
|
-
- Merge duplicate citations into one authoritative reference.
|
|
96
|
-
- Surface contradictions without picking a side.
|
|
97
|
-
- Tier every claim per the `epistemics` skill.
|
|
98
|
-
- Hand each investigator's Additional Leads to the owning category's follow-up, or record them as gaps.
|
|
99
|
-
- When competing hypotheses are decision-changing for an imminent code change, consult the `advisor` agent with the tiered findings for a steer.
|
|
13
|
+
## Investigate
|
|
100
14
|
|
|
101
|
-
|
|
15
|
+
Identify the target files/symbols and the specific decision being asked about. Read the relevant source, blame, and history; use `git log --follow`, pickaxe, and linked PR/issue discussions to trace the decision. Source mechanics alone do not establish motivation.
|
|
102
16
|
|
|
103
|
-
|
|
17
|
+
Select evidence sources that can answer the question:
|
|
104
18
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
6. **What We Don't Know** — specific searches that came up empty, named unavailable sources, people who would know
|
|
111
|
-
7. **Sources Consulted** — one line per category INCLUDING empties, gaps, and justified skips: `- <Category>: <what was searched>. <found / no relevant results / skipped: reason / unavailable: gap>`
|
|
112
|
-
8. **Confidence Summary** — 1-2 sentences
|
|
19
|
+
- Git history and changed tests: origin, later changes, reversions, and constraints.
|
|
20
|
+
- PR/review record: rejected alternatives and discussion before merge.
|
|
21
|
+
- Existing planning records: decisions, lessons, summaries, verification, and handoffs.
|
|
22
|
+
- ADRs and changelogs: recorded rationale and later revisions.
|
|
23
|
+
- Available external tools: relevant tracker, conversation, or operational evidence. Do not invent access or contact people.
|
|
113
24
|
|
|
114
|
-
|
|
25
|
+
Follow decisive leads, including incident evidence for defensive code. A direct answer in a relevant record may be sufficient; do not require an investigator for every category. Report unavailable sources when they materially limit the answer.
|
|
115
26
|
|
|
116
|
-
|
|
27
|
+
## Delegate when useful
|
|
117
28
|
|
|
118
|
-
|
|
29
|
+
Use `investigator` agents for independent evidence searches. Give each only the question, code anchor, assigned sources, relevant leads, and read-only scope. Shared investigator instructions already define citations and reporting; avoid copying the entire protocol into every task.
|
|
119
30
|
|
|
120
|
-
|
|
31
|
+
Require `STATUS: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED`. Supply available missing context for `NEEDS_CONTEXT`; an unavailable required tool is a blocker, not a reason to retry unchanged. At most 3 re-dispatches total.
|
|
121
32
|
|
|
122
|
-
|
|
33
|
+
The lead checks load-bearing citations, merges duplicate evidence, and resolves cross-source leads. Consult the `advisor` agent when a contested inference would change an imminent implementation decision.
|
|
123
34
|
|
|
124
|
-
|
|
35
|
+
## Report
|
|
125
36
|
|
|
126
|
-
|
|
127
|
-
- Citing code as evidence of its own intent
|
|
128
|
-
- Recency bias — explaining an accretion as one decision; trace back
|
|
129
|
-
- Sycophantic agreement with the asker's embedded hypothesis
|
|
130
|
-
- Skipping the gaps section
|
|
131
|
-
- Skipping investigators by anticipation — a null result is a data point; a skipped search is a blind spot
|
|
132
|
-
- Collapsing categories into one investigator
|
|
37
|
+
Lead with the answer and its confidence. Separate what sources establish from what is inferred; cite each material claim and preserve contradictions. Include unresolved hypotheses only when they help answer the question.
|
|
133
38
|
|
|
134
|
-
|
|
39
|
+
End with a concise **Sources Consulted** account of the searches, relevant null results, and material coverage gaps. Do not require empty headings or searches unrelated to the question. Follow `unslop` for prose and `explainers` when a timeline, dependency, or causal diagram helps.
|
|
135
40
|
|
|
136
|
-
|
|
137
|
-
|--------|---------|
|
|
138
|
-
| "The commit message says X, done" | One source is a lead, not a verdict — the record contradicts itself more often than it lies consistently. |
|
|
139
|
-
| "The code obviously does this for performance" | Code is mechanics; motivation needs an external source or an [Inferred] label. |
|
|
140
|
-
| "The user already told me why" | That is a hypothesis; check it independently. |
|
|
141
|
-
| "No .planning/ here, nothing to search" | git and gh still exist; report the missing categories as gaps, don't invent. |
|
|
41
|
+
When this investigation precedes a change, state the resulting Preserve / Change / Avoid / Risk constraints. These can guide ordinary implementation or an explicitly selected GSD plan.
|
package/hooks/hooks.json
CHANGED
|
@@ -45,6 +45,16 @@
|
|
|
45
45
|
}
|
|
46
46
|
],
|
|
47
47
|
"PreToolUse": [
|
|
48
|
+
{
|
|
49
|
+
"matcher": "Bash|bash|exec_command|shell_command",
|
|
50
|
+
"hooks": [
|
|
51
|
+
{
|
|
52
|
+
"type": "command",
|
|
53
|
+
"command": "node \"${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT}}/scripts/git-safety-hook.cjs\"",
|
|
54
|
+
"timeout": 10
|
|
55
|
+
}
|
|
56
|
+
]
|
|
57
|
+
},
|
|
48
58
|
{
|
|
49
59
|
"matcher": "Edit|Write|MultiEdit",
|
|
50
60
|
"hooks": [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "draht-codex",
|
|
3
|
-
"version": "2026.10.
|
|
3
|
+
"version": "2026.10.23",
|
|
4
4
|
"description": "Draht GSD, multi-agent, TDD and DDD workflows as a Codex plugin. Install with `npx draht-codex install`.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
"scripts": {
|
|
25
25
|
"sync-tools": "node ../../scripts/sync-draht-tools.mjs",
|
|
26
26
|
"test": "node cli.mjs --help > /dev/null && node scripts/gsd-pre-execute.cjs --self-check 2>/dev/null || true",
|
|
27
|
-
"prepublishOnly": "node ../../scripts/sync-draht-tools.mjs && node ../../scripts/generate-skills-artifacts.mjs --check"
|
|
27
|
+
"prepublishOnly": "node ../../scripts/sync-draht-tools.mjs && node ../../scripts/generate-skills-artifacts.mjs --check && node ../../scripts/sync-checks-runtime.mjs --check"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@draht/tools": "2026.10.
|
|
30
|
+
"@draht/tools": "2026.10.23"
|
|
31
31
|
},
|
|
32
32
|
"keywords": [
|
|
33
33
|
"codex",
|
|
@@ -52,6 +52,6 @@
|
|
|
52
52
|
"directory": "packages/draht-codex"
|
|
53
53
|
},
|
|
54
54
|
"engines": {
|
|
55
|
-
"node": "
|
|
55
|
+
"node": "^22.23.4 || ^24.22.1 || ^26.12.1"
|
|
56
56
|
}
|
|
57
57
|
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// Canonical runtime. scripts/sync-checks-runtime.mjs copies this into each plugin.
|
|
5
|
+
const { execFileSync, spawnSync } = require("node:child_process");
|
|
6
|
+
const { createHash } = require("node:crypto");
|
|
7
|
+
const fs = require("node:fs");
|
|
8
|
+
const path = require("node:path");
|
|
9
|
+
|
|
10
|
+
const VERSION = 1;
|
|
11
|
+
const TOTAL_TIMEOUT_MS = 150000;
|
|
12
|
+
const MAX_OUTPUT = 4000;
|
|
13
|
+
|
|
14
|
+
function digest(value) {
|
|
15
|
+
return createHash("sha256").update(value).digest("hex");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function git(cwd, args) {
|
|
19
|
+
return execFileSync("git", args, { cwd, encoding: "utf8", timeout: 10000, maxBuffer: 32 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function findConfig(cwd) {
|
|
23
|
+
let directory = path.resolve(cwd);
|
|
24
|
+
while (true) {
|
|
25
|
+
const file = path.join(directory, ".draht", "checks.json");
|
|
26
|
+
if (fs.existsSync(file)) return { file, root: directory };
|
|
27
|
+
const parent = path.dirname(directory);
|
|
28
|
+
if (fs.existsSync(path.join(directory, ".git")) || parent === directory) return null;
|
|
29
|
+
directory = parent;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function relativePath(value, field) {
|
|
34
|
+
if (typeof value !== "string" || !value || path.isAbsolute(value) || value.includes("\0") || /[*?\[\]{}]/.test(value)) {
|
|
35
|
+
throw new Error(`${field} must be a relative file or directory path (no globs)`);
|
|
36
|
+
}
|
|
37
|
+
const normalized = path.normalize(value);
|
|
38
|
+
if (normalized === ".." || normalized.startsWith(`..${path.sep}`)) throw new Error(`${field} must stay inside the project`);
|
|
39
|
+
return normalized.split(path.sep).join("/").replace(/\/+$/, "");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function loadConfig(location) {
|
|
43
|
+
const source = fs.readFileSync(location.file, "utf8");
|
|
44
|
+
const raw = JSON.parse(source);
|
|
45
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("checks.json must contain an object");
|
|
46
|
+
if (raw.enabled !== undefined && typeof raw.enabled !== "boolean") throw new Error("enabled must be a boolean");
|
|
47
|
+
if (raw.enabled === false) return { enabled: false, checks: [] };
|
|
48
|
+
if (!Array.isArray(raw.checks) || raw.checks.length === 0) throw new Error("checks must be a nonempty array");
|
|
49
|
+
const names = new Set();
|
|
50
|
+
const checks = raw.checks.map((check) => {
|
|
51
|
+
if (!check || typeof check !== "object" || typeof check.name !== "string" || !check.name.trim() || names.has(check.name)) {
|
|
52
|
+
throw new Error("each check needs a unique nonempty name");
|
|
53
|
+
}
|
|
54
|
+
names.add(check.name);
|
|
55
|
+
if (!Array.isArray(check.command) || check.command.length === 0 || check.command.some((part) => typeof part !== "string" || part.includes("\0")) || !check.command[0]) {
|
|
56
|
+
throw new Error(`${check.name}: command must be an argv array`);
|
|
57
|
+
}
|
|
58
|
+
if (check.timeoutMs !== undefined && (!Number.isInteger(check.timeoutMs) || check.timeoutMs < 1 || check.timeoutMs > TOTAL_TIMEOUT_MS)) {
|
|
59
|
+
throw new Error(`${check.name}: timeoutMs must be between 1 and ${TOTAL_TIMEOUT_MS}`);
|
|
60
|
+
}
|
|
61
|
+
if (check.cache !== undefined && typeof check.cache !== "boolean") throw new Error(`${check.name}: cache must be a boolean`);
|
|
62
|
+
if (check.inputs !== undefined && (!Array.isArray(check.inputs) || check.inputs.length === 0)) throw new Error(`${check.name}: inputs must be a nonempty array`);
|
|
63
|
+
return {
|
|
64
|
+
name: check.name,
|
|
65
|
+
command: check.command,
|
|
66
|
+
cwd: relativePath(check.cwd ?? ".", `${check.name}.cwd`),
|
|
67
|
+
inputs: (check.inputs ?? ["."]).map((input) => relativePath(input, `${check.name}.inputs`)),
|
|
68
|
+
timeoutMs: check.timeoutMs ?? 30000,
|
|
69
|
+
cache: check.cache !== false,
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
return { enabled: true, checks, sourceHash: digest(source) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function repository(root) {
|
|
76
|
+
// Outside Git, configured checks still run; there is no evidence cache.
|
|
77
|
+
let directory = root;
|
|
78
|
+
while (!fs.existsSync(path.join(directory, ".git"))) {
|
|
79
|
+
const parent = path.dirname(directory);
|
|
80
|
+
if (parent === directory) return null;
|
|
81
|
+
directory = parent;
|
|
82
|
+
}
|
|
83
|
+
const cachePath = git(root, ["rev-parse", "--path-format=absolute", "--git-path", `draht/checks/${digest(root)}.json`]).trim();
|
|
84
|
+
let revision = "unborn";
|
|
85
|
+
try { revision = git(root, ["rev-parse", "--verify", "HEAD"]).trim(); } catch { /* initial repository */ }
|
|
86
|
+
return { cachePath, revision };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function fingerprint(root, check, config, repo) {
|
|
90
|
+
if (!repo || !check.cache) return null;
|
|
91
|
+
const files = new Set(git(root, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0").filter(Boolean));
|
|
92
|
+
for (const input of check.inputs) {
|
|
93
|
+
// Git may omit ignored symlinks; inspect every explicit input ancestor.
|
|
94
|
+
let absolute = root;
|
|
95
|
+
for (const component of input.split("/")) {
|
|
96
|
+
absolute = path.join(absolute, component);
|
|
97
|
+
try {
|
|
98
|
+
if (fs.lstatSync(absolute).isSymbolicLink()) return null;
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (error.code !== "ENOENT") throw error;
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Include explicit ignored files too (e.g. a generated schema).
|
|
105
|
+
try { if (!fs.statSync(path.join(root, input)).isDirectory()) files.add(input); } catch { files.add(input); }
|
|
106
|
+
}
|
|
107
|
+
const hash = createHash("sha256").update(JSON.stringify({ version: VERSION, root, check, config, node: process.version, platform: process.platform, arch: process.arch }));
|
|
108
|
+
hash.update(fs.readFileSync(path.join(root, ".draht", "checks.json")));
|
|
109
|
+
for (const file of [...files].sort()) {
|
|
110
|
+
if (!check.inputs.some((input) => input === "." || file === input || file.startsWith(`${input}/`) || input.startsWith(`${file}/`))) continue;
|
|
111
|
+
hash.update(`\0${file}\0`);
|
|
112
|
+
try {
|
|
113
|
+
const absolute = path.join(root, file);
|
|
114
|
+
const stat = fs.lstatSync(absolute);
|
|
115
|
+
// Submodules and symlinks can depend on content outside this snapshot.
|
|
116
|
+
if (!stat.isFile()) return null;
|
|
117
|
+
hash.update(`${stat.mode}\0`).update(fs.readFileSync(absolute));
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (error.code !== "ENOENT") throw error;
|
|
120
|
+
hash.update("missing");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return hash.digest("hex");
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function readCache(repo) {
|
|
127
|
+
if (!repo) return {};
|
|
128
|
+
try {
|
|
129
|
+
const cached = JSON.parse(fs.readFileSync(repo.cachePath, "utf8"));
|
|
130
|
+
return cached.version === VERSION && cached.checks && typeof cached.checks === "object" ? cached.checks : {};
|
|
131
|
+
} catch { return {}; }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function writeCache(repo, checks) {
|
|
135
|
+
if (!repo) return;
|
|
136
|
+
fs.mkdirSync(path.dirname(repo.cachePath), { recursive: true });
|
|
137
|
+
const temporary = `${repo.cachePath}.${process.pid}.tmp`;
|
|
138
|
+
fs.writeFileSync(temporary, JSON.stringify({ version: VERSION, revision: repo.revision, checks }));
|
|
139
|
+
fs.renameSync(temporary, repo.cachePath);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function runChecks({ cwd = process.cwd(), force = false } = {}) {
|
|
143
|
+
const checks = [];
|
|
144
|
+
let configured = false;
|
|
145
|
+
try {
|
|
146
|
+
const location = findConfig(cwd);
|
|
147
|
+
if (!location) return { status: "skipped", configured, summary: "No .draht/checks.json configured", checks };
|
|
148
|
+
configured = true;
|
|
149
|
+
const config = loadConfig(location);
|
|
150
|
+
if (!config.enabled) return { status: "skipped", configured, summary: "Project checks explicitly disabled", checks };
|
|
151
|
+
const repo = repository(location.root);
|
|
152
|
+
const cache = readCache(repo);
|
|
153
|
+
const current = Object.create(null);
|
|
154
|
+
const snapshots = new Map();
|
|
155
|
+
const deadline = Date.now() + TOTAL_TIMEOUT_MS;
|
|
156
|
+
for (const check of config.checks) {
|
|
157
|
+
const before = fingerprint(location.root, check, config, repo);
|
|
158
|
+
snapshots.set(check.name, before);
|
|
159
|
+
if (!force && before && cache[check.name]?.fingerprint === before && cache[check.name]?.status === "passed") {
|
|
160
|
+
checks.push({ name: check.name, status: "cached", fingerprint: before });
|
|
161
|
+
current[check.name] = cache[check.name];
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const remaining = deadline - Date.now();
|
|
165
|
+
if (remaining <= 0) {
|
|
166
|
+
checks.push({ name: check.name, status: "failed", reason: "Total check time limit reached" });
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const started = Date.now();
|
|
170
|
+
let result;
|
|
171
|
+
try {
|
|
172
|
+
result = spawnSync(check.command[0], check.command.slice(1), {
|
|
173
|
+
cwd: path.resolve(location.root, check.cwd), encoding: "utf8", timeout: Math.min(check.timeoutMs, remaining),
|
|
174
|
+
killSignal: "SIGKILL", maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
|
|
175
|
+
});
|
|
176
|
+
} catch (error) { result = { error }; }
|
|
177
|
+
const passed = !result.error && !result.signal && result.status === 0;
|
|
178
|
+
const reason = passed ? undefined : String(result.error?.code || result.signal || (typeof result.status === "number" ? `exit ${result.status}` : "unknown exit"));
|
|
179
|
+
const record = { name: check.name, status: passed ? "passed" : "failed", reason, durationMs: Date.now() - started,
|
|
180
|
+
output: [result.stdout, result.stderr, result.error?.message].filter(Boolean).join("\n").slice(0, MAX_OUTPUT), fingerprint: before };
|
|
181
|
+
checks.push(record);
|
|
182
|
+
current[check.name] = { ...record, checkedAt: new Date().toISOString() };
|
|
183
|
+
}
|
|
184
|
+
// A formatter or concurrent edit invalidates earlier evidence from this run.
|
|
185
|
+
const configChanged = digest(fs.readFileSync(location.file, "utf8")) !== config.sourceHash;
|
|
186
|
+
for (const check of config.checks) {
|
|
187
|
+
const record = checks.find((entry) => entry.name === check.name);
|
|
188
|
+
const before = snapshots.get(check.name);
|
|
189
|
+
if (record.status !== "failed" && (configChanged || (before && before !== fingerprint(location.root, check, config, repo)))) {
|
|
190
|
+
record.status = "failed";
|
|
191
|
+
record.reason = "Check inputs changed during verification; run again";
|
|
192
|
+
delete current[check.name];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
writeCache(repo, current);
|
|
196
|
+
const failed = checks.filter((check) => check.status === "failed");
|
|
197
|
+
return { status: failed.length ? "failed" : "passed", configured, checks,
|
|
198
|
+
summary: failed.length ? `Project checks failed: ${failed.map((check) => `${check.name} (${check.reason})`).join(", ")}` : `Project checks passed (${checks.filter((check) => check.status === "cached").length} reused, ${checks.filter((check) => check.status === "passed").length} run)` };
|
|
199
|
+
} catch (error) {
|
|
200
|
+
return { status: "failed", configured, checks, summary: `Project checks failed: ${error.message}` };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
module.exports = { findConfig, runChecks };
|
|
205
|
+
|
|
206
|
+
if (require.main === module) {
|
|
207
|
+
const cwdIndex = process.argv.indexOf("--cwd");
|
|
208
|
+
const result = runChecks({ cwd: cwdIndex < 0 ? process.cwd() : process.argv[cwdIndex + 1], force: process.argv.includes("--force") });
|
|
209
|
+
if (process.argv.includes("--json")) console.log(JSON.stringify(result));
|
|
210
|
+
else {
|
|
211
|
+
console.log(result.summary);
|
|
212
|
+
for (const check of result.checks) if (check.output) console.log(`${check.name}: ${check.output}`);
|
|
213
|
+
}
|
|
214
|
+
process.exitCode = result.status === "failed" ? 1 : 0;
|
|
215
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const fs = require("node:fs");
|
|
5
|
+
const { findGitSafetyViolation } = require("./git-safety.cjs");
|
|
6
|
+
|
|
7
|
+
try {
|
|
8
|
+
const event = JSON.parse(fs.readFileSync(0, "utf8"));
|
|
9
|
+
const input = event.tool_input ?? event.arguments ?? {};
|
|
10
|
+
const command = input.command ?? input.cmd;
|
|
11
|
+
if (typeof command === "string") {
|
|
12
|
+
const violation = findGitSafetyViolation(command);
|
|
13
|
+
if (violation) {
|
|
14
|
+
process.stderr.write(`${violation}\n`);
|
|
15
|
+
process.exitCode = 2;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
} catch (error) {
|
|
19
|
+
process.stderr.write(`Git safety hook could not inspect the tool input: ${error.message}\n`);
|
|
20
|
+
process.exitCode = 2;
|
|
21
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// A guard for literal shell commands, not a sandbox or a shell interpreter.
|
|
4
|
+
// Keep this dependency-free so native and plugin hosts use the same policy.
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
|
|
7
|
+
function shellCommands(source, depth = 0) {
|
|
8
|
+
if (depth > 8 || source.length > 262144) return [];
|
|
9
|
+
const commands = [];
|
|
10
|
+
let words = [];
|
|
11
|
+
let word = "";
|
|
12
|
+
let started = false;
|
|
13
|
+
let quote = "";
|
|
14
|
+
const flushWord = () => {
|
|
15
|
+
if (started) words.push(word);
|
|
16
|
+
word = "";
|
|
17
|
+
started = false;
|
|
18
|
+
};
|
|
19
|
+
const flushCommand = () => {
|
|
20
|
+
flushWord();
|
|
21
|
+
if (words.length) commands.push(words);
|
|
22
|
+
words = [];
|
|
23
|
+
};
|
|
24
|
+
for (let i = 0; i < source.length; i++) {
|
|
25
|
+
const ch = source[i];
|
|
26
|
+
if (quote === "'") {
|
|
27
|
+
if (ch === "'") quote = "";
|
|
28
|
+
else word += ch;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (ch === "\\" && i + 1 < source.length) {
|
|
32
|
+
const next = source[++i];
|
|
33
|
+
if (next !== "\n") {
|
|
34
|
+
word += quote === '"' && !['$', '`', '"', "\\"].includes(next) ? `\\${next}` : next;
|
|
35
|
+
started = true;
|
|
36
|
+
}
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (ch === "`" || (ch === "$" && source[i + 1] === "(")) {
|
|
40
|
+
const start = i + (ch === "`" ? 1 : 2);
|
|
41
|
+
let end = start;
|
|
42
|
+
let nesting = 1;
|
|
43
|
+
let innerQuote = "";
|
|
44
|
+
for (; end < source.length; end++) {
|
|
45
|
+
const inner = source[end];
|
|
46
|
+
if (inner === "\\" && innerQuote !== "'") { end++; continue; }
|
|
47
|
+
if (innerQuote) { if (inner === innerQuote) innerQuote = ""; continue; }
|
|
48
|
+
if (inner === "'" || inner === '"') { innerQuote = inner; continue; }
|
|
49
|
+
if (ch === "`" && inner === "`") break;
|
|
50
|
+
if (ch === "$" && inner === "(") nesting++;
|
|
51
|
+
if (ch === "$" && inner === ")" && --nesting === 0) break;
|
|
52
|
+
}
|
|
53
|
+
commands.push(...shellCommands(source.slice(start, end), depth + 1));
|
|
54
|
+
word += "<substitution>";
|
|
55
|
+
started = true;
|
|
56
|
+
i = end;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (quote === '"') {
|
|
60
|
+
if (ch === '"') quote = "";
|
|
61
|
+
else word += ch;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (ch === "'" || ch === '"') { quote = ch; started = true; continue; }
|
|
65
|
+
if (ch === "#" && !started) {
|
|
66
|
+
while (i < source.length && source[i] !== "\n") i++;
|
|
67
|
+
flushCommand();
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (/[;&|()\n]/.test(ch)) { flushCommand(); continue; }
|
|
71
|
+
if (/\s/.test(ch)) { flushWord(); continue; }
|
|
72
|
+
word += ch;
|
|
73
|
+
started = true;
|
|
74
|
+
}
|
|
75
|
+
flushCommand();
|
|
76
|
+
return commands;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function executable(word) {
|
|
80
|
+
return path.posix.basename(word.replace(/\\/g, "/")).replace(/\.exe$/i, "");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function canonicalFlag(word) {
|
|
84
|
+
const equals = word.indexOf("=");
|
|
85
|
+
const option = equals < 0 ? word : word.slice(0, equals);
|
|
86
|
+
// Git accepts unambiguous long-option prefixes, including hook bypasses.
|
|
87
|
+
const guarded = ["--no-verify", "--force", "--force-with-lease", "--force-if-includes"];
|
|
88
|
+
const full = guarded.find((flag) => option.startsWith("--") && option.length > 2 && flag.startsWith(option));
|
|
89
|
+
return full ? full + (equals < 0 ? "" : word.slice(equals)) : word;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function gitArguments(words, subcommand) {
|
|
93
|
+
const flags = [];
|
|
94
|
+
const positional = [];
|
|
95
|
+
const takesValue = new Set([
|
|
96
|
+
"--message", "--file", "--reuse-message", "--reedit-message", "--template", "--author", "--date",
|
|
97
|
+
"--cleanup", "--fixup", "--squash", "--pathspec-from-file", "--push-option", "--receive-pack", "--exec", "--repo",
|
|
98
|
+
]);
|
|
99
|
+
const shortValues = subcommand === "push" ? "o" : "mFCct";
|
|
100
|
+
for (let i = 0; i < words.length; i++) {
|
|
101
|
+
const word = words[i];
|
|
102
|
+
if (word === "--") { positional.push(...words.slice(i + 1)); break; }
|
|
103
|
+
if (word.startsWith("--")) {
|
|
104
|
+
flags.push(canonicalFlag(word));
|
|
105
|
+
if (takesValue.has(word)) i++;
|
|
106
|
+
} else if (word.startsWith("-")) {
|
|
107
|
+
for (let j = 1; j < word.length; j++) {
|
|
108
|
+
if (shortValues.includes(word[j])) { if (j === word.length - 1) i++; break; }
|
|
109
|
+
flags.push(`-${word[j]}`);
|
|
110
|
+
}
|
|
111
|
+
} else positional.push(word);
|
|
112
|
+
}
|
|
113
|
+
return { flags, positional };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function inspectWords(original, depth) {
|
|
117
|
+
const words = [...original];
|
|
118
|
+
let bypassHooks = false;
|
|
119
|
+
while (words.length) {
|
|
120
|
+
if (["if", "then", "elif", "else", "while", "until", "do", "!"].includes(words[0])) {
|
|
121
|
+
words.shift();
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (/^[A-Za-z_][A-Za-z_0-9]*=/.test(words[0])) {
|
|
125
|
+
if (words[0] === "HUSKY=0") bypassHooks = true;
|
|
126
|
+
words.shift();
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const head = executable(words[0]);
|
|
130
|
+
if (["command", "builtin", "exec", "nohup"].includes(head)) {
|
|
131
|
+
words.shift();
|
|
132
|
+
if (words[0] === "--") words.shift();
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (head === "env") {
|
|
136
|
+
words.shift();
|
|
137
|
+
while (words[0]?.startsWith("-")) {
|
|
138
|
+
const flag = words.shift();
|
|
139
|
+
if (["-u", "--unset", "-C", "--chdir"].includes(flag)) words.shift();
|
|
140
|
+
}
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (head === "sudo") {
|
|
144
|
+
words.shift();
|
|
145
|
+
while (words[0]?.startsWith("-")) {
|
|
146
|
+
if (["-u", "-g", "-h", "-p"].includes(words.shift())) words.shift();
|
|
147
|
+
}
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
if (!words.length) return undefined;
|
|
153
|
+
const head = executable(words.shift());
|
|
154
|
+
if (["sh", "bash", "zsh", "dash", "ksh"].includes(head)) {
|
|
155
|
+
const commandFlag = words.findIndex((word) => /^-[^-]*c/.test(word));
|
|
156
|
+
return commandFlag >= 0 ? findGitSafetyViolation(words[commandFlag + 1] ?? "", depth + 1) : undefined;
|
|
157
|
+
}
|
|
158
|
+
if (head !== "git") return undefined;
|
|
159
|
+
while (words[0]?.startsWith("-")) {
|
|
160
|
+
const option = words.shift();
|
|
161
|
+
if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(option)) {
|
|
162
|
+
const value = words.shift() ?? "";
|
|
163
|
+
if ((option === "-c" || option === "--config-env") && /^core\.hooksPath=/i.test(value)) bypassHooks = true;
|
|
164
|
+
} else if (/^-ccore\.hooksPath=|^--config-env=core\.hooksPath=/i.test(option)) bypassHooks = true;
|
|
165
|
+
}
|
|
166
|
+
const subcommand = words.shift();
|
|
167
|
+
if (!["commit", "push", "merge", "rebase", "am"].includes(subcommand)) return undefined;
|
|
168
|
+
const { flags, positional } = gitArguments(words, subcommand);
|
|
169
|
+
if (bypassHooks || flags.includes("--no-verify") || (subcommand === "commit" && flags.includes("-n"))) {
|
|
170
|
+
return "Git hook bypass is disabled. Run the required checks and keep commit/push hooks enabled.";
|
|
171
|
+
}
|
|
172
|
+
if (subcommand !== "push") return undefined;
|
|
173
|
+
if (positional.some((word) => word.startsWith("+"))) return "Forced Git refspecs are disabled. Use a normal push.";
|
|
174
|
+
for (const word of flags) {
|
|
175
|
+
if (word === "--force" || word === "--force-if-includes" || word === "-f") {
|
|
176
|
+
return "Forced Git updates are disabled. Reconcile the branch and use a normal push.";
|
|
177
|
+
}
|
|
178
|
+
if (word.startsWith("--force-with-lease")) {
|
|
179
|
+
// A named ref with an empty expectation creates only an absent ref;
|
|
180
|
+
// the saga lock uses this compare-and-set operation without rewriting history.
|
|
181
|
+
if (!/^--force-with-lease=refs\/[A-Za-z0-9_./-]+:$/.test(word)) {
|
|
182
|
+
return "Forced Git updates are disabled. Only an explicit create-if-absent ref lease is allowed.";
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function findGitSafetyViolation(command, depth = 0) {
|
|
190
|
+
if (typeof command !== "string" || depth > 8) return undefined;
|
|
191
|
+
for (const words of shellCommands(command, depth)) {
|
|
192
|
+
const violation = inspectWords(words, depth);
|
|
193
|
+
if (violation) return violation;
|
|
194
|
+
}
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
module.exports = { findGitSafetyViolation };
|