agentleFS
WhiteBiteWhiteBite/dejavu-gates/AGENTS.md

dejavu-gates

AGENTS.md16 starsChanged 47 days agoMITView on GitHub

Generated: 2026-08-22 (refreshed 2026-10-01) Commit: 2.49.0 (audit-fix batch 2: URL/one-liner identity, $(...) immunity, escalation lock discipline, index quarantine, errored wiring for V1) Branch: main dejavu — error gates for AI coding agents ("memory prosthesis with teeth"): mechanically detects recurring tool-call failures and promotes them into enforced gates (3 failures across 2 distinct sessions). Remind first, hard-block on same-session repeat offense. One harness-agnostic engine, two host forms: the OpenCode plugin (index.ts, long-lived process), a hook-handler CLI (src/cli.ts, short-lived process per event)…

  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 32,671 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository4 other files it gives its agents.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

19 rules. About 0 are common, 2 are distinctive, and 17 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 17

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    No semicolons, double quotes, explicit return types on everything, node: prefix on builtins

    line 117
  2. Distinctive:

    No linter/formatter config exists — style is maintained by hand, match neighboring code

    line 118
  3. Very specific:

    Do NOT scan read/edit/write output for failure text — it is file CONTENT, not command output (caused false gates).

    line 125
  4. Very specific:

    Do NOT surface a success-shaped line as failure evidence — failureSnippet scans from the end for a failure-shaped line, looksLikeSuccess …

    line 126
  5. Very specific:

    Do NOT quote a success-shaped or bare-exit code snippet in a correction — suggestCorrection falls back to family/generic text.

    line 127
  6. Very specific:

    Do NOT count exit 1 from diagnostic verbs (grep/tsc/pytest/curl/ls...) as failure — intended outcome.

    line 130
  7. Very specific:

    Do NOT flatten interpreter one-liner payloads (python -c, node -e, PowerShell & "...\python.exe" -c @"..."@) to <str> — the code IS the …

    line 131
  8. Very specific:

    Do NOT enforce signatures without residual identity — if normalization parameterized the whole command away (cmd <path> <str>, node <str> …

    line 132
  9. Very specific:

    Do NOT keep cmd /c wrappers in signatures — unwrapCmdWrapper() normalizes the payload so identity and the diagnostic tier see the real verb

    line 133
  10. Very specific:

    Do NOT persist anything before sanitizeForStore() (control-char strip + secret scrub) — signatures, snippets, args, error text, logs.

    line 134
  11. Very specific:

    Do NOT throw from hooks except GateSignal — plugin bugs must never break the tool pipeline

    line 135
  12. Very specific:

    Do NOT let file-probe or diagnostic tools reach blocking status — canBlock() is the single source of truth.

    line 136
  13. Very specific:

    Do NOT add Unix viewers (cat/head/tail/wc/less/more) to DIAGNOSTIC_VERBS — their exit 1 must stay RECORDABLE (a missing file / …

    line 137
  14. Distinctive:

    Do NOT create gates manually — promotion is mechanical (3 failures × 2 sessions)

    line 138
  15. Very specific:

    Do NOT delete quarantine files (gates.json.corrupt-*, log.jsonl.corrupt) without inspection — they are the preserved forensic bytes of …

    line 139
  16. Very specific:

    Do NOT block in the post phase — the call already ran.

    line 141
  17. Very specific:

    Do NOT let adapters throw on malformed payloads — mapInbound returns null (CLI no-ops {} exit 0).

    line 143
  18. Very specific:

    Do NOT make the CLI fail closed — any internal error prints {} and exits 0.

    line 144
  19. Very specific:

    commit-msg hygiene hook: scripts/githooks/commit-msg — header ≤100 chars, no emoji, no AI attribution trailers.

    line 174

≈ “Common” is an estimate: at least 1 in 5 of the 41,581 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

PROJECT KNOWLEDGE BASE

Generated: 2026-08-22 (refreshed 2026-10-01) Commit: 2.49.0 (audit-fix batch 2: URL/one-liner identity, $(...) immunity, escalation lock discipline, index quarantine, errored wiring for V1) Branch: main

OVERVIEW

dejavu — error gates for AI coding agents ("memory prosthesis with teeth"): mechanically detects recurring tool-call failures and promotes them into enforced gates (3 failures across 2 distinct sessions). Remind first, hard-block on same-session repeat offense. One harness-agnostic engine, two host forms: the OpenCode plugin (index.ts, long-lived process), a hook-handler CLI (src/cli.ts, short-lived process per event) with adapters for Claude Code, Codex CLI, Gemini CLI, Cursor, Copilot CLI, Crush, Devin CLI, Kiro, and an in-package Cline plugin host (src/cline-plugin.ts, long-lived sandbox subprocess). TypeScript ESM, runs under Bun, ships as raw .ts (no build step). Repo/npm name: dejavu-gates (formerly opencode-dejavu).

STRUCTURE

dejavu-gates/
├── index.ts            # OpenCode V1 plugin host — exports Dejavu (Plugin factory); glue only
├── src/
│   ├── patterns.ts     # Pure engine: signatures, normalization, secret scrub, detection, blocking policy
│   ├── store.ts        # GateStore/Stores: two-scope persistence, locks, promotion, TTL, migration, reconcile
│   ├── fs.ts           # leaf fs primitives: ntPath (NT long paths) + atomicWrite (tmp+rename, AV backoff) — shared by store and installer
│   ├── validate.ts     # Invariant layer: strict gate parsing + mechanical repair (parse-don't-validate boundary)
│   ├── types.ts        # Cross-harness contract: NormalizedEvent/Verdict/OutboundDecision/HarnessAdapter (types only, zero imports)
│   ├── enforce.ts      # Engine public surface (re-exports) + EnforceContext
│   ├── context.ts      # EphemeralState (+ CLI degradation contract), caps, cross-channel dedup helpers, shared retirement tunables
│   ├── host-init.ts    # host boot lifecycle: initStores (ordered reconcile→migrate→expire + per-host opts), scheduleSweep (jittered TTL), rateLimitedErrorSink
│   ├── before.ts       # enforceBefore — repeat block, guards, remind→block chain under the store lock
│   ├── after.ts        # enforceAfter — failure detection/attribution/recording, reminding NOTE production
│   ├── event.ts        # recordEventFailure + cleanupSession (event channel)
│   ├── guards.ts       # proactive guards (long-running/wait-loop/spawn/orphan-job/snowball) — messages verbatim
│   ├── repeat.ts       # repeat-series before-block (override FALLS THROUGH to gate processing)
│   ├── repeat-channel.ts # transform-channel orchestration (sanitize markers, REPETITION/windowed notes, shape loops, loop-break injection) — engine module, hosts wire it (V1 transform / V2 generate)
│   ├── messages.ts     # remindMessage/remindNote/blockMessage — the teaching texts
│   ├── lesson.ts       # `dejavu lesson` subcommand: list/show/set human corrections on existing gates
│   ├── adapters/       # per-harness payload↔contract mapping: shared.ts + claude/codex/gemini/cursor/copilot/crush/devin/kiro.ts
│   ├── opencode-v2.ts  # OpenCode V2 host glue: v2Setup registers tool/event/compaction/generate hooks on the V2 plugin Context
│   ├── cli.ts          # hook-handler CLI: stdin JSON → engine → stdout decision JSON, exit 0/2/1, fail-open
│   ├── install.ts      # `dejavu install|uninstall|hooks` — idempotent harness-config merging (backup, foreign-hook survival)
│   ├── install-config.ts # per-harness config paths/shapes + dejavu-entry detection (isDejavuCommand/isDejavuHookCommand)
│   └── main.ts         # npm bin entry (`dejavu`/`dejavu-gates`): routes install/report/lesson/hook subcommands
├── test/               # smoke (plugin), enforce (engine), adapters, cli (e2e spawn), store (persistence perf/behavior), language-gaps, property, fuzz, guards, messages, install, v2-host, cline-plugin, env, recurrence, lesson — plain bun scripts
├── scripts/            # doctor.ts, analyze.ts, migrate.ts, install-hooks.ts (shim → src/install.ts) + templates/*.json per harness
├── commands/           # /dejavu slash-command: dejavu.md (OpenCode copy-in + Claude/Cursor plugin discovery) + dejavu.toml (Gemini extension discovery)
├── skills/dejavu/      # Companion agent-protocol skill (install → ~/.config/opencode/skills/)
└── .omo/, .codegraph/  # Tooling artifacts — not project code

WHERE TO LOOK

TaskLocationNotes
Gate enforcement (remind/block/override)src/before.ts + src/after.ts (via src/enforce.ts)hosts only glue: index.ts throws GateSignal on deny verdicts; cli.ts maps verdicts to harness dialects
Failure detection + recordingsrc/after.ts (exit/text) + src/event.ts (event channel)cross-channel dedup guard counts one call once; external harnesses have NO exit codes → text channel only
Harness payload mappingsrc/adapters/<h>.ts + src/adapters/shared.tstool aliases + arg-field normalization feed callSignature — signatures stay harness-neutral so gates travel
Hook config generationsrc/install.ts + src/install-config.ts + scripts/templates/*.jsonidempotent merge, aborts on unparseable config, {{CLI}} placeholder; scripts/install-hooks.ts is a shim
Repeat/loop-break transform channelsrc/repeat-channel.ts (orchestration) + src/patterns.ts (detectRepeatSeries/Windows/ShapeLoops)hosts only register + cast payloads: V1 experimental.chat.messages.transform, V2 generate hook
Host boot (init/sweep/error sink)src/host-init.tsordered reconcile→migrate→expire once; per-host reduction is explicit opts (CLI: no init event/rotate/health)
Signature/normalizationsrc/patterns.tscallSignature, normalizeCommand, parameterizeError
Enforcement policysrc/patterns.ts:canBlock()/canRemind()three tiers — bash non-diagnostics block, diagnostics + Unix viewers remind-only, everything else just watches
Persistence, locks, promotion, global escalationsrc/store.tsStores.recordFailure() is the core; cross-project evidence lives in global index.json
Self-healing / reconcilesrc/store.ts + src/validate.tsStores.reconcileAll() at every init; doctor --repair on demand
Tunablessrc/store.ts, src/context.ts, src/before.ts, src/repeat.ts, src/repeat-channel.ts, src/host-init.tspromote thresholds in store; retirement tunables + caps in context; review/race in before; repeat-block in repeat; channel notes/windows/shape-loop in repeat-channel; TTL/error-sink intervals in host-init
Pathology checksscripts/doctor.tsdefect classes: unparseable/bad records, duplicate keys, temporal inversion, nested tokens, enforced-without-evidence, stale blocking/reminding, not-teaching, annoying, stale-correction, review-flagged, reminders-ignored, unsanitized, stale copies, corrupt logs, version drift, cross-store index checks, flappy, flood evictions, cross-channel double-count, quarantine artifacts, feedback-demoted, overridden, lock degradations; no-arg run discovers projects from the index

CODE MAP

Line numbers intentionally omitted — they rot every round; locate by symbol name.

SymbolTypeLocationRole
DejavuPlugin factoryindex.tsV1 entry of a dual V1/V2 default export; wires 4 hooks
v2Setupfnsrc/opencode-v2.tsOpenCode V2 host: registers execute.before/after (deny via throw), event.subscribe (session.deleted cleanup), compaction, and generate (repeat-channel parity with V1's transform) hooks on the V2 plugin Context; reuses the same engine calls as the V1 host
GateSignalclassindex.tssentinel error — the ONLY error rethrown from hooks
enforceBefore / enforceAfterfnsrc/before.ts / src/after.tsthe engine's two hook entry points; return verdicts/outcomes, never throw GateSignal (hosts translate)
recordEventFailure / cleanupSessionfnsrc/event.tsevent-channel failure recording + session teardown
applyRepeatChannelfnsrc/repeat-channel.tstransform-channel orchestration over structural messages — sanitize markers, REPETITION/windowed/shape notes, loop-break injection; hosts cast payloads and apply injections
initStores / scheduleSweep / rateLimitedErrorSinkfnsrc/host-init.tshost boot: ordered init (per-host opts), jittered TTL sweep with disposer, 60s error-sink rate limit
EnforceContext / EphemeralStateinterface / fnsrc/context.tsinjected host dependencies (stores/log/onHookError/projectDir) + per-process state; createEphemeralState() JSDoc is the CLI degradation contract
NormalizedEvent / Verdict / OutboundDecision / HarnessAdaptertypessrc/types.tsthe cross-harness contract; zero imports, types only
internalTool / internalArgsfnsrc/adapters/shared.tsharness tool-name aliases + arg-field normalization → callSignature vocabulary
ADAPTERS registryconstsrc/cli.tsHarnessName → adapter; CliHarness excludes opencode (plugin host, not CLI)
scrubSecretsfnsrc/patterns.tssecret redaction (half of the persistence boundary)
stripControl / sanitizeForStorefnsrc/patterns.tsC0/ANSI strip; sanitizeForStore = stripControl + scrubSecrets — the persistence boundary
hashInterpreterPayloadfnsrc/patterns.ts-c/-e code payload → <code:hash> (identity of one-liners, incl. PowerShell here-strings + env prefixes)
cmdWrapperPayload / unwrapCmdWrapperfnsrc/patterns.tscmd /c|/k payload extraction; unwrap normalizes the inner command
normalizeCommandfnsrc/patterns.tsbash → signature; strips control chars, unwraps cmd /c, fingerprints one-liner payloads
isIntendedNonzerofnsrc/patterns.tsexit-1 immunity for diagnostic chains (all segments diagnostic; paren groups flattened first)
canBlock / canRemindfnsrc/patterns.tsblocking tier / remind-only tier (diagnostics + iteration verbs + Unix viewers via isUnixViewerSignature)
isRepoLocalfnsrc/patterns.tsrepo-local verbs that never escalate globally
splitChain / bashSegmentSignaturesfnsrc/patterns.tsquote/paren-aware chain split; per-segment signatures, unfolds cmd /c + $(...) + backticks (chain-bypass protection)
producerSegmentSignaturesfnsrc/patterns.tsproducer-only segment signatures for chain attribution — transparent segments (nav/env/inert/pipe-tail) can never absorb a failure
callSignaturefnsrc/patterns.tsstable call identity per tool (bash/read/edit/write/glob/grep)
patternKeyfnsrc/patterns.tssha1 prefix-12 of signature — the gate key
fuzzySimilarfnsrc/patterns.tsnear-duplicate merge; O(1) length-band pre-filter + FUZZY_MAX_LEN cap; strict flag additions with identical base rescue onto an absolute budget (SUBSET_ADD_MAX_DISTANCE)
detectFailure / failureSnippetfnsrc/patterns.tsline-by-line bash-output failure scan / evidence line selection (error-aware tail scan, never a success-shaped line)
looksLikeSuccess / looksLikeFailurefnsrc/patterns.tsevidence-quality classifiers — a pass summary is never failure evidence
isNoiseErrorfnsrc/patterns.tsinfrastructure noise ≠ failure: aborted/cancelled/empty-result/dismissed + server-side unavailability (LSP daemon, MCP transport, non-2xx)
suggestCorrectionfnsrc/patterns.tsmechanical default corrections by command family; never quotes a success-shaped snippet
nonTransparentProducersfnsrc/patterns.tscounts producers AFTER full expansion (cmd /c, $(...)) - consistent with the attribution loop, single-producer rule for chain attribution
hasResidualIdentityfnsrc/patterns.tsover-generic shape guard — gates every enforcement tier (flag-only wrapper shapes have no identity)
GLOBAL_PROJECTSconstsrc/store.tscross-project escalation threshold
GateStoreclasssrc/store.tsone scope: gates.json + index.json + log.jsonl, TTL caches, key index; load() read-only vs loadForMutation() (write-capable, under lock)
mergeGatefnsrc/store.tsevidence merge for dedupe/escalation (rank-preserving, preserves session state + feedback marks)
checkFeedbackDemotionfnsrc/store.tsnegative feedback: recurrences (2+ reoffense sessions) / overrides (2+ bypassing sessions) → watching + feedbackDemoted
retireTaught / retireAntiNagfnsrc/store.tsshared retirement mutations (taught = soft, anti-nag = feedbackDemoted + counter reset); conditions stay tier-explicit at the hook call sites
levenshteinCappedfnsrc/patterns.tsearly-exit edit distance for the fuzzy flood path (same verdicts as full Levenshtein)
Storesclasssrc/store.tstwo-scope manager: findGate/recordFailure/recordSuccess/migrate/expireAll/reconcileAll/forgetSession
recordSuccessmethodsrc/store.tsheal streak + session-chain clearing (exact matches only)
coerceGateShapefnsrc/validate.tsstrict parse of a persisted gate record (hopeless → null)
repairGatefnsrc/validate.tsmechanical repair: inverted dates, truncation, re-sanitize, demote, session-state hygiene
hasNestedTokensfnsrc/validate.tsnested-placeholder corruption fingerprint
atomicWrite / ntPathfnsrc/fs.tsWindows-safe write primitives (tmp+rename, AV backoff, long paths) — shared by store and installer
withLockfnsrc/store.tslockfile with stale-steal, ownership-verified unlock, 3s cross-process degrade
extractOutput / errorSignalled / genericToolOutputfnsrc/adapters/shared.tsone output extractor for all adapters (empty parts skipped); structural failure signal → errored on post events; success-shaped generic results stay out of the text scan

CONVENTIONS

  • ESM ("type": "module") + Bun runtime; scripts run directly (bun scripts/x.ts); no build, no bundling
  • No semicolons, double quotes, explicit return types on everything, node: prefix on builtins
  • No linter/formatter config exists — style is maintained by hand, match neighboring code
  • JSDoc /** */ on exports; inline // comments explain WHY (design rationale), not WHAT — ONE line max; multi-line comment essays are AI slop and get deleted
  • Catch blocks swallow deliberately with a rationale comment; only GateSignal is rethrown
  • Tunables are named UPPER_SNAKE constants grouped under // --- Section --- dividers

ANTI-PATTERNS (THIS PROJECT)

  • Do NOT scan read/edit/write output for failure text — it is file CONTENT, not command output (caused false gates); file-tool failures come exclusively from the event channel
  • Do NOT surface a success-shaped line as failure evidence — failureSnippet scans from the end for a failure-shaped line, looksLikeSuccess rejects pass summaries, and recordFailure never overwrites a failure-shaped snippet with a success-shaped one; a gate that teaches "fix 17 passed" is anti-teaching
  • Do NOT quote a success-shaped or bare-exit code snippet in a correction — suggestCorrection falls back to family/generic text; repairGate re-derives machine template corrections that quoted a success line (human edits never match the fixed template and stay)
  • Do NOT attribute a multi-producer chain failure to a single segment — the exit code does not say which producer failed; nonTransparentProducers must be exactly 1 or the failure records under the whole call (a diagnostic segment's gate must not be inflated by another producer's failure). Attribution iterates ONLY producer segments (producerSegmentSignatures) — a transparent segment's gate (cd/pipe-tail/env) must never absorb the failure even when its key is known
  • Do NOT record noise as failure — isNoiseError() filters it on both channels: aborted/cancelled executions AND server-side unavailability (LSP daemon down, MCP transport, non-2xx) are not agent mistakes; client-side errors (4xx, ENOENT, syntax) stay teachable. Retroactively, migrate() backdates already-recorded noise gates to the epoch so the TTL sweep expires them
  • Do NOT count exit 1 from diagnostic verbs (grep/tsc/pytest/curl/ls...) as failure — intended outcome; exit ≥ 2 always counts (OpenCode normalizes exits to 1, so discriminate by command shape)
  • Do NOT flatten interpreter one-liner payloads (python -c, node -e, PowerShell & "...\python.exe" -c @"..."@) to <str> — the code IS the call; hashInterpreterPayload fingerprints it so distinct scripts never share a gate
  • Do NOT enforce signatures without residual identity — if normalization parameterized the whole command away (cmd <path> <str>, node <str> <n>), it matches a command family; hasResidualIdentity() guards every tier, such shapes may only watch
  • Do NOT keep cmd /c wrappers in signatures — unwrapCmdWrapper() normalizes the payload so identity and the diagnostic tier see the real verb
  • Do NOT persist anything before sanitizeForStore() (control-char strip + secret scrub) — signatures, snippets, args, error text, logs; PowerShell VT colors in persisted text are a bug
  • Do NOT throw from hooks except GateSignal — plugin bugs must never break the tool pipeline
  • Do NOT let file-probe or diagnostic tools reach blocking status — canBlock() is the single source of truth; migrate() auto-demotes violations (diagnostics land in reminding, never blocking)
  • Do NOT add Unix viewers (cat/head/tail/wc/less/more) to DIAGNOSTIC_VERBS — their exit 1 must stay RECORDABLE (a missing file / not-recognized is a real teachable failure, and tail as a terminal producer still counts); their never-block policy lives in isUnixViewerSignature
  • Do NOT create gates manually — promotion is mechanical (3 failures × 2 sessions)
  • Do NOT delete quarantine files (gates.json.corrupt-*, log.jsonl.corrupt) without inspection — they are the preserved forensic bytes of corrupted data
  • Do NOT bypass the validation boundary — gates enter memory through coerceGateShape/repairGate (in load()/loadForMutation()) and structural healing through reconcile(); never hand-roll raw JSON reads/writes of store files. Use loadForMutation() (not a load(true) flag) inside locks — the write capability is in the name (no-load-force-flag ast-grep gate)
  • Do NOT block in the post phase — the call already ran; mapOutbound canonical contract: post checks annotation FIRST (rides on allow, exit 0), only pre denies. An adapter that early-returns on action === "allow" before the annotation branch silently kills the reminding NOTE (the 2.39 pre-release bug)
  • Do NOT write to stdout in the hook paths (engine + src/cli.ts) — the CLI's stdout is the harness's decision-JSON channel; diagnostics go to stderr (DEJAVU_DEBUG-gated in the CLI). Separate bin entries (src/main.ts, src/install.ts, src/lesson.ts) own their process's stdout — they never share a process with the hook channel
  • Do NOT let adapters throw on malformed payloads — mapInbound returns null (CLI no-ops {} exit 0); harness JSON is untrusted external input and must cross sanitizeForStore() via the engine like everything else
  • Do NOT make the CLI fail closed — any internal error prints {} and exits 0; a dejavu bug must never wedge the host's tool pipeline (usage errors exit 1, blocks exit 2)

UNIQUE STYLES

  • Two host forms, one engine: the OpenCode plugin (long-lived process, all channels incl. transform/compacting hooks) and the hook CLI (one short-lived process per hook event; fresh EphemeralState per invocation — repeat-series/pending-calls/dedup-window/iteration-discriminator degrade per-process BY DESIGN, gate enforcement does NOT: the remind→block chain is persisted on the gate). createEphemeralState() JSDoc is the contract
  • The repeat/loop-break channel is engine code (src/repeat-channel.ts), not host code: both OpenCode hosts wire the SAME applyRepeatChannel (V1 via experimental.chat.messages.transform, V2 via the generate hook over a structural payload view) — hosts keep only registration + payload casts + injection application
  • Leaked tool-call recovery (opt-in, DEJAVU_LEAK_RECOVERY): an OpenAI-compatible gateway can leak its tool-call serialization into assistant text as plain text, so no tool_call is produced and every detection channel is blind. Three dialects: the full <|DSL|calls>…</|DSL|calls> block, a stream cut inside the payload, and tool-call tags serialized as text — any <junk@tool …>…</junk@tool> / <junk/tool …> shape carrying a known tool word (attributes included, unknown prefix needs no release). The repeat channel's recoverLeakedToolCall pass (after the loop-break block) detects every dialect (DSL block tail-anchored; fenced examples, quoted spans and inline mentions are left alone), neutralizes the guard-passing blocks in the outgoing payload, and injects a synthetic recovery turn telling the model to re-issue a proper tool call; logs leak-recovery once per session (project log only, like loop-break/shape-loop). No gates, no persistence, no promotion
  • Loop recovery (OpenCode only, opt-in, DEJAVU_LOOP_RECOVERY): a reasoning model can get stuck — lexical spam (one token repeated) or a hedge-heavy deliberation loop that never emits a tool call. src/loop-recovery.ts watches the streaming reasoning on the event channel, runs the pure detectStuckReasoning detector (src/patterns.ts — Unicode letter tokens with CJK syllable splitting, digit exclusion, run-length dominance, exact-duplicate sentences, fence stripping over full text), aborts the session, and injects a corrective user turn via checkLoopRecovery → settleLoopInjection; two consecutive positive checks confirm before the abort (a transient spike arms only), the quota/cooldown/log settle only on a landed abort+prompt (a failed attempt burns nothing and naturally retries), a monotonic per-message length counter (StuckMessageState.total) keeps the throttle live past the 8000-char buffer cap, per-message state is keyed ${sessionID}:${messageID} so session cleanup is complete; capped at 2 landed injections per session with a 30s cooldown, logs loop-recovery once per session (project log only). No gates, no persistence, no promotion
  • Host boot is one helper (src/host-init.ts): initStores encodes the reconcile→migrate→expire order once, per-host reduction is explicit opts (CLI: no init event, no rotate, no health, no drift check), scheduleSweep returns a disposer (V2 disposes; index/cline don't), rateLimitedErrorSink replaces the three 60s copies (the CLI stays unlimited — one process, one call)
  • Iteration evidence counts only LANDED edits: the workspace-version bump is gated on !failed && event.errored !== true — a failed edit/write must never lift the hard-block chain or mark the next failure "iterated"; errored is the host's structural failure signal (adapters: errorSignalled; V2 routes event.error to the event channel instead)
  • Unified cross-harness store: adapters normalize tool names/arg fields BEFORE callSignature, so signatures are harness-neutral — a gate learned in Claude Code fires in OpenCode/Cursor/etc.; all hosts share .opencode/dejavu/ + ~/.config/opencode/dejavu/ (paths are historical, the store is harness-neutral)
  • Two-scope store: project gates in <repo>/.opencode/dejavu/ (committable) escalate to global ~/.config/opencode/dejavu/ after appearing in 2+ project dirs (agent habits vs repo quirks) — except repo-local verbs (npm/git/gradle/docker/...), which are repo quirks by nature and stay project-scoped forever
  • Three enforcement tiers: blocking (remind-abort, then hard-block on same-session repeat), reminding (diagnostics + Unix viewers + tool-error heads with ≥ 3 literal word tokens — annotate the failing output, never interrupt), watching (evidence only); fuzzySimilar never merges disjoint flag sets; strict flag additions with identical non-flag text merge on an absolute budget even when the relative band rejects
  • Session cleanup: in-process hosts clean on session.deleted/departed; CLI harnesses via the session-event phase — implemented for Claude (SessionEnd hook → forgetSession), other CLI harnesses remain TTL-only until their session-end surface is verified
  • SessionStart digest (Claude only): the session-start CLI phase reads the stores read-only (unlocked load() via enforcedGates(), never loadForMutation) and injects the top enforced gates (blocking first, then reminding, lastSeen-desc in a tier; 5 gates, ~2000 chars, whole lines only) as hookSpecificOutput.additionalContext — the agent is taught upfront instead of losing a first call to a reminder; the phase never denies and never records; other harnesses no-op (mapInbound null → allow dialect) until a verified session-start surface exists
  • Self-healing stores: every init runs reconcileAll() — unparseable files are quarantined (bytes preserved in *.corrupt-*, never deleted), records are strictly parsed + mechanically repaired, index is reconciled, and every repair is logged (repaired/quarantined events); doctor --repair does the same on demand — one command replaces hand-debugging. The init-storm version-stamp skip is a STARTUP optimization only: doctor --repair and the migrate script call migrate(force) so an explicit repair always applies the full per-gate healing, even on a same-version re-run
  • Multi-window safe: the remind→block chain is persisted on the gate, not in process memory — several OpenCode windows (each its own process on the shared store) and process restarts all see the same escalation; hot-path reads use a 1s TTL cache + O(1) key index
  • dejavu:proceed escape hatch: trailing marker comment, matched with word boundaries, stripped before normalization so bypassed failures land on the original pattern
  • recurredAfterGate is THE health metric — gates that fire without killing the error get review: true; its mirror succeededAfterGate heals gates — 3 consecutive successes on an enforced gate retire it to watching, so a fixed command stops reminding
  • Enforcement has negative feedback: 3+ post-gate recurrences (across 2+ reoffense sessions) or 3+ explicit overrides (across 2+ distinct bypassing sessions) demote a gate to watching + feedbackDemoted (never re-promotes mechanically; feedbackBaseline gives a human re-enforcement a fresh grace window) — a gate the agent keeps fighting is friction, not teaching; BOTH votes need distinct sessions so one stubborn/injected session can't disarm a gate; overrides are counted on the gate (overrideCount/overrideSessions) on EVERY enforced tier — blocking keeps the 3/2 formula, reminding demotes on DEMOTE_OVERRIDES_REMINDING (5) distinct bypassing sessions with no raw-count bar — and promotion never wipes the counters (lifetime friction, like promotionCount); demotions log demoted
  • The loop closes on success: a SUCCESS on an enforced gate clears that session from the remind→block chain (override + prove-the-fix leaves the session clean) and grows the heal streak — enforcement listens to behavior in both directions; iteration runners (dart run, go run|build|test|vet, cargo run|build|test|clippy) annotate the failing output but never interrupt or block
  • Taught retirement: a gate reminded 5+ times with zero reoffense has taught its lesson (no success can ever heal it — the agent changed behavior) and retires to watching (retired-taught); re-promotion on new failures stays possible. Blocking fires it in the before-hook (recurredAfterGate === 0); reminding fires it in the after-hook at one reminder higher (recurredAfterGate grows structurally there, so only recurredAfterReminder === 0 is the teachability signal) — the extra round keeps it from preempting anti-nag evidence; the chronic lane (CHRONIC_REMINDERS 10, reoffense 1–2) retires the stuck middle between taught and anti-nag (retired-chronic)
  • Retirement damping: a healed/taught-retired gate keeps its lifetime count/sessions, which alone would clear the promotion bar and re-promote it on the very next single failure (a promote→heal→promote loop). Retirement captures retireBaseline.count; promotion ADVANCES it to the current lifetime count (never deletes), so every re-promotion needs a full fresh bar of failures since the last promotion (count − retireBaseline.count ≥ threshold). Doctor's FLAPPY report watches for the oscillation; at 3 promotions AND 3 retirements (retiredCount, merge-summed) promotion refuses mechanically — watching + feedbackDemoted, terminal
  • promotionCount is the lifetime promotion counter (never reset, merge-summed) — the rot-proof FLAPPY signal; doctor escalates it at >= 3. lastInitVersion is stamped by save() with the writer's own version — the durable version-drift signal (log init events rotate away); a newer-writer stamp self-surfaces at boot (warn + version-drift event, long-lived hosts only — the check runs BEFORE reconcile, which re-stamps the file)
  • Cross-channel dedup: one tool call must never be counted twice — the after-hook (exit/text) and the event stream (error parts) are disjoint by construction, but a runtime guard keyed on (key, session) + channel-mismatch window counts a double-firing call once (doctor's CROSS-CHANNEL DOUBLE-COUNT is the observable tripwire). The dedup key is the WHOLE-CALL signature, not the segment-attributed key — the event channel signs the entire call, so a chained command must dedup on one shared identity or it slips through on mismatched keys
  • Global forensics for deferred events: deferred events bypass logAll's routing, so the project store mirrors its salient deferred events (demoted/retired-healed) into the global log via routeSalientTo — direct events are not mirrored there (logAll already routes them)
  • Windows-first fs: \\?\ long-path prefix, tmp+rename with EPERM/EACCES/EBUSY backoff, lockfile with stale-steal and 3s degrade-to-unlocked (never hang the tool pipeline). Same-process callers (parallel tool calls in one window) serialize on an in-process queue BEFORE the file lock and never degrade — the 3s degrade is cross-process only. A transiently-unreadable store (EISDIR/EPERM/AV lock, not ENOENT) THROWS instead of parsing as empty, so a failed read can never let the next save clobber real gates

GIT HOOKS

  • commit-msg hygiene hook: scripts/githooks/commit-msg — header ≤100 chars, no emoji, no AI attribution trailers; matches trailer structure, so plain tool-name mentions pass
  • Activate once per clone: git config core.hooksPath scripts/githooks

COMMANDS

bun install
bun run typecheck            # tsc --noEmit — covers index.ts, src/**, scripts/**, test/**
bun test/smoke.ts            # full behavioral test; exit 1 on any failure
bun test/enforce.ts          # engine characterization (harness-agnostic core)
bun test/adapters.ts         # adapter mapping + decision dialects
bun test/cli.ts              # CLI end-to-end (spawn, promotion, block/annotate, fail-open)
bun test/store.ts            # store persistence: reconcile no-op skip, excise prefilter, expire peek, deferred index (BENCH=1 for the init benchmark)
bun test/language-gaps.ts    # language-ecosystem coverage of patterns.ts
bun test/guards.ts           # proactive guards characterization (fire shapes, precedence, bypass warnings)
bun test/messages.ts         # teaching-text framing (tier-truthful, data-label, storeDir-derived path)
bun test/property.ts         # seeded-generator invariants (normalization, capped-fuzzy equivalence, substitutions)
bun test/fuzz.ts             # mutation fuzz: no crash, no invariant break
bun test/install.ts          # installer e2e (install/uninstall/hooks --check, backup, foreign-hook survival)
bun test/v2-host.ts          # OpenCode V2 dual-export characterization (server() parity with V1 Dejavu)
bun test/cline-plugin.ts     # Cline plugin host characterization (beforeTool skip/afterTool appendContext over a temp store)
bun run lint:ast             # ast-grep structural gates (.ast-grep/rules/); needs ast-grep on PATH
bun scripts/doctor.ts [projectDirs...]
bun scripts/analyze.ts [projectDirs...]
bun scripts/migrate.ts <projectDirs...>
bun scripts/install-hooks.ts --harness <claude|codex|gemini|cursor|copilot|crush|devin|kiro> [--user|--project] [--dry-run]

NOTES

  • tsconfig.json covers index.ts, src/**, scripts/**, test/** — everything typechecks
  • CI: GitHub Actions (bun install --frozen-lockfile + typecheck + smoke + enforce + adapters + cli + store + language-gaps + guards + messages + property + fuzz + install + v2-host + cline-plugin + env + recurrence + ast-grep scan) on every push/PR
  • Structural gates live in .ast-grep/rules/ + sgconfig.yml: no-load-force-flag forbids load(true)/loadIndex(true) (use the named loadForMutation()/loadIndexForMutation()). Add a gate here when a bug class is structurally repeatable; sabotage-test it (introduce the bug shape → gate must fire)
  • Install = npm ({ "plugin": ["dejavu-gates"] }) or clone + re-export from ~/.config/opencode/plugins/dejavu.ts (see README); other harnesses via scripts/install-hooks.ts
  • DEJAVU_HOME env var overrides the global store dir — smoke test and scripts rely on it
  • Bump PLUGIN_VERSION (src/store.ts) on behavior changes — doctor detects version drift via init log events — AND keep package.json version in sync (npm publish uses the package version); tag the release's final commit vX.Y.Z (lightweight, matching existing tags) and push the tag — an untagged release is an unfinished release (the convention broke at v2.51.0 and was restored with 2.53.0)
  • gates.json files are human-editable by design: delete a gate object to disable, edit correction to teach
  • Project stores self-ignore: init writes .opencode/dejavu/.gitignore (gates.json committable, runtime files ignored); doctor --repair sweeps orphan *.tmp/stale *.lock artifacts (--prune-corrupt=<days> opt-in prunes quarantine files)

Discoverability (RDK)

  • On-demand only: run these when the user explicitly asks; never proactively.
  • npm run rdk:audit — Discoverability Score 0-100 and findings; read-only.
  • npm run rdk:fix — preview safe autofixes; npm run rdk:fix -- --apply writes them.
  • The rdk-audit workflow fails pull requests below vars.RDK_MIN_SCORE.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.