agentleFS
WhiteBiteWhiteBite/dejavu-gates/src/AGENTS.md

dejavu-gates / src

AGENTS.md16 starsChanged 47 days agoMITView on GitHub

Dependency-free core: patterns.ts (pure functions — call identity, normalization, detection, policy), store.ts (stateful — gates.json/log.jsonl I/O under locks, promotion, scope escalation, feedback demotion), fs.ts (leaf write primitives shared with the installer) and validate.ts (the parse/repair boundary every persisted gate crosses). On top of it, the harness-agnostic enforcement engine (types.ts contract + context/before/after/event/guards/repeat/repeat-channel/messages + host-init.ts boot lifecycle + enforce.ts public surface) consumed by hosts: ../index.ts (OpenCode V1 plugin + dual-export entry), opencode-v2.ts (OpenCode V2 host glue), cline-plugin.ts (Cline sandbox plugin), and…

  • Installs packages
  • 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

17 rules. About 0 are common, 2 are distinctive, and 15 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.

  • 15

    Very specific

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

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

    Every gate read from disk crosses coerceGateShape + repairGate in load() — enforcement never sees raw state.

    line 96
  2. Very specific:

    Do NOT add a tool to callSignature without deciding its class: PROBE_TOOLS (higher bar, never blocks) or bash-class

    line 117
  3. Very specific:

    Do NOT widen FAILURE_SIGNATURES to cover file-tool output — that text is file content.

    line 118
  4. Very specific:

    Do NOT flatten interpreter one-liner payloads to <str> — hashInterpreterPayload must run before string parameterization.

    line 119
  5. Very specific:

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

    line 120
  6. 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 121
  7. Distinctive:

    Do NOT prune global index entries because the CURRENT scope lacks the key — the gate may live in another project's store.

    line 122
  8. Very specific:

    Do NOT persist anything before sanitizeForStore() — terminal control chars in signatures/snippets/corrections are a bug (PowerShell colors …

    line 123
  9. Very specific:

    Do NOT count aborted/cancelled executions as failures — filter with isNoiseError() at the event channel

    line 124
  10. Very specific:

    Do NOT widen coerceGateShape drop rules casually — records it deems hopeless are silently dropped on every load.

    line 125
  11. Very specific:

    Do NOT write gates.json directly — always runLocked + save() (atomicWrite).

    line 126
  12. Very specific:

    Do NOT let withLock throw on CROSS-process contention — it degrades to unlocked after LOCK_WAIT_MS by design (pipeline must not hang).

    line 127
  13. Very specific:

    Do NOT call load(true)/loadIndex(true) — the write-capable read is loadForMutation()/loadIndexForMutation(), and only under the store lock.

    line 128
  14. Very specific:

    Do NOT reorder INTERPRETER_ONELINER alternatives shortest-first and do NOT add a code-passing interpreter flag without adding it to …

    line 129
  15. Distinctive:

    Do NOT promise blocks in reminding-tier messages — tier-truthful wording only.

    line 130
  16. Very specific:

    Do NOT read log.jsonl outside the log lock for rewrite-style operations (excise/rotate) — an unlocked read + locked rewrite drops …

    line 131
  17. Very specific:

    Do NOT add an adapter deny path that returns exit 0 with empty stdout for claude/codex/gemini, or exit 2 for cursor/copilot/crush — each …

    line 134

≈ “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

src/ — pattern engine + gate persistence + enforcement engine + harness adapters

OVERVIEW

Dependency-free core: patterns.ts (pure functions — call identity, normalization, detection, policy), store.ts (stateful — gates.json/log.jsonl I/O under locks, promotion, scope escalation, feedback demotion), fs.ts (leaf write primitives shared with the installer) and validate.ts (the parse/repair boundary every persisted gate crosses). On top of it, the harness-agnostic enforcement engine (types.ts contract + context/before/after/event/guards/repeat/repeat-channel/messages + host-init.ts boot lifecycle + enforce.ts public surface) consumed by hosts: ../index.ts (OpenCode V1 plugin + dual-export entry), opencode-v2.ts (OpenCode V2 host glue), cline-plugin.ts (Cline sandbox plugin), and cli.ts (hook-handler CLI for external harnesses). adapters/ maps eight external harnesses' hook payloads to the contract. Engine and adapters import only node: builtins + sibling modules — never a harness SDK.

WHERE TO LOOK

TaskFileSymbols
Call identity / gate keyspatterns.tscallSignature → normalizeCommand/normalizeFilePath → patternKey
Interpreter one-liner identitypatterns.tshashInterpreterPayload — -c/-e code payload → <code:hash>; quote-layer independent (one code = one key across "x", 'x', bare x); trailing args ride after the token
Chain-bypass protectionpatterns.tssplitChain (quote/paren-aware) → bashSegmentSignatures (unfolds cmd /c, $(...), backticks)
Free-form error collapsingpatterns.tsparameterizeError (event channel) vs normalizeCommand (bash)
Near-duplicate mergepatterns.tsfuzzySimilar = levenshteinCapped (early-exit) ≤ 0.3 + flag-subset rule + strict-flag-addition rescue on an absolute budget
Failure text scanpatterns.tsdetectFailure + FAILURE_SIGNATURES
Leaked tool-call serializationpatterns.tsdetectLeakedToolCall (DSL block tail-anchored, truncated tail, tool-word-tagged pairs/strays with attributes — fence/quote/inline guards) + neutralizeLeakedToolCalls (same guards, range-based splice) + NEUTRAL_PLACEHOLDER
Stuck-reasoning detectionpatterns.tsdetectStuckReasoning — letter-token run-length dominance / exact-duplicate lines / hedge density over a fence-stripped Unicode window; StuckVerdict
Loop recovery (opt-in)loop-recovery.tscheckLoopRecovery/settleLoopInjection/markTurnActed/appendReasoningDelta/clearLoopRecoverySession — DEJAVU_LOOP_RECOVERY, cap 2 landed injections, 30s cooldown, two-check confirmation, quota settles on outcome (a failed abort+prompt retries), monotonic per-message length (StuckMessageState.total) so the 8000-char buffer cap cannot stall the throttle, session-scoped ${sessionID}:${messageID} keys with full cleanup; hosts wire it (V1 event / V2 event.subscribe)
Noise filteringpatterns.tsisNoiseError + NOISE_ERRORS (aborted/cancelled ≠ failed)
Diagnostic/intended-exit logicpatterns.tsDIAGNOSTIC_VERBS, isIntendedNonzero, canBlock, canRemind, isUnixViewerSignature
Over-generic shape guardpatterns.tshasResidualIdentity — parameterized-away substance ⇒ watching only
Wrapper unwrappingpatterns.tsunwrapCmdWrapper — cmd /c|/k payload normalizes as the inner command
Persistence boundarypatterns.tssanitizeForStore = stripControl (ANSI/C0) + scrubSecrets
Escalation scope policypatterns.tsisRepoLocal + REPO_LOCAL_VERBS — repo-local verbs never escalate globally
One scope (gates.json + index.json + log.jsonl)store.tsGateStore — load/loadForMutation/save/loadIndex/loadIndexForMutation/saveIndex/log/expire/extract/rotateLog/reconcile; deferred events deferEvent/flushDeferred/appendBatch + routeSalientTo
Two-scope logic + promotionstore.tsStores — findGate/recordFailure/migrate/enforcedGates/reconcileAll; mergeGate merges duplicate keys
Enforcement negative feedbackstore.tscheckFeedbackDemotion + retireTaught/retireAntiNag; thresholds DEMOTE_RECURRENCES/DEMOTE_OVERRIDES/DEMOTE_OVERRIDE_SESSIONS; counters overrideCount/overrideSessions/recurredAfterGate, grace via feedbackBaseline
Gate parse/repair boundaryvalidate.tscoerceGateShape (strict parse), repairGate (mechanical coercion), hasNestedTokens (corruption fingerprint)
fs safetyfs.ts + store.tsntPath, atomicWrite (fs.ts — shared with the installer); withLock (store.ts — in-process queue + cross-process file lock)
Cross-harness contracttypes.tsNormalizedEvent/Verdict/OutboundDecision/HarnessAdapter — types only, zero imports
Enforcement entry pointsbefore.ts / after.ts / event.tsenforceBefore/enforceAfter/recordEventFailure/cleanupSession; verdicts out, never GateSignal (hosts translate)
Host-injected dependenciescontext.tsEnforceContext (stores/ephemeral/log/onHookError/platform/projectDir), EphemeralState + createEphemeralState (CLI degradation contract in its JSDoc), caps + dedup helpers
Host boot lifecyclehost-init.tsinitStores (ordered reconcile→migrate→expire + per-host opts), scheduleSweep (jittered TTL, returns disposer), rateLimitedErrorSink
Teaching textsmessages.tsremindMessage/remindNote/blockMessage — verbatim wording, tier-truthful
Proactive guardsguards.tslong-running/wait-loop/suppressed-spawn/inherited-spawn/orphan-job/snowball + bypass warnings
Repeat-series blockrepeat.tsrepeatSeriesDecision — override kind FALLS THROUGH to gate processing
Repeat/loop-break transform channelrepeat-channel.tsapplyRepeatChannel — marker sanitization, REPETITION/windowed/shape notes, loop-break injection, opt-in leaked tool-call recovery (recoverLeakedToolCall, DEJAVU_LEAK_RECOVERY) over structural messages; hosts wire it (V1 transform / V2 generate)
Harness payload mappingadapters/*.tsper-harness mapInbound/mapOutbound; adapters/shared.ts — internalTool/internalArgs/str/rec/extractOutput/errorSignalled/genericToolOutput/allowDecision/denyDecision
Hook-handler CLIcli.tsargv/stdin parse → adapter → engine → decision JSON; fail-open; registry ADAPTERS; session-start phase → SessionStart gate digest (claude-only, read-only)
OpenCode V2 host glueopencode-v2.tsv2Setup — registers execute.before/after, event.subscribe (session.deleted + loop-recovery reasoning/text/tool deltas), compaction, and generate (repeat-channel parity) on the V2 plugin Context; deny-by-throw; reuses enforceBefore/enforceAfter/recordEventFailure/cleanupSession

INVARIANTS (do not break)

  • Rule order in PARAM_RULES matters: quoted strings first, specific tokens (uuid/sha/ip/url/date), generic numbers last — reordering fragments signatures
  • Rule order in normalizeCommand matters too: control-char strip first, then quoted strings are parameterized BEFORE token rules - a <str> substitution inserts spaces that would expose an adjacent / to the path rule on a second pass (idempotency); scheme URLs parameterize to <url> BEFORE the drive-letter rule (else https://x shatters into http + <path>); trailing # ... comments strip LAST, after the placeholder rules (their inserted spaces expose the # only then); unwrapCmdWrapper runs before hashInterpreterPayload so a wrapped one-liner still fingerprints; interpreter payload hashing runs while the payload is still raw
  • sanitizeForStore() (control-char strip + scrubSecrets) runs on every string before it touches disk; recordFailure re-sanitizes defensively
  • Three enforcement tiers: canBlock (bash && non-diagnostic && non-viewer && residual identity) is the ONLY path to blocking; canRemind ((diagnostic OR Unix-viewer) bash && residual identity, OR a tool-error head with ≥ 3 literal word tokens) is the only path to reminding; probe tools use PROMOTE_COUNT_PROBE and never leave watching; hasResidualIdentity guards BOTH tiers — a fully parameterized shape may only watch
  • Feedback demotion is the negative twin of healing: recurrences (DEMOTE_RECURRENCES across DEMOTE_REOFFENSE_SESSIONS distinct reoffense sessions) OR overrides (DEMOTE_OVERRIDES across DEMOTE_OVERRIDE_SESSIONS distinct bypassing sessions) past threshold demote to watching + feedbackDemoted, which blocks mechanical re-promotion; BOTH votes require distinct sessions so one stubborn/poisoned session cannot demote a gate for everyone. Legacy exception: overrideSessions === undefined (overrides predate 2.28 session tracking — current hooks ALWAYS record sessions alongside the count) falls back to count-only demotion, else historical gates could never reach the session bar; reoffenseSessions keeps the strict rule (it legitimately stays absent on current data — first-encounter failures never vote). feedbackBaseline (counter values at demotion) gives a human re-enforcement a fresh grace window; mergeGate sums overrideCount and baselines, unions overrideSessions, and preserves the demotion mark
  • Index entries are never pruned on one project's initiative by reconcileAll (it rebuilds missing entries only) — a process sees one project store, so "absent here" ≠ "dead". expireAll's index sweep prunes via time-decayed candidacy: a key absent from every visible scope (own project + global) is stamped orphanCandidateSince, cleared the moment any scope holds the gate again, and deleted only after ORPHAN_CANDIDATE_DAYS (7) of continuous absence — a live gate in an unopened project clears its own candidacy on that project's sweep; the plain lastSeen TTL still applies regardless
  • Repo-local verbs (isRepoLocal) never escalate to the global store — their failures are repo quirks; both escalation paths (recordFailure + reconcileAll) and doctor's MISSED-ESCALATION honor this
  • Fuzzy merging requires comparable flag sets (one a subset of the other) — disjoint switches are different operations and must never merge; subset additions still consolidate: a STRICT flag addition onto identical non-flag text rescues onto an absolute distance budget (SUBSET_ADD_MAX_DISTANCE) when the relative length band rejects (short commands always fail the band) — the O(1) band still rejects first and the rescue is computed only on band-reject (flood path runs per gate under the gates lock)
  • DIAGNOSTIC_VERBS serves two callers (exit-1 allowlist + blocking policy) — one list, two uses; edit knowing both move. Unix viewers (cat/head/tail/wc/less/more) are deliberately NOT in it — their exit 1 must stay recordable (a missing file is a real failure) and a terminal tail producer still counts; their never-block/remindable policy lives in the separate isUnixViewerSignature (canBlock/canRemind only). PowerShell read-only probes (Get-Process/Get-Item/Get-ChildItem/Get-Content/Test-Path/Resolve-Path/Measure-Object) ARE diagnostics — the ls class, probe result not operation failure
  • Lock order is always project → global, gates → index (see recordFailure escalation) — reversing deadlocks; the log lock is separate and leaf-level, acquired alone or outermost, NEVER while holding a gates/index lock — log-hygiene helpers (exciseCorruptLogLines/rotate) run OUTSIDE the scope lock, else the scope critical section stretches across a full log read+parse+rewrite at init-storm time
  • A degraded lock waiter NEVER unlinks the lockfile (withLock tracks acquired) — deleting the live holder's lock destroys mutual exclusion for every subsequent acquirer (the production corrupt-log root cause)
  • Incoming bash signatures without residual identity match concrete gates EXACTLY only (findGate fuzzy + recordFailure consolidation both guard it) — family noise must neither enforce nor pollute another gate's evidence
  • bashSegmentSignatures unfolds cmd /c payloads AND $(...)/backtick substitutions recursively (depth-bounded) — inner-chain gates fire through the wrapper/substitution, and the before-hook honors dejavu:proceed inside a LEADING wrapper payload (unwrap before quote-strip). Substitution extraction only ADDS candidate signatures (fail-safe); quote handling is PowerShell-first toggling (backslash is NOT an escape — bash \" spans are a documented limitation)
  • INTERPRETER_ONELINER alternatives run longest-first — -c matching inside -command swallowed the flag tail into the payload and fragmented keys across flag spellings
  • Cross-project evidence lives ONLY in the global index.json — a gate's own projects array sees one store and never drives escalation alone
  • Escalation writes the global gate FIRST, then removes the project copy — a crash between the two writes must leave a duplicate (healed by migrate), never a hole
  • mergeGate preserves session enforcement state (remindedSessions/failedSessions) — merging must never reset the remind→block chain
  • Fuzzy consolidation in recordFailure prefers the gate holding the session's reminded state (before/after hooks must stay in sync) and never overwrites the evidence snippet
  • Snippets and corrections are UNTRUSTED text re-injected into agent context — keep the data-label framing in messages, the 200-char correction bound, and scrub quarantine bytes
  • Inside runLocked always loadForMutation(); OUTSIDE the gates lock always read-only load() — loadForMutation() bypasses the cache and quarantines an unparseable file (a WRITE), so calling it outside the lock is a write-without-lock (the class round 3 fixed in doctor); unlocked load() peeks are routing hints only, never a basis for mutation. The capability is in the NAME, not a boolean flag — the no-load-force-flag ast-grep gate forbids load(true)/loadIndex(true)
  • Hot-path reads use the 1s TTL cache + key index (byKey/enforcedOnly); mutations inside locks use loadForMutation(); save() refreshes the cache directly; removals go through extract() (drops keyIndex/enforcedCache) — a raw splice strands the index (the v2.35.0 escalation-fragmentation bug; no-raw-gates-splice ast-grep gate)
  • Iteration evidence is a COARSE proxy by design (any landed edit/write in the project moves the version — unrelated files included; subagent edits share the process). Only a LANDED edit bumps: the after-hook gates the version increment on !failed && event.errored !== true — a failed edit/write must never lift the session's hard-block chain or mark the next failure "iterated" (errored is the host's structural failure signal: adapters set it from errorSignalled; V2 routes event.error to the event channel instead; V1 tool-level failures never reach tool.execute.after). Accepted bounds (oracle-reviewed 2.35.0): a grace consumed by an unrelated edit costs one extra failing run; a promotion false-negative needs ignored-failure + constant unrelated edits + never-changing error (rare, human-recoverable). Multi-window desync is bounded and self-correcting (failedSessions are session-keyed). Merging a retired gate can drive stuckEvidence negative — the direction is conservative (harder re-promotion, never over-enforcement). movedOn/iteratedVersion are lifetime/bookkeeping fields: mergeGate sums movedOn, takes max iteratedVersion, preserves target retireBaseline
  • The remind→block chain is persisted ON THE GATE (remindedSessions/failedSessions) and enforced under the store lock — process memory holds nothing authoritative, so several windows and restarts share one escalation
  • Successes heal: recordSuccess grows succeededAfterGate on an enforced gate; at HEAL_SUCCESSES (3) it retires to watching and logs healed. A failure resets the streak in recordFailure. Only bash successes heal (only bash gates enforce). A success ALSO clears the succeeding session from remindedSessions/failedSessions — override + success must leave the session clean, otherwise the only exit from a block is permanent overriding (the arms-race engine). Heal-aware: a blocking gate with succeededAfterGate > 0 skips the first-encounter abort (a likely-fixed command) — it arms the chain silently and blocks only a repeat failure
  • Iteration verbs (dart run, go run|build|test|vet, cargo run|build|test|clippy) are diagnostic: their failures are the work itself — they annotate the failing output and never interrupt or block, and their exit 1 is the intended "still broken" outcome of iteration. Diagnostic signatures are ALSO exempt from the recurredAfterGate metric (after-hook): a test runner failing again after the note is iteration, not failure-to-teach — counting it inflated recurrence into useless demotion/review pressure; nagging still retires via remindedCount/recurredAfterReminder (taught/anti-nag)
  • Overrides count toward demotion ONLY on blocking gates — a reminding gate never blocks and never interrupts, so bypassing it is not friction with the teaching (the override event is still logged for visibility)
  • EVERY failure indexes (no churn gate): a pattern failing ONCE per project across N projects is the canonical agent habit, so the first failure must reach the global index or cross-project escalation can never see it. The old count < 2 skip starved exactly the sparse-but-global patterns the global store exists to collect. Index writes are split: STRUCTURAL changes (new key, new project dir) save immediately under the index lock; lastSeen-only refreshes defer (deferIndexTouch) and flush with flushDeferred (CLI exit, host sweeps) — a crash may lose a lastSeen bump, never first evidence
  • Weak one-off patterns rot fast: expire() applies NOISE_TTL_DAYS ONLY to watching gates with count <= 1 (never recurred); a twice-seen pattern has proven recurrence and gets the full TTL_DAYS even below the promotion bar, so slow recurrences (every 8+ days) can still accumulate to promotion
  • Unparseable gate dates reset to now at the parse boundary — expire compares Date.parse < cutoff, and NaN is never < anything (immortal gates)
  • migrate() never re-promotes feedbackDemoted gates (the watching→reminding catch-up checks the flag) — "never re-promotes mechanically" must hold on EVERY mechanical path, not just recordFailure. The catch-up ALSO exempts retireBaseline gates: a healed/taught-retired gate's lifetime count already clears the catch-up bar, so re-promoting it on every migrate would re-open the promote→heal→promote oscillation the damping baseline exists to kill — retirement is evidence-based and only a fresh bar of failures (via recordFailure) may lift it
  • recordSuccess heals and clears session chains on EXACT matches only — fuzzy matches are attribution convenience, never a basis for state mutation (proxy successes would heal the wrong gate)
  • The override marker requires comment syntax (# dejavu:proceed) — quote-stripping alone let unquoted markers smuggled as data (echo dejavu:proceed && gated) bypass gates
  • Exit-1 immunity requires every NON-transparent chain segment to be diagnostic — a diagnostic later in the chain must not hide a non-diagnostic's failure (deploy && grep). Pipe formatters (select-object/tee-object/tee/head/tail/...) are transparent ONLY in pipe-tail position (after a |, including bash's |& pipe-stdout-and-stderr, which is a pipe so its tail is a pipe tail too): they never produce the pipeline's exit code there, so tsc | Select-Object keeps immunity; but a formatter standing alone or as the TERMINAL producer of a sequence (npm test && tail -5 missing.log) IS the failing producer and still counts. Navigation (cd/set-location) is transparent only when the segment is PURE navigation — a segment pairing a nav verb with a diagnostic and no separator (cd packages/foo npx vitest run …) keeps the diagnostic instead of being dropped wholesale (dropping it hid the command and broke immunity); a bare cd /bad/path still counts. A real non-diagnostic producer still breaks immunity (npm install | select-object counts). Position comes from splitChainTagged; || is a sequence separator, so the segment after it is a producer, not a pipe tail. A single & is deliberately NOT a separator — on Windows it is the PowerShell call operator (& "C:\…\exe"), and splitting on it would break those invocations
  • load()/loadForMutation() distinguish THREE states: ENOENT = legitimately absent (empty store), unparseable = corruption (quarantine under the lock, bytes kept — never silently empty, which let the next save overwrite recoverable gates), and any OTHER read error (EISDIR/EPERM/AV lock) = transient unreadable → THROW (fail loud; hook catches stay fail-open) — treating a transient read failure as empty let the next save clobber the real gates.json
  • withLock verifies ownership (pid in the lockfile) before unlinking — after a stale-steal the original holder would otherwise delete the stealer's lock and open the critical section
  • Retire-on-taught: reminded TAUGHT_REMINDERS+ times with zero reoffense AND zero post-gate failures → softly to watching (retired-taught, no feedbackDemoted — re-promotion stays possible). Healing via success is impossible there: the agent changed behavior, the gated call never runs again. Only TRUE first encounters count — raced calls (same dispatch burst) never saw the reminder
  • Reminding gates NEVER abort the call: the before-hook returns early for reminding, and the after-hook appends a [dejavu] NOTE (remindNote) to the FAILING output once per session (repeat same-session failures only accrue recurredAfterReminder); a succeeding run produces no note. Reminding taught retirement fires in the after-hook at one reminder ABOVE TAUGHT_REMINDERS with recurredAfterReminder === 0 — recurredAfterGate is no signal there (it grows structurally: every session's first failure counts and the note rides AFTER it), and 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)
  • Anti-nag retirement (the negative twin of taught) runs at two hook points: the before-hook for BLOCKING gates (first encounter) and the after-hook for REMINDING gates (a same-session failure after the note). Condition: reminded ANTI_NAG_REMINDERS+ times AND recurredAfterReminder >= ANTI_NAG_REOFFENSE → the gate NAGS instead of teaching: watching + feedbackDemoted, counters reset (a manual re-enforce starts fresh). feedbackDemoted blocks mechanical re-promotion; a human re-enforces manually. recurredAfterReminder accrues for blocking (failedSessions branch) and reminding (ignored-note branch); repairGate zeroes it only AT the blocking→non-blocking demotion transition (stale-evidence guard), since reminding gates now accrue it freshly — the plugin should help, not nag
  • Retirement damping (retireBaseline): heal and teach-retire both capture {count} at the moment of retirement, and re-promotion requires count − retireBaseline.count ≥ threshold — a full fresh bar — which promotion then consumes (deletes). Without it a retired gate re-promotes on the VERY NEXT single failure, because its lifetime count/sessions already clear the bar (promote→heal→promote oscillation). mergeGate preserves an existing baseline, repairGate clamps it to ≤ count (a corrupted overshoot must keep damping active, not re-open instant re-promotion). feedbackDemoted gates are orthogonal — they never re-promote at all
  • Enforcement counters are lifecycle-scoped: promotion resets remindedCount/recurrences/heal streak/baseline AND clears session chains (remindedSessions/failedSessions) — a re-promoted gate must not inherit the previous retire/heal round's evidence, and stale chains must not let a session skip its reminder. Override friction (overrideCount/overrideSessions) is LIFETIME like promotionCount — promotion never wipes it, so the demotion loop closes across retire/re-promote cycles
  • Demotion votes count only failures the gate had a chance to prevent: recurrence demotion additionally requires DEMOTE_REOFFENSE_SESSIONS distinct sessions that reoffended AFTER a reminder (reoffenseSessions) — first-encounter failures never saw a reminder, and one bad session/model must not demote a gate for everyone
  • Exit-1 immunity flattens SUBSHELL paren groups before splitting (isIntendedNonzero -> flattenSubshellParens): (deploy && grep) is a container, not an atom - a diagnostic inside parens must not immunize a non-diagnostic failure. Flattening is brace-aware AND substitution-aware: parens inside {} script blocks, quotes and $(...) command substitutions are left alone (grep x $(find ...) is ONE command), so method-call parens (ForEach-Object { $_.trim() }) don't split their segment. cmd /c wrappers and interpreter one-liners delegate the exit code to their payload - immunity is decided on the RAW payload before fingerprinting
  • Hook events are queued inside the store lock and logged AFTER release — logging under the gates lock extends the critical section and cascades contention into degrade storms
  • recordSuccess is exact-only (byKey across scopes, no fuzzy scan): it runs on every successful bash call, and healing/chain-clearing are state mutations — fuzzy matches are attribution convenience, never a basis for mutation
  • Log appends and rotation take the log lock — every OpenCode window shares the global log; unlocked appends interleave into broken JSON
  • Nothing logs under the gates lock — events are deferred (deferEvent) and flushed by the next log()/flushDeferred(); scripts (doctor/migrate) MUST call flushDeferred() before exiting or repair events are lost ("every repair is logged"). The drain happens INSIDE the log lock (draining before the lock dropped events)
  • reconcile() preserves the migration stamp when it rewrites gates.json — dropping it forces a full migrate() scan on every startup (init storm); a no-op heal (zero dropped/repaired/merged) skips the rewrite entirely — file bytes untouched, the parsed view refreshes the TTL caches
  • logAll scopes events: high-volume events (detected/reminded/blocked/retry-allowed/recurred-after-gate) stay in the project log; only machine-memory-salient events (GLOBAL_LOG_EVENTS = init/promoted/demoted/healed/retired-*/override) reach the global log — the global log lock is the most-contended lock. detected events carry the producing harness (forensics: which harness taught a gate)
  • Deferred events bypass logAll's routing, so the project store mirrors them itself: routeSalientTo (project→global, wired in the Stores constructor; the global store gets NO peer) makes log()/flushDeferred() forward the salient subset of the DRAINED deferred batch via the peer's appendBatch, AFTER the store's own log lock releases (leaf locks, one at a time). Direct events are NEVER mirrored here — logAll already routes them; mirroring the direct event inside log() would double-write it to the global log
  • recordFailure uses FLAT lock phases — the project gates lock is released before the index lock and the global gates lock (never nested); escalation is three short phases (copy → global-first write → remove-local); a crash between the two writes leaves a duplicate healed by migrate, never a hole
  • The TTL sweep timer is jittered (0.75–1.25× interval) and flushes deferred events (flushDeferredAll) so a quiet long-lived process doesn't lose sweep events on exit
  • Every gate read from disk crosses coerceGateShape + repairGate in load() — enforcement never sees raw state; hopeless records are dropped, repairable ones coerced
  • Quarantine preserves bytes: unparseable files are renamed to *.corrupt-*, never deleted; every repair emits a repaired/quarantined log event
  • exciseCorruptLogLines accepts {…}-enveloped lines without a full JSON.parse — the corruption classes quarantine exists for (truncated writes, interleaved appends) always break the envelope; scripts/doctor.ts remains the thorough full-parse pass
  • Fuzzy matching is Levenshtein-based on purpose: token Jaccard collapsed all <str> placeholders into one bucket; ratio ≤ 0.3 PLUS absolute distance ≥ 3 (verb-level-different commands must never merge). fuzzySimilar uses levenshteinCapped (row-min early exit) — identical verdicts to full Levenshtein, but the flood path (per-gate under the lock) skips the DP cost cliff on long dissimilar pairs; the strict-flag-addition rescue keeps the early exit honest (cutoff = max(ratioCutoff, SUBSET_ADD_MAX_DISTANCE) when it applies, so the capped DP never exits below the budget); property.ts proves the capped and reference implementations agree
  • Taught/anti-nag retirement MUTATIONS are shared (retireTaught/retireAntiNag in store.ts) and called from both hooks; the CONDITIONS stay at the call sites because they are tier-explicit (before-hook blocking vs after-hook reminding) and intentionally differ
  • Evidence quality: failureSnippet is error-aware — for a non-zero exit it scans from the END for a failure-shaped line and never returns a success-shaped one (looksLikeSuccess rejects pass summaries); recordFailure never overwrites a failure-shaped snippet with a success-shaped one (latest wins among failure-shaped); repairGate clears success-shaped snippets and re-derives machine Last error: template corrections that quoted one (human edits never match the fixed template byte-for-byte, so they stay)
  • Chain attribution requires exactly ONE non-transparent producer (nonTransparentProducers) — with several, the exit code does not say which failed, so the failure records under the WHOLE call; a diagnostic segment's gate must not be inflated by another producer's failure. The attribution loop iterates ONLY producer segments (producerSegmentSignatures, sharing the isTransparentSegment predicate) and skips signatures without residual identity — a transparent segment's gate (cd/pipe-tail/env) must never absorb the failure even when its key is known
  • segmentHasIdentity treats bare flags (-x/--foo) after a wrapper head as switches, not identity — a flag-only wrapper (cmd <path> <str> -f) matches a command family and may only watch. Family VERB PHRASES extend the rule: git commit (message always parameterized, staged content invisible — a bare git commit gate matches EVERY commit), npx <runner> (tsx/ts-node/esno/vite-node — the package is the verb, the script is the call), and a run-subcommand right after a wrapper head (bun run <str>) — identity must come from a concrete argument AFTER the verb phrase (git commit src/foo.ts -m <str>, npx tsx scripts/x.ts, bun run scripts/build.ts all keep it)
  • Env assignments ($env:X=…, FOO=bar) and start-sleep are transparent producers (they cannot be the failing producer) — like navigation, they break neither exit-1 immunity nor attribution
  • promotionCount increments on every promotion and is never reset (mergeGate sums it) — the rot-proof FLAPPY measure (the log-based one rots with rotation); at 3 promotions AND 3 retirements (retiredCount, summed by mergeGate, incremented by heal + retireTaught only) promotion refuses mechanically — watching + feedbackDemoted, terminal; save() stamps lastInitVersion with the WRITER's own version — the durable 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)
  • mapOutbound canonical contract: POST never blocks — the call already ran, so annotation is checked FIRST (rides on allow, exit 0, additionalContext-shaped JSON per harness, 10k cap where documented); only PRE denies (exit-2+stderr for claude/codex/gemini, native JSON deny for cursor/copilot/crush). SESSION-START never denies either — the digest rides additionalContext (claude: hookEventName: "SessionStart") or the phase stays silent. An early action === "allow" return before the annotation branch kills the reminding NOTE (the 2.39 pre-release bug, pinned by test/adapters.ts + test/cli.ts)
  • Engine functions return verdicts and never throw GateSignal — translating a deny verdict into the host's abort dialect is the HOST's job (index.ts throws GateSignal; cli.ts sets exit 2 + stderr). Engine bugs propagate to the host's catch (index: logHookError + fail-open; cli: {} + exit 0)
  • CLI stdout is the harness's decision-JSON channel — nothing in the hook paths (engine + cli.ts dispatch) may write to stdout; engine diagnostics go through EnforceContext.log (the CLI wires it to stderr, DEJAVU_DEBUG-gated). Separate bin entries (main.ts, install.ts, lesson.ts) own their process's stdout — they never share a process with the hook channel. The CLI fails OPEN on every fault path (malformed stdin / broken store / internal error → {} exit 0); only usage errors exit 1 and deliberate blocks exit 2
  • Harness payloads are untrusted external input: mapInbound never throws (unrecognized → null → no-op), and every string crossing into persistence goes through the same sanitizeForStore() boundary as the OpenCode channel (recordFailure re-sanitizes defensively)
  • Adapters normalize tool names/arg fields BEFORE callSignature (via internalTool/internalArgs) so signatures are harness-neutral — the unified store only works while a Claude Bash{command} and an OpenCode bash{command} produce the identical signature
  • EphemeralState degradation is a contract, not a bug: a fresh state per CLI process weakens repeat-series/pendingCalls/dedup-window/iteration-discriminator to single-call scope; gate enforcement stays multi-process safe because the remind→block chain is persisted ON THE GATE (createEphemeralState() JSDoc is the reference)
  • Host boot is encoded ONCE in host-init.ts: initStores owns the reconcile→migrate→expire order (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 never call it), rateLimitedErrorSink unifies the three 60s error sinks (the CLI deliberately stays unlimited — one process serves one call)
  • The repeat/loop-break transform channel is engine code (repeat-channel.ts applyRepeatChannel over structural messages) — hosts keep only hook registration, payload casts, and injection application (V1 experimental.chat.messages.transform, V2 generate); a new host wires the same call instead of copying ~200 lines

ANTI-PATTERNS

  • Do NOT add a tool to callSignature without deciding its class: PROBE_TOOLS (higher bar, never blocks) or bash-class
  • Do NOT widen FAILURE_SIGNATURES to cover file-tool output — that text is file content; extend the event channel instead
  • Do NOT flatten interpreter one-liner payloads to <str> — hashInterpreterPayload must run before string parameterization; a bare -c <str> gate would block the whole command family
  • 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 prune global index entries because the CURRENT scope lacks the key — the gate may live in another project's store; only the TTL sweep removes entries
  • Do NOT persist anything before sanitizeForStore() — terminal control chars in signatures/snippets/corrections are a bug (PowerShell colors errors with VT sequences)
  • Do NOT count aborted/cancelled executions as failures — filter with isNoiseError() at the event channel
  • Do NOT widen coerceGateShape drop rules casually — records it deems hopeless are silently dropped on every load; a bad rule silently empties stores
  • Do NOT write gates.json directly — always runLocked + save() (atomicWrite); logs are append-only via log()
  • Do NOT let withLock throw on CROSS-process contention — it degrades to unlocked after LOCK_WAIT_MS by design (pipeline must not hang). Same-process contention is different: it serializes on the in-process queue and NEVER degrades (parallel tool calls in one window must not clobber each other)
  • Do NOT call load(true)/loadIndex(true) — the write-capable read is loadForMutation()/loadIndexForMutation(), and only under the store lock; the no-load-force-flag ast-grep gate enforces this
  • Do NOT reorder INTERPRETER_ONELINER alternatives shortest-first and do NOT add a code-passing interpreter flag without adding it to CODE_PASSING_FLAGS (the guard and the fingerprint must agree on what is structure)
  • Do NOT promise blocks in reminding-tier messages — tier-truthful wording only; a wrong enforcement model teaches the agent wrongly
  • Do NOT read log.jsonl outside the log lock for rewrite-style operations (excise/rotate) — an unlocked read + locked rewrite drops concurrent appends
  • Reminding-tier overrides count toward demotion too, on a session-vote-only bar: DEMOTE_OVERRIDES_REMINDING (5) DISTINCT bypassing sessions, no raw-count bar — bypassing a gate that never interrupts is weaker friction and needs broader consensus
  • Do NOT import a harness SDK into src/** — the engine + adapters depend only on node: builtins and siblings; harness specifics live in index.ts (OpenCode) or the adapter's payload mapping; exception: opencode-v2.ts may import type from @opencode/plugin (types-only, zero runtime dep) because it IS the OpenCode V2 host
  • Do NOT add an adapter deny path that returns exit 0 with empty stdout for claude/codex/gemini, or exit 2 for cursor/copilot/crush — each harness has ONE verified deny dialect (see the adapter JSDoc); mixing them silently un-blocks or double-signals
  • Do NOT "fix" the per-invocation CLI init (reconcileAll/migrate/expireAll per hook call) by removing it — it is the accepted cost of the short-lived host; repeated invocations are cheap by construction (migrate version-stamp skip, reconcile no-op skip, excise shape prefilter, unlocked expire peek, deferred index lastSeen flush), and flushDeferredAll before exit keeps forensics

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.