* feat(#2255): blocking catastrophic-shrink guard for .planning writes Adds hooks/gsd-write-guard.js, a PreToolUse hook that hard-blocks (decision: 'block', exit 2) a whole-file Write collapsing a curated .planning/ artifact (ROADMAP.md, .planning/milestones/*-ROADMAP.md, STATE.md) below 40% of its on-disk line count. Files under 40 lines are exempt; GSD_ALLOW_PLANNING_SHRINK=1 (named in the block message) bypasses for legitimate milestone resets. Fix 3 of #973 — the only defense independent of per-agent tool config. Registered on the Claude plugin surface (hooks.json), settings-json runtimes (runtime-hooks-surface.cts, self-contained pattern), Kimi spec, and the OpenCode/Kilo plugin buses. Golden install fixtures and INVENTORY regenerated; regression tests negative-controlled (16/16 RED with the hook absent, 16/16 GREEN with it present). * chore(#2255): backfill changeset pr number to 2301 * enhance(#2255): address review — fail-closed reads, typed block output, registration, property test Review fixes for trek-e's CHANGES_REQUESTED on PR #2301: - Blocker 2: register gsd-write-guard.js in BUNDLED_GSD_HOOK_FILES (no-shipping-drift test). - Blocker 3: update the always-on hook enumerations in ADR-766 and CONTEXT.md from six to seven. - Major 4: fail CLOSED on non-ENOENT read errors — only a missing file (new-file Write) passes; EACCES/EISDIR/ELOOP/etc now block, with a typed readError field and the override still honored. Tested, with a negative control against the pre-fix hook. - Major 5: fast-check property test for the SHRINK_RATIO/FLOOR_LINES budget contract (blocked ⟺ newLines < oldLines*SHRINK_RATIO above the floor; sub-floor always exempt), boundary examples pinned. - Major 6: block output now carries typed oldLines/newLines/ overrideEnvVar fields; tests assert on those instead of regexing the free-form reason string. - Minor: CURATED_PATTERNS are case-insensitive (case-insensitive-FS bypass on macOS/Windows); limit+1 boundary tests added for both the floor and the ratio. * enhance(#2255): engage the write guard on Kimi's native payload shape The guard shipped with Claude-vocabulary checks (tool_name 'Write', tool_input.file_path), which #2304 showed leaves a guard dormant on Kimi: the [[hooks]] matcher is registered pre-translated but kimi-cli forwards its native payload verbatim — tool_name 'WriteFile' (bare or module-qualified) and tool_input.path per its tool schemas (src/kimi_cli/tools/file/write.py). The guard matched, saw an unknown name, and exited 0. Apply the same per-guard normalization PR #2326 gives the three sibling guards (name + field mapping, inlined — hook scripts stage as standalone files), and write the block reason to stderr as well as stdout JSON: Kimi feeds stderr, not stdout, back to the model on exit 2, so a stdout-only reason blocks without telling the model why or naming the documented override. Regression tests pipe Kimi-shaped payloads (engage, qualified-name, stderr-reason) plus exemption pins (StrReplaceFile stays out of scope by design; non-curated paths pass) — verified red against the pre-fix guard, green after. * enhance(#2255): rebase onto next; regenerate golden-parity fixtures * enhance(#2255): wire the escape hatch into complete-milestone's reorganize step Review Blocker 1: the guard hard-blocked /gsd:complete-milestone's ROADMAP reorganize — the tree's only legitimate milestone reset and the exact caller GSD_ALLOW_PLANNING_SHRINK was built for. The reorganize step now performs the rewrite through a shell write with the hatch set on the command (a hook inherits the runtime env, so a bare Write cannot carry a per-step override), and a binding test derives the env var name from the guard's typed output and asserts (a) the workflow step sets it and (b) the guard passes the identical catastrophic payload under it — so the next complete-milestone.md edit cannot silently re-break the wiring. * enhance(#2255): drop dead Edit-class mapping from normalizeKimiPayload Review Major 1: StrReplaceFile -> 'Edit' and the old_string/new_string reconstruction were unreachable-by-effect — the guard exits 0 for any tool_name !== 'Write', so nothing ever read the fields they set, leaving guaranteed-surviving mutants against the Stryker bar. The map now carries only WriteFile -> 'Write'; the StrReplaceFile exemption test message states the fall-through it actually exercises. * enhance(#2255): review minors — American spellings; writeSync before exit(2) Minor 1: normalised/normalise -> American house style. Minor 2: the two block paths wrote stdout+stderr via async pipe writes then exit(2) — async-on-Windows, unflushed at exit; fs.writeSync(1/2, ...) makes the block payload durable. * enhance(#2255): assert stderr equals the typed reason, not raw prose Minor 3: the last raw-text match in the suite pinned override-name prose on stderr. The contract is "stderr carries the reason Kimi feeds back" — now asserted as stderr non-empty and byte-equal to the parsed stdout.reason. * enhance(#2255): bind the write-guard's Kimi normalization into the parity test Review Major 2: the guard's normalizeKimiPayload is a 4th inlined copy with nothing binding it. This extends PR #2326's kimi-guard-normalization-parity test (same path and helpers, authored as a superset so either merge order resolves cleanly): sibling byte-parity is existence-gated zero-or-all — trivially green until #2326 lands, full-strength after — and the write-guard copy is bound semantically (map is the value-inverse of convertKimiToolName; the Kimi name for Write must map, or the guard is dormant on Kimi; the path -> file_path half must be present). Byte-parity is deliberately not asserted for this copy: it legitimately omits the Edit-class mapping (Major 1 — dead code in a Write-only guard). * enhance(#2255): refresh golden-parity fixtures for revised guard + workflow * chore(#2255): regenerate golden fixtures after rebase onto next The committed fixture hashes were generated against a tree predating next's latest 11 commits, which independently modified the same install-parity surface. Rebased onto next and regenerated with `npm run gen:golden`. Verified: against upstream/next the regenerated fixtures differ by exactly this PR's own entries -- hooks/gsd-write-guard.js (new), hooks/managed-hooks-registry.cjs, plugins/gsd-core.js, and gsd-core/workflows/complete-milestone.md. No unrelated drift. * fix(#2255): regenerate workflow size baseline for complete-milestone `complete-milestone.md` grew 31071 -> 32061 (+990) when the round-2 review fix bound GSD_ALLOW_PLANNING_SHRINK=1 into the reorganize step, but tests/workflow-size-baseline.json was never regenerated. The per-file workflow baseline test (issue #1074) failed on ubuntu-latest/22 and both macOS shard 1/3 jobs. The growth is justified: it is the escape-hatch binding requested in review round 2 (the guard must not hard-block the tree's only legitimate milestone reset), not incidental bloat. Regenerated via `npm run size:baseline`; the diff is exactly the one entry. * chore(#2255): regenerate golden fixtures and size baseline after rebase onto next * enhance(#2255): bind the shrink escape hatch mechanically — single-use sentinel the guard consumes Round-5 M1: the per-step `GSD_ALLOW_PLANNING_SHRINK=1 tee` prefix was inert (no PreToolUse hook exists on Bash in this family; the write succeeded by dodging the guard, not by the override firing) and the protection was prose. The hatch is now a transport code consults: complete-milestone's reorganize step arms `.planning/.gsd-allow-shrink` with the target's path, keeps the Write tool as the sanctioned path, and the guard — at the block point only — verifies the sentinel is fresh (15 min) and names the pending target, then CONSUMES it and allows that one write. Path-bound + single-use + freshness keep it from becoming a standing unlock. The env var remains as the interactive transport, where it can actually reach the hook. Regression tests written first (negative control: 3 failed pre-fix): the armed-sentinel Write passes and consumes; stale does not exempt; a token for a different file neither exempts nor is consumed; the binding test now takes the sentinel name from the guard's typed output (overrideSentinel), asserts the step arms it, and asserts the step no longer routes the rewrite around Write via a shell pipe. Also in this commit, same file: - m2: block emission is exception-safe — emitBlock() wraps both writeSync sites in their own try/catch that still exits 2, so an EPIPE can no longer convert fail-closed into the outer catch's fail-open. - Header discloses the two reviewed design limits (cumulative sequential shrink; lexical match vs symlinked paths) per round-5 scoping. * docs(#2255): document the sentinel transport across guard surfaces; changeset ends with the (#2255) parenthetical (m4) USER-GUIDE bullet, INVENTORY row (en + ja/ko/pt/zh), the runtime-hooks-surface registration comment, and the changeset now describe both hatches — the single-use sentinel for workflow steps and the env var for interactive use — instead of implying a per-step env can reach a hook. The changeset's trailing `Resolves #2255.` prose becomes the `(#2255)` parenthetical the repo's fragments use (round-5 m4). * chore(#2255): regenerate derived families on the rebased tree (full sweep) Full generator sweep after rebasing onto next @ the body-parser-patched lockfile: build, gen-inventory-manifest, gen:golden, size:baseline. Every regen delta verified to be either a PR-owned entry (gsd-write-guard.js, complete-milestone.md, INVENTORY/USER-GUIDE) or exact convergence to next's committed value for entries our arbitrary-side conflict resolution had left stale (all 18 runtime fixtures checked mechanically). * test(#2255): use helpers.cleanup for sentinel teardown, not raw fs.rmSync The repo's local/no-raw-rmsync-in-tests rule exists for the Windows-EBUSY retry budget; the sentinel disarm now rides it like every other teardown. * chore(#2255): regenerate derived families after rebase onto next Full sweep on the rebased tree (build -> gen-inventory-manifest -> gen:golden -> size:baseline). Every delta is either a PR-owned entry (hooks/gsd-write-guard.js, its registration surfaces hooks/managed-hooks-registry.cjs and the two plugin buses, gsd-core/workflows/complete-milestone.md) or exact convergence to next's committed value across all 18 runtime fixtures. * chore(#2255): regenerate derived families after rebase onto next @a5180d96Rebase onto current `next` (a5180d96) resolved 12 conflicting golden-install-parity fixtures; all regenerated via the full generator sweep (build, gen:golden, size:baseline) rather than a single generator. `lint:generated-sync` reports every generated artifact in sync. All 45 differing fixture keys and the single workflow-size-baseline entry map to files this PR actually touches; no foreign drift. * fix(#2255): remove the stale unguarded reorganize_roadmap step (round-8 blocker) complete-milestone.md carried a second ROADMAP-collapsing step, `reorganize_roadmap`, distinct from the sentinel-armed `reorganize_roadmap_and_delete_originals` this PR wired. It is a vestige of the pre-archive-then-reorganize design: it sits BEFORE archive_milestone, so executing it as written would collapse ROADMAP.md before the archive snapshots the full phase detail — and its Write is exactly the shape gsd-write-guard hard-blocks, with no hatch armed. The file's own success criteria describe only one reorganize outcome (Backlog-preserving, overwrite-in-place — the later step's properties), and archive_milestone points forward to "the reorganize step". Removed rather than wired, per the round-8 review's confirm-and-remove option. A new binding test asserts the sentinel-armed step is the ONLY reorganize step in the workflow, so an unguarded collapse step cannot be silently reintroduced (negative-controlled: fails against the pre-fix tree). Golden-parity fixtures and the size baseline regenerate for the shrunk file; every changed fixture key is complete-milestone.md's own. * test(#2255): document why the read-error injection is a path collision, not an fs monkeypatch Round-8 nit: the non-ENOENT tests inject via a directory-at-target-path collision instead of the repo's fs-method monkeypatch pattern. That is deliberate, not drift — runHook exercises the hook as a spawnSync child process, so an in-process fs.readFileSync patch (the pattern the cited siblings use on require'd, in-process code) can never reach the code under test. Record the reasoning at the injection site. * chore(#2255): regenerate derived families after rebase onto next @0d08c320Rebase onto current next (0d08c320) for the CONFLICTING/DIRTY state. All 32 conflicts were generated artifacts (19 golden-install-parity, 12 install-tree, workflow-size-baseline); resolved arbitrarily and regenerated via a full generator sweep (build, gen:golden, size:baseline, gen-inventory-manifest) rather than hand-merged. No source conflicts. Regen diff verified against the PR's changed-file set: 7 distinct differing keys, all PR-owned (gsd-write-guard.js, managed-hooks-registry.cjs, plugins/gsd-core.js, complete-milestone.md, and their .kimi mirrors). lint:generated-sync clean. * chore(#2255): regenerate derived families after rebase onto next @9138271bConflict set was 20 paths, every one a generated artifact, zero source conflicts — resolved arbitrarily during the replay and regenerated here, per the maintainer's round-9 recipe (never hand-merged). Generator sweep (not just gen:golden): npm run build, gen:golden, size:baseline, gen-inventory-manifest, gen:registry. INVENTORY-MANIFEST came back byte-identical, so the merged value was already correct. Regen diff verified == PR-touched entries: every differing leaf key attributes to a file this PR changes (complete-milestone.md, the guard, managed-hooks-registry.cjs, both plugin buses) — derived from the changed-file set, not a feature-name filter. * fix(#2255): port the #2595 Kimi-payload hardening the base landed for the sibling guards Self-found via the round-10 base sweep:a8b40fa5(#2547/PR #2595) hardened gsd-prompt/read/worktree-path-guard's normalizeKimiPayload after this PR was authored, and this guard carried all three pre-fix shapes: - `path` now wins outright over a model-supplied `file_path` — kimi-cli's WriteFile schema carries no `file_path`, so a payload pairing a curated `path` with a spurious `file_path: ""` had the guard reading '' and exiting 0 while kimi-cli wrote to `path` (one-key bypass, no crash needed). - null/primitive payloads pass through deliberately instead of throwing into the fail-open catch. - the `file_path` read is typed (`typeof === 'string'`), closing the crash-to-allow on `[]`/`{}` — this is what the base-added kimi-guard-typed-payload-reads scan flags. Negative-controlled: the shadowing payload exits 0 against the pre-fix guard and 2 against this one. * fix(#2255): round 9 Major 2 — stop printing the sentinel recipe in the agent-facing denial The block message ended by telling the blocked agent exactly how to arm the single-use sentinel — handing the #973 actor a mechanical self-authorization in the moment it is blocked. The recipe is gone from the prose; the corrective advice and the env override's name stay (the latter is a #2255 acceptance criterion, and a per-step env prefix cannot reach a hook anyway), and the typed overrideSentinel field stays for the binding tests. The hatch remains documented in USER-GUIDE.md and complete-milestone.md, where humans and the workflow engine read. * fix(#2255): round 9 Minors 1-2 — realpath-resolve the target before the curated match; disclose the /i Linux cost Minor 1: a Write to a non-curated path that symlinks into a curated file was not matched while writeFileSync followed the link — the target is now realpath-resolved before the curated match (ENOENT keeps the lexical resolution so new-file Writes still pass; any other realpath error falls through to the read, which fails closed). Negative-controlled: the symlink payload exits 0 against the pre-fix guard, 2 against this one. Test skips on win32, where symlink creation needs privilege. Minor 2: the header's design-limits block now names the unconditional /i cost on case-sensitive Linux (a genuinely distinct .planning/roadmap.md is also treated as curated) next to the stateless limit, and drops the closed symlink limit. * test(#2255): round 9 Minors 3-4 — CRLF counting pin + a passing Write leaves a fresh sentinel unburned Minor 3: countLines' split('\n') is CRLF-safe for a count (the \r rides along), confirmed by trace in the review — this pins it against this repo's recurring CRLF regressions, on both sides of the compare and at the 40% boundary. Minor 4: consumeSentinelFor runs only after the ratio check would block, so a within-tolerance Write never burns the workflow's token — true by construction, previously un-asserted. * fix(#2255): round 9 Major 3 — correct the stale env-var line in archive_milestone's summary complete-milestone.md's "After archival" bullet still said the reorganize happens "under GSD_ALLOW_PLANNING_SHRINK=1" — the wording from the round-2 design this PR's own history rejected in round 5 (a per-step env var cannot reach a hook; setting it in a Bash step silently does nothing). It now points at the sentinel mechanics the reorganize step actually documents, matching that step and USER-GUIDE.md. * docs(#2255): round 9 Major 1 — user-facing docs state the stateless per-Write limit The changeset and USER-GUIDE described the guard as covering "catastrophically shrinks" with no caveat, while the stateless design was disclosed only in the hook header — an operator reading the shipped docs would conclude iterative erosion is covered. Both surfaces now state the per-Write comparison and the erosion non-goal explicitly, in line with what the guard does. * fix(#2255): round 10 Blocker 1 — arm the hatch in the roadmapper's curated writes gsd-roadmapper Step 7 Writes both .planning/ROADMAP.md and .planning/STATE.md wholesale, and /gsd:new-milestone spawns it against the OUTGOING milestone's files. new-milestone's `phases.clear` archives phase DIRECTORIES, never ROADMAP.md, so nothing compacts it first, and no ordering rule forces /gsd:complete-milestone to run before /gsd:new-milestone. Measured against the shipped hook at the #973 file size (292 lines): a new 4-phase roadmap lands at 18.2% and an 8-phase one at 31.8% — both blocked; only a 12-phase replacement (45.5%) clears. So the collapse is reachable on a first-party flow, which is the failure mode #2255 para 4 says the guard must not have. Arms the single-use sentinel immediately before each Write, one per target (the token is path-bound and single-use, so one arming cannot cover both), and gates each arming on `[ -f ]` so the /gsd:new-project path — where the guard already exempts via ENOENT — strands no unconsumed token. Binding test derives the sentinel name from the guard's own typed output, so a rename on either side fails the suite instead of silently unwiring the hatch. Negative-controlled: 2 assertions fail against the pre-fix roadmapper. * docs(#2255): round 10 Major 2 — scope the claim to the guarantee that ships The sentinel is a plain file, so an agent that would reason past an advisory can arm one with a single Bash call it is already permitted to make. The "only defense independent of per-agent tool config" framing outran that, and the changeset was on its way into CHANGELOG.md. Retitles the claim on all three surfaces (changeset, guard header, USER-GUIDE) to what the guard actually delivers: it blocks accidental and single-shot collapse and is not a defense against a determined agent; what it converts is "ignore a sentence" into "take one deliberate, path-bound, single-use, auditable action". Pinned by test on the DURABLE surfaces only — the guard header and USER-GUIDE. The changeset fragment is deliberately not pinned: it is consumed at release, so a test reading it would start failing the moment the release lands. The bound-statement assertion normalizes comment markers and whitespace first, so it pins the claim rather than the paragraph's line wrapping. Negative-controlled: both assertions fail against the pre-fix surfaces. * test(#2255): acknowledge the roadmapper growth from the round 10 Blocker 1 wiring The emitted-attribution gate (#2719/#2767) flags gsd-roadmapper.md growing 1130 bytes without an acknowledgment. The growth is the Blocker 1 sentinel wiring plus the rationale a future editor needs to keep it, so it gets an ack fragment rather than a silencing regen — the gate's own message is explicit that there is nothing left to regenerate. Fragment is PR-scoped (2301-…) per the gate's naming instruction, and uses the plain-string reason form the shipped fragments use. Verified against the TRUE upstream tip, not the fork's origin/next: a stale origin made this same gate report unrelated phantom drift (1 emitted path + 6 grown files + 5 stale acks) that vanishes when GSD_EMITTED_BASE is pinned. * test(#2255): renumber the roadmapper PROSE_ALLOWLIST pin after the Step 7 wiring CI red on shard 2/3, all four platforms. The #2751 gate keys PROSE_ALLOWLIST on {file, line}; the Blocker 1 wiring added 18 lines above the allowlisted parenthetical in agents/gsd-roadmapper.md, moving it 624 -> 642. Both halves of the gate then fired: the moved line reads as a new offender, and the stale entry no longer matches anything. Line content at 642 is byte-identical to what the entry describes — a descriptive "e.g." naming SDK queries a user could run — so this is a renumber, not a re-classification. Swept the defect class rather than the instance: agents/gsd-roadmapper.md is the only line-pinned reference to any file this round changed. Negative-controlled: both assertions fail against the un-renumbered allowlist. --------- Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
783 lines
32 KiB
JavaScript
783 lines
32 KiB
JavaScript
/**
|
|
* GSD plugin for OpenCode.ai (CommonJS)
|
|
*
|
|
* Architecture: SUBPROCESS REUSE. Instead of re-implementing hook logic inside
|
|
* the plugin, this file is a thin adapter that spawns the existing Claude Code
|
|
* hook scripts under hooks/ as child processes. The hooks speak a stable
|
|
* protocol (JSON on stdin, JSON + exit code on stdout); this adapter:
|
|
* 1. Translates OpenCode plugin events into Claude Code hook payloads
|
|
* 2. Spawns `node <HOOKS_DIR>/<hook>.js` with the payload on stdin
|
|
* 3. Translates hook output back into OpenCode semantics
|
|
* - block → throw Error (OpenCode returns the error to the model)
|
|
* - advisory → output.metadata + console.error (best-effort surfacing)
|
|
*
|
|
* Namespace conversion (/gsd:xxx → /gsd-xxx) reuses scripts/fix-slash-commands.cjs
|
|
* via require(), keeping the single source of truth.
|
|
*
|
|
* ── Two distribution shapes, one adapter (issue #1914) ─────────────────────
|
|
* This single file serves both distribution paths, distinguished at load time
|
|
* by REPO_ROOT (path.resolve(__dirname, "../..")):
|
|
*
|
|
* • Option 1 — file copy (the supported GSD path). `bin/install.js` copies
|
|
* this file to <opencodeConfigDir>/plugins/gsd-core.js, so REPO_ROOT is the
|
|
* OpenCode config dir. GSD's own install already stages `hooks/*.js` and
|
|
* `gsd-core/` there (ADR-857 skips hook *registration* for OpenCode, not the
|
|
* file copy), so the hook bridge and content rewriting resolve natively.
|
|
* Commands/agents/skills are ALREADY registered by GSD's native file copy in
|
|
* this mode, so the plugin's own config-hook registration is redundant and is
|
|
* SKIPPED (see IS_PACKAGE_TREE) to avoid double-registration.
|
|
*
|
|
* • Option 2 — package / git-spec. When loaded from the package tree (npm
|
|
* `main`, or an OpenCode git-spec install), REPO_ROOT is the package root and
|
|
* the source layout (commands/gsd/, agents/, skills/) is present. Here the
|
|
* plugin IS the sole registrar, so it registers commands/agents/skills too.
|
|
*
|
|
* IS_PACKAGE_TREE keys off the presence of the SOURCE command layout
|
|
* (commands/gsd/), which only exists in the package tree — never in an installed
|
|
* config dir (that uses the flattened command/ layout). The hook bridge and
|
|
* Read-time content rewriting run in BOTH modes; only the config-hook
|
|
* registration of commands/agents/skills is gated.
|
|
*
|
|
* Runtime-specific hooks are deliberately excluded:
|
|
* - gsd-statusline.js / gsd-update-banner.js (Claude Code statusline)
|
|
* - gsd-cursor-*.js (Cursor-specific)
|
|
* - *.sh scripts (invoked directly by commands/agents, not hook events)
|
|
*/
|
|
|
|
"use strict";
|
|
|
|
const path = require("path");
|
|
const fs = require("fs");
|
|
const os = require("os");
|
|
const { spawnSync } = require("child_process");
|
|
|
|
// Resolve REPO_ROOT to the directory that actually holds the GSD payload
|
|
// (hooks/ + gsd-core/). This must work across three physical layouts because a
|
|
// single adapter file serves both distribution shapes (see header):
|
|
// • package/git-spec tree: <root>/.opencode/plugins/gsd-core.js → <root>
|
|
// • global file-copy: ~/.config/opencode/plugins/gsd-core.js → ~/.config/opencode
|
|
// • local file-copy: <proj>/.opencode/plugins/gsd-core.js → <proj>/.opencode
|
|
// A fixed "../.." only works for the first; the copied layouts sit one level
|
|
// shallower. Walking up to the first ancestor containing BOTH payload markers
|
|
// resolves all three deterministically. Falls back to the package-tree
|
|
// assumption ("../..") if no ancestor matches (keeps graceful degradation).
|
|
function resolveRepoRoot(startDir) {
|
|
let dir = startDir;
|
|
for (let i = 0; i < 6; i++) {
|
|
if (
|
|
fs.existsSync(path.join(dir, "hooks")) &&
|
|
fs.existsSync(path.join(dir, "gsd-core"))
|
|
) {
|
|
return dir;
|
|
}
|
|
const parent = path.dirname(dir);
|
|
if (parent === dir) break; // filesystem root
|
|
dir = parent;
|
|
}
|
|
// No ancestor carried both markers (broken/partial layout — the plugin can't
|
|
// function regardless). Fall back to the package-tree assumption ("../.."),
|
|
// matching the historical fixed-depth behavior and the .opencode/plugins/
|
|
// source layout.
|
|
return path.resolve(startDir, "../..");
|
|
}
|
|
|
|
// CJS: __dirname is a global, no need to derive from import.meta.url
|
|
const REPO_ROOT = resolveRepoRoot(__dirname);
|
|
const HOOKS_DIR = path.join(REPO_ROOT, "hooks");
|
|
const COMMANDS = path.join(REPO_ROOT, "commands", "gsd");
|
|
const AGENTS = path.join(REPO_ROOT, "agents");
|
|
const SKILLS = path.join(REPO_ROOT, "skills");
|
|
const GSD_CORE = path.join(REPO_ROOT, "gsd-core");
|
|
|
|
// True only when loaded from the package/source tree (Option 2), detected by the
|
|
// presence of the SOURCE command layout (commands/gsd/). In an installed OpenCode
|
|
// config dir (Option 1) this directory is absent — the flattened command/ layout
|
|
// is used instead — so the plugin skips its own command/agent/skill registration
|
|
// and lets GSD's native file copy own that surface (avoids double-registration).
|
|
const IS_PACKAGE_TREE = fs.existsSync(COMMANDS);
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Namespace conversion — reuse the single source of truth
|
|
// ---------------------------------------------------------------------------
|
|
|
|
let _cmdNames = null;
|
|
let _transformFn = null;
|
|
|
|
/**
|
|
* Lazily load scripts/fix-slash-commands.cjs and cache the transform function
|
|
* + command name list. Returns null if the module is unavailable (the plugin
|
|
* still works, just without namespace conversion).
|
|
*/
|
|
function getNamespaceConverter() {
|
|
if (_transformFn) return _transformFn;
|
|
try {
|
|
const mod = require(
|
|
path.join(REPO_ROOT, "scripts", "fix-slash-commands.cjs"),
|
|
);
|
|
_cmdNames = mod.readCmdNames();
|
|
_transformFn = mod.transformContentToHyphen;
|
|
return _transformFn;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Session state — tracked across plugin hook invocations
|
|
// ---------------------------------------------------------------------------
|
|
|
|
let currentSessionId = null;
|
|
let currentCwd = process.cwd();
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tool name / argument mapping (OpenCode ↔ Claude Code)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const TOOL_NAME_MAP = {
|
|
read: "Read",
|
|
write: "Write",
|
|
edit: "Edit",
|
|
apply_patch: "MultiEdit",
|
|
multi_edit: "MultiEdit",
|
|
bash: "Bash",
|
|
webfetch: "WebFetch",
|
|
web_search: "WebSearch",
|
|
websearch: "WebSearch",
|
|
task: "Task",
|
|
subagent: "Task",
|
|
};
|
|
|
|
function mapToolName(tool) {
|
|
if (!tool) return "";
|
|
return TOOL_NAME_MAP[String(tool).toLowerCase()] || tool;
|
|
}
|
|
|
|
// Build a Claude-style `tool_input` object from OpenCode's `output.args`.
|
|
function mapToolInput(args) {
|
|
const input = {};
|
|
if (!args || typeof args !== "object") return input;
|
|
|
|
// File-path keys (OpenCode uses filePath/path; Claude uses file_path)
|
|
const filePath = args.filePath || args.path || args.file_path;
|
|
if (filePath) input.file_path = filePath;
|
|
|
|
// Content for Write
|
|
if (args.content !== undefined) input.content = args.content;
|
|
|
|
// Edit patch fields
|
|
if (args.new_string !== undefined) input.new_string = args.new_string;
|
|
if (args.newString !== undefined) input.new_string = args.newString;
|
|
if (args.old_string !== undefined) input.old_string = args.old_string;
|
|
if (args.oldString !== undefined) input.old_string = args.oldString;
|
|
|
|
// Bash command
|
|
if (args.command !== undefined) input.command = args.command;
|
|
|
|
// Web
|
|
if (args.url !== undefined) input.url = args.url;
|
|
if (args.query !== undefined) input.query = args.query;
|
|
|
|
return input;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Hook subprocess runner
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Spawn a Claude Code hook script and pipe a JSON payload to its stdin.
|
|
*
|
|
* Hooks follow the convention:
|
|
* - stdout: JSON object (decision/advisory) or empty
|
|
* - exit 0: allow (with optional advisory JSON on stdout)
|
|
* - exit 2: block (Claude convention; reason in stdout JSON)
|
|
* - any error: exit 0 silently (hooks swallow their own errors)
|
|
*
|
|
* @param {string} hookFile filename under hooks/, e.g. "gsd-prompt-guard.js"
|
|
* @param {object} payload stdin JSON (hook_event_name, tool_name, ...)
|
|
* @param {object} [opts]
|
|
* @param {number} [opts.timeout=8000] spawn timeout in ms
|
|
* @param {string} [opts.cwd] working directory for the child
|
|
* @returns {{ stdout: string, exitCode: number, timedOut: boolean }}
|
|
*/
|
|
const warnedMissingHooks = new Set();
|
|
|
|
function runHook(hookFile, payload, opts = {}) {
|
|
const hookPath = path.join(HOOKS_DIR, hookFile);
|
|
if (!fs.existsSync(hookPath)) {
|
|
// A missing guard script means the guard is silently NOT enforced — the
|
|
// exact failure mode of #2305 (plugin staged, hooks bundle not). Never
|
|
// break the tool call (the adapter's design contract), but never be
|
|
// silent about it either: warn loudly, once per hook file.
|
|
if (!warnedMissingHooks.has(hookFile)) {
|
|
warnedMissingHooks.add(hookFile);
|
|
console.error(
|
|
`[gsd-core] hook script missing: ${hookPath} — ${hookFile} is NOT ` +
|
|
"enforced. The GSD install may be incomplete; reinstall (or run " +
|
|
"/gsd-update) to restage the hooks/ bundle.",
|
|
);
|
|
}
|
|
return { stdout: "", exitCode: 0, timedOut: false };
|
|
}
|
|
const timeout = opts.timeout ?? 8000;
|
|
let result;
|
|
try {
|
|
result = spawnSync(process.execPath, [hookPath], {
|
|
input: JSON.stringify(payload),
|
|
encoding: "utf8",
|
|
timeout,
|
|
cwd: opts.cwd || currentCwd,
|
|
windowsHide: true,
|
|
});
|
|
} catch {
|
|
// Spawn failure — never break the tool call
|
|
return { stdout: "", exitCode: 0, timedOut: false };
|
|
}
|
|
|
|
const stdout = (result.stdout || "").trim();
|
|
const exitCode = result.status == null ? 0 : result.status;
|
|
return { stdout, exitCode, timedOut: result.signal === "SIGTERM" };
|
|
}
|
|
|
|
/**
|
|
* In-process check for whether context-usage warnings are disabled in project
|
|
* config. Mirrors the exact semantics of the same check inside
|
|
* hooks/gsd-context-monitor.js (introduced by #1073): an explicit
|
|
* `config.hooks.context_warnings === false` disables them; a missing or
|
|
* unparseable .planning/config.json keeps them enabled (the default).
|
|
*
|
|
* #2697: hoisting this check in-process lets the adapter SKIP the context-monitor
|
|
* spawn entirely when the user has opted out, instead of paying a full Node boot
|
|
* inside the child only to read the boolean and exit. Missing/unparseable config
|
|
* MUST behave identically to the hook (enabled) so the default path is unchanged.
|
|
*
|
|
* @param {string} cwd project working directory (the plugin's currentCwd)
|
|
* @returns {boolean} true when context warnings are explicitly disabled
|
|
*/
|
|
function contextWarningsDisabled(cwd) {
|
|
try {
|
|
const configPath = path.join(cwd, '.planning', 'config.json');
|
|
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
return config.hooks?.context_warnings === false;
|
|
} catch {
|
|
// Missing or unparseable config → proceed with defaults (context warnings enabled).
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Hook output translation → OpenCode semantics
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Parse a hook's stdout and apply its effect to the OpenCode output object.
|
|
*
|
|
* - Block → throw Error(parsed.reason) so OpenCode aborts the tool call
|
|
* - Advisory→ append to output.metadata._gsdAdvisory[] and log to stderr
|
|
* - Silent → no-op
|
|
*
|
|
* @param {{ stdout: string, exitCode: number }} hookResult
|
|
* @param {object} [output] OpenCode mutable output object (optional)
|
|
*/
|
|
function handleHookResult(hookResult, output) {
|
|
const { stdout, exitCode } = hookResult;
|
|
if (!stdout && exitCode !== 2) return; // silent allow
|
|
|
|
let parsed = null;
|
|
if (stdout) {
|
|
try {
|
|
parsed = JSON.parse(stdout);
|
|
} catch {
|
|
// Non-JSON stdout (e.g. a stray log) — treat exit 2 as hard block, else allow
|
|
}
|
|
}
|
|
|
|
// Block: explicit decision OR Claude exit-code-2 convention
|
|
const isBlock = exitCode === 2 || (parsed && parsed.decision === "block");
|
|
if (isBlock) {
|
|
const reason =
|
|
(parsed && parsed.reason) || "Blocked by GSD hook (no reason provided).";
|
|
throw new Error(reason);
|
|
}
|
|
|
|
// Advisory: inject additionalContext into metadata + log
|
|
const advisory =
|
|
parsed &&
|
|
parsed.hookSpecificOutput &&
|
|
parsed.hookSpecificOutput.additionalContext;
|
|
if (advisory) {
|
|
if (output) {
|
|
output.metadata = output.metadata || {};
|
|
// Accumulate: a single tool call can run several advisory hooks in
|
|
// sequence (prompt guard, read guard, worktree guard, workflow guard).
|
|
// Storing a scalar would let a later advisory clobber an earlier one, so
|
|
// collect them all.
|
|
if (!Array.isArray(output.metadata._gsdAdvisory)) {
|
|
output.metadata._gsdAdvisory = [];
|
|
}
|
|
output.metadata._gsdAdvisory.push(advisory);
|
|
}
|
|
// Best-effort visibility when metadata isn't surfaced to the model
|
|
console.error(advisory);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Frontmatter helpers (for config registration)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function parseFrontmatter(content) {
|
|
const m = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
|
if (!m) return { frontmatter: {}, body: content };
|
|
const fm = {};
|
|
for (const line of m[1].split("\n")) {
|
|
const i = line.indexOf(":");
|
|
if (i > 0) {
|
|
let v = line.slice(i + 1).trim();
|
|
if (v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1);
|
|
fm[line.slice(0, i).trim()] = v;
|
|
}
|
|
}
|
|
return { frontmatter: fm, body: m[2] };
|
|
}
|
|
|
|
// Rewrite @~/.claude/ includes to point at the repo root.
|
|
// Also applies /gsd:xxx → /gsd-xxx namespace conversion via the shared
|
|
// transform from scripts/fix-slash-commands.cjs (single source of truth).
|
|
function rewriteRefs(content) {
|
|
let out = content.replace(/@~\/\.claude\//g, `@${REPO_ROOT}/`);
|
|
const transform = getNamespaceConverter();
|
|
if (transform && _cmdNames && _cmdNames.length) {
|
|
out = transform(out, _cmdNames);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function loadDir(dir, keyFn, valFn) {
|
|
const result = {};
|
|
if (!fs.existsSync(dir)) return result;
|
|
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".md"))) {
|
|
const raw = fs.readFileSync(path.join(dir, f), "utf8");
|
|
const { frontmatter, body } = parseFrontmatter(raw);
|
|
result[keyFn(f)] = valFn(body, frontmatter, f);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Runtime content transform — for Read tool results on GSD-managed files
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Directories whose .md files may contain ~/.claude/ paths and gsd: namespace
|
|
// refs. When the model reads these via the Read tool, we transparently rewrite
|
|
// both so OpenCode sees correct paths and hyphen-form command names.
|
|
const GSD_MANAGED_DIRS = [
|
|
path.join(GSD_CORE, "workflows"),
|
|
path.join(GSD_CORE, "references"),
|
|
path.join(GSD_CORE, "templates"),
|
|
path.join(GSD_CORE, "contexts"),
|
|
COMMANDS,
|
|
AGENTS,
|
|
SKILLS,
|
|
];
|
|
|
|
function isGsdManagedFile(filePath) {
|
|
if (!filePath) return false;
|
|
const resolved = path.resolve(filePath);
|
|
return GSD_MANAGED_DIRS.some(
|
|
(dir) => resolved === dir || resolved.startsWith(dir + path.sep),
|
|
);
|
|
}
|
|
|
|
// Rewrite content for OpenCode consumption:
|
|
// 1. @-include paths: @~/.claude/ → @<REPO_ROOT>/
|
|
// 2. plain-text paths: ~/.claude/gsd-core/ → <GSD_CORE>/
|
|
// 3. namespace: gsd:xxx → gsd-xxx (via fix-slash-commands.cjs)
|
|
function rewriteContent(content) {
|
|
let out = content;
|
|
out = out.replace(/@~\/\.claude\//g, `@${REPO_ROOT}/`);
|
|
out = out.replace(/~\/\.claude\/gsd-core\//g, `${GSD_CORE}/`);
|
|
const transform = getNamespaceConverter();
|
|
if (transform && _cmdNames && _cmdNames.length) {
|
|
out = transform(out, _cmdNames);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Skills cache — copy SKILL.md files with rewritten @-include paths
|
|
// ---------------------------------------------------------------------------
|
|
//
|
|
// OpenCode's skill loader reads SKILL.md files directly from disk and resolves
|
|
// @-includes internally — this bypasses our tool.execute hooks. To make
|
|
// @~/.claude/gsd-core/... includes resolve, we copy all SKILL.md files to a
|
|
// cache directory with paths rewritten to the actual GSD_CORE location.
|
|
//
|
|
// Only used in package-tree mode (Option 2). In an installed OpenCode config
|
|
// dir (Option 1) skills are already staged + registered by GSD's native file
|
|
// copy, so we never register skills from the plugin (see IS_PACKAGE_TREE).
|
|
|
|
const SKILLS_CACHE = path.join(
|
|
os.homedir(),
|
|
".cache",
|
|
"opencode",
|
|
"gsd-skills",
|
|
);
|
|
|
|
function prepareSkillsCache() {
|
|
if (!fs.existsSync(SKILLS)) return null;
|
|
fs.mkdirSync(SKILLS_CACHE, { recursive: true });
|
|
for (const dir of fs.readdirSync(SKILLS)) {
|
|
const srcFile = path.join(SKILLS, dir, "SKILL.md");
|
|
if (!fs.existsSync(srcFile)) continue;
|
|
const raw = fs.readFileSync(srcFile, "utf8");
|
|
// Rewrite @-include paths only; namespace conversion is handled at
|
|
// Read-time via tool.execute.after for workflow/reference files.
|
|
const rewritten = raw
|
|
.replace(/@~\/\.claude\/gsd-core\//g, `@${GSD_CORE}/`)
|
|
.replace(/~\/\.claude\/gsd-core\//g, `${GSD_CORE}/`);
|
|
const destDir = path.join(SKILLS_CACHE, dir);
|
|
fs.mkdirSync(destDir, { recursive: true });
|
|
fs.writeFileSync(path.join(destDir, "SKILL.md"), rewritten);
|
|
}
|
|
return SKILLS_CACHE;
|
|
}
|
|
|
|
// ===========================================================================
|
|
// Plugin entry
|
|
// ===========================================================================
|
|
|
|
const GsdCorePlugin = async ({ directory } = {}) => {
|
|
if (directory) currentCwd = directory;
|
|
|
|
return {
|
|
// ── Config: register commands / agents / skills paths ──────────────
|
|
// Only in package-tree mode (Option 2). In an installed config dir
|
|
// (Option 1) GSD's native file copy already registered these, so the
|
|
// plugin stays out of registration to avoid double-registering.
|
|
config: async (config) => {
|
|
if (!IS_PACKAGE_TREE) return;
|
|
|
|
// Commands (commands/gsd/*.md → gsd-<name>)
|
|
config.command = config.command || {};
|
|
const cmds = loadDir(
|
|
COMMANDS,
|
|
(f) => "gsd-" + f.slice(0, -3),
|
|
(body, fm, name) => ({
|
|
template: rewriteRefs(body.trim()),
|
|
description: fm.description || `GSD ${name.slice(0, -3)} command`,
|
|
}),
|
|
);
|
|
for (const [k, v] of Object.entries(cmds)) {
|
|
if (!config.command[k]) config.command[k] = v;
|
|
}
|
|
|
|
// Agents (agents/*.md)
|
|
config.agent = config.agent || {};
|
|
const agents = loadDir(
|
|
AGENTS,
|
|
(f) => f.slice(0, -3),
|
|
(body, fm, name) => ({
|
|
prompt: rewriteRefs(body.trim()),
|
|
description: fm.description || `GSD ${name.slice(0, -3)} agent`,
|
|
mode: fm.mode || "subagent",
|
|
}),
|
|
);
|
|
for (const [k, v] of Object.entries(agents)) {
|
|
if (!config.agent[k]) config.agent[k] = v;
|
|
}
|
|
|
|
// Skills — copy SKILL.md files to cache with rewritten @-include paths,
|
|
// then register the cache directory. OpenCode's skill loader reads
|
|
// SKILL.md from disk and resolves @-includes internally (bypassing our
|
|
// tool.execute hooks), so we must pre-process the files.
|
|
const skillsCache = prepareSkillsCache();
|
|
config.skills = config.skills || {};
|
|
config.skills.paths = config.skills.paths || [];
|
|
const skillsPath = skillsCache || SKILLS;
|
|
if (!config.skills.paths.includes(skillsPath)) {
|
|
config.skills.paths.push(skillsPath);
|
|
}
|
|
},
|
|
|
|
// ── shell.env ───────────────────────────────────────────────────────
|
|
"shell.env": async (_input, output) => {
|
|
output.env = output.env || {};
|
|
output.env.GSD_DIR = GSD_CORE;
|
|
},
|
|
|
|
// ── tool.execute.before — PreToolUse hooks ─────────────────────────
|
|
"tool.execute.before": async (input, output) => {
|
|
const claudeTool = mapToolName(input.tool);
|
|
const toolInput = mapToolInput(output.args || {});
|
|
const cwd = currentCwd;
|
|
|
|
// 0. Read path rewrite — redirect ~/.claude/gsd-core/ to actual GSD_CORE
|
|
// so the model can read workflow/reference/template files that SKILL.md
|
|
// and command templates reference via the canonical Claude path.
|
|
if (claudeTool === "Read" && toolInput.file_path) {
|
|
const original = toolInput.file_path;
|
|
const rewritten = original
|
|
.replace(/^~\/\.claude\/gsd-core\//, GSD_CORE + "/")
|
|
.replace(/(?:.*)\/\.claude\/gsd-core\//, GSD_CORE + "/");
|
|
if (rewritten !== original) {
|
|
const args = output.args || {};
|
|
if (args.filePath) args.filePath = rewritten;
|
|
else if (args.path) args.path = rewritten;
|
|
else if (args.file_path) args.file_path = rewritten;
|
|
else args.filePath = rewritten;
|
|
}
|
|
}
|
|
|
|
const basePayload = {
|
|
hook_event_name: "PreToolUse",
|
|
cwd,
|
|
};
|
|
// NOTE: session_id intentionally omitted for PreToolUse hooks.
|
|
// gsd-read-guard.js treats a non-empty session_id as a Claude Code
|
|
// session and skips its advisory. On OpenCode we WANT the advisory.
|
|
const prePayload = (overrides = {}) => ({
|
|
...basePayload,
|
|
tool_name: claudeTool,
|
|
tool_input: toolInput,
|
|
...overrides,
|
|
});
|
|
|
|
const isWriteLike = ["Write", "Edit", "MultiEdit"].includes(claudeTool);
|
|
|
|
// 1. gsd-prompt-guard.js — injection scan on .planning/ writes
|
|
if (claudeTool === "Write" || claudeTool === "Edit") {
|
|
const r = runHook("gsd-prompt-guard.js", prePayload());
|
|
handleHookResult(r, output);
|
|
}
|
|
|
|
// 2. gsd-read-guard.js — read-before-edit advisory
|
|
if (claudeTool === "Write" || claudeTool === "Edit") {
|
|
const r = runHook("gsd-read-guard.js", prePayload());
|
|
handleHookResult(r, output);
|
|
}
|
|
|
|
// 3. gsd-worktree-path-guard.js — hard-block edits outside worktree
|
|
if (isWriteLike) {
|
|
const r = runHook("gsd-worktree-path-guard.js", prePayload());
|
|
handleHookResult(r, output);
|
|
}
|
|
|
|
// 4. gsd-write-guard.js — hard-block catastrophic shrink of curated
|
|
// .planning/ artifacts (ROADMAP.md, milestones/*-ROADMAP.md, STATE.md)
|
|
if (claudeTool === "Write") {
|
|
const r = runHook("gsd-write-guard.js", prePayload());
|
|
handleHookResult(r, output);
|
|
}
|
|
|
|
// 5. gsd-workflow-guard.js — workflow advisory + git-force-add block
|
|
// (covers Write/Edit/MultiEdit AND Bash force-add detection)
|
|
if (isWriteLike || claudeTool === "Bash") {
|
|
const r = runHook("gsd-workflow-guard.js", prePayload());
|
|
handleHookResult(r, output);
|
|
}
|
|
},
|
|
|
|
// ── tool.execute.after — PostToolUse hooks ─────────────────────────
|
|
"tool.execute.after": async (input, output) => {
|
|
const claudeTool = mapToolName(input.tool);
|
|
// NOTE: In the `after` hook, `args` lives on `input` (not `output`).
|
|
// The `output` object only has { title, output, metadata }.
|
|
const toolInput = mapToolInput(input.args || {});
|
|
const cwd = currentCwd;
|
|
|
|
// GSD content transform — rewrite paths + namespace in Read results
|
|
// BEFORE injection scanning so the scanner sees the final content.
|
|
if (
|
|
claudeTool === "Read" &&
|
|
output.output &&
|
|
isGsdManagedFile(toolInput.file_path)
|
|
) {
|
|
const content =
|
|
typeof output.output === "string"
|
|
? output.output
|
|
: String(output.output);
|
|
output.output = rewriteContent(content);
|
|
}
|
|
|
|
// gsd-read-injection-scanner.js — scan Read/WebFetch/WebSearch results
|
|
if (
|
|
claudeTool === "Read" ||
|
|
claudeTool === "WebFetch" ||
|
|
claudeTool === "WebSearch"
|
|
) {
|
|
const payload = {
|
|
hook_event_name: "PostToolUse",
|
|
tool_name: claudeTool,
|
|
tool_input: toolInput,
|
|
tool_response: output.output,
|
|
cwd,
|
|
};
|
|
const r = runHook("gsd-read-injection-scanner.js", payload);
|
|
handleHookResult(r, output);
|
|
return;
|
|
}
|
|
|
|
// gsd-context-monitor.js — context usage warnings (Bash/Edit/Write/Task/...)
|
|
// Only meaningful when a session_id is tracked (writes metrics sentinel).
|
|
// #2697: skip the subprocess spawn entirely when context warnings are
|
|
// explicitly disabled in project config — the hook would exit early anyway,
|
|
// so hoisting the check in-process avoids paying a Node boot per tool call.
|
|
// Missing/unparseable config = enabled (default), so the spawn still runs.
|
|
if (currentSessionId && !contextWarningsDisabled(cwd)) {
|
|
const payload = {
|
|
hook_event_name: "PostToolUse",
|
|
tool_name: claudeTool,
|
|
tool_input: toolInput,
|
|
session_id: currentSessionId,
|
|
cwd,
|
|
};
|
|
const r = runHook("gsd-context-monitor.js", payload);
|
|
handleHookResult(r, output);
|
|
}
|
|
},
|
|
|
|
// ── experimental.session.compacting — PreCompact ───────────────────
|
|
"experimental.session.compacting": async (_input, output) => {
|
|
if (!currentSessionId) return;
|
|
const payload = {
|
|
hook_event_name: "PreCompact",
|
|
session_id: currentSessionId,
|
|
cwd: currentCwd,
|
|
};
|
|
const r = runHook("gsd-context-monitor.js", payload);
|
|
handleHookResult(r, output);
|
|
|
|
// Also inject a GSD compaction breadcrumb (mirrors the original plugin)
|
|
output.context = output.context || [];
|
|
output.context.push(
|
|
`[GSD] Active session: ${currentSessionId}. Preserve any in-flight phase/plan state.`,
|
|
);
|
|
},
|
|
|
|
// ── General event subscriptions ─────────────────────────────────────
|
|
event: async ({ event }) => {
|
|
// session.created → SessionStart hooks
|
|
if (event.type === "session.created") {
|
|
// Track session for context-monitor payloads.
|
|
// SDK type EventSessionCreated: { properties: { info: Session } }
|
|
// Session has `id` and `directory` (not `cwd`).
|
|
const info = event.properties?.info;
|
|
currentSessionId =
|
|
info?.id || event.sessionID || event.session_id || null;
|
|
if (info?.directory) currentCwd = info.directory;
|
|
|
|
// gsd-ensure-canonical-path.js — no stdin dependency; silent
|
|
runHook("gsd-ensure-canonical-path.js", {
|
|
hook_event_name: "SessionStart",
|
|
session_id: currentSessionId,
|
|
cwd: currentCwd,
|
|
});
|
|
// gsd-check-update.js — spawns its own background worker; no stdin
|
|
runHook("gsd-check-update.js", {
|
|
hook_event_name: "SessionStart",
|
|
session_id: currentSessionId,
|
|
cwd: currentCwd,
|
|
});
|
|
return;
|
|
}
|
|
|
|
// file.edited → FileChanged hook (config.json reload)
|
|
if (event.type === "file.edited") {
|
|
// SDK type EventFileEdited: { properties: { file: string } }
|
|
const filePath = event.properties?.file || event.filePath || "";
|
|
if (!filePath.endsWith("config.json")) return;
|
|
const cwd = event.properties?.cwd || currentCwd;
|
|
const expected = path.join(cwd, ".planning", "config.json");
|
|
if (path.resolve(filePath) !== path.resolve(expected)) return;
|
|
|
|
const payload = {
|
|
hook_event_name: "FileChanged",
|
|
file_path: filePath,
|
|
event: "change",
|
|
cwd,
|
|
};
|
|
const r = runHook("gsd-config-reload.js", payload);
|
|
// Advisory-only (additionalContext); surface to logs
|
|
handleHookResult(r);
|
|
return;
|
|
}
|
|
|
|
// session.idle ↔ Claude Stop lifecycle point (#1682 Slice 1b/c).
|
|
// OpenCode fires session.idle when the run quiesces. GSD maps it to the
|
|
// Stop equivalent — the opencode-subset lifecycle peer of compaction
|
|
// (compaction preserves state across context-window summarization; idle
|
|
// marks end-of-turn). No-op sentinel today (GSD state is already
|
|
// persisted to .planning/), but it MUST be recognized so the declared
|
|
// opencode-subset surface is fully wired and a future Stop-class hook can
|
|
// attach without a plugin change.
|
|
if (event.type === "session.idle") {
|
|
return;
|
|
}
|
|
|
|
// permission.asked / permission.replied — OpenCode permission lifecycle
|
|
// (#2087, opencode.ai/docs/plugins). GSD gates tool INPUTS at
|
|
// tool.execute.before (read-guard, injection-scanner); the permission
|
|
// grant/deny decision itself carries no GSD workflow-phase contribution,
|
|
// so these are recognized sentinels — wired so a future permission-aware
|
|
// gate can attach without a plugin change (the engine owns phase
|
|
// sequencing; this host bus is session/tool/permission-scoped, never
|
|
// phase-scoped — ADR-1239 §OpenCode).
|
|
if (event.type === "permission.asked" || event.type === "permission.replied") {
|
|
return;
|
|
}
|
|
|
|
// session.error — OpenCode session-error lifecycle point (#2087). No GSD
|
|
// hook fires here today (loop state is already persisted to .planning/);
|
|
// recognized so the declared extension-event surface is fully wired and a
|
|
// future error-class hook can attach without a plugin change.
|
|
if (event.type === "session.error") {
|
|
return;
|
|
}
|
|
},
|
|
};
|
|
};
|
|
|
|
// Export shape — verified against OpenCode's plugin loader source
|
|
// (packages/opencode/src/plugin). The loader imports this module and runs
|
|
// `for (const entry of Object.values(mod)) { getServerPlugin(entry) }`, where
|
|
// `getServerPlugin` accepts a bare function OR an object exposing a `.server`
|
|
// function, and THROWS `TypeError("Plugin export is not a function")` for
|
|
// anything else. So EVERY enumerable value the loader iterates must be a
|
|
// function or an object with `.server`.
|
|
//
|
|
// The subtlety: depending on how OpenCode's runtime (Node or Bun) imports a
|
|
// CommonJS file, `mod` may be the raw `module.exports` OR an ESM namespace of
|
|
// the form `{ default: module.exports, ...syntheticNamedExports }`. A plain
|
|
// `module.exports = { id: "gsd-core", server }` literal risks a string `id`
|
|
// appearing in `Object.values(mod)` (as a raw property, or as a lexer-
|
|
// synthesized named export) — which would trip the throw. Two defenses:
|
|
// 1. `id` is defined NON-ENUMERABLE, so it never appears in Object.values yet
|
|
// stays readable (via property access) for the loader's identity/dedup.
|
|
// 2. `module.exports` is assigned from a VARIABLE (not an object literal), so
|
|
// cjs-module-lexer cannot statically synthesize named exports from it —
|
|
// only `default` is exposed under ESM/Bun interop.
|
|
// Result: raw-CJS `Object.values` = `[server]`; ESM `Object.values` =
|
|
// `[{server, <id non-enum>}]` — both fully extractable. Test-only helpers hang
|
|
// off the `server` FUNCTION (`server._internals`), never as a sibling export.
|
|
GsdCorePlugin._internals = {
|
|
REPO_ROOT,
|
|
IS_PACKAGE_TREE,
|
|
mapToolName,
|
|
mapToolInput,
|
|
parseFrontmatter,
|
|
rewriteContent,
|
|
isGsdManagedFile,
|
|
handleHookResult,
|
|
GsdCorePlugin,
|
|
};
|
|
|
|
const gsdCorePluginExport = { server: GsdCorePlugin };
|
|
Object.defineProperty(gsdCorePluginExport, "id", {
|
|
value: "gsd-core",
|
|
enumerable: false,
|
|
writable: false,
|
|
configurable: false,
|
|
});
|
|
module.exports = gsdCorePluginExport;
|