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.
- AGENTS.mdAGENTS.md
- llms-full.txtllms.txt
- llms.txtllms.txt
- dejavuSkill
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
- Very specific: line 96
Every gate read from disk crosses coerceGateShape + repairGate in load() — enforcement never sees raw state.
- Very specific: line 117
Do NOT add a tool to callSignature without deciding its class: PROBE_TOOLS (higher bar, never blocks) or bash-class
- Very specific: line 118
Do NOT widen FAILURE_SIGNATURES to cover file-tool output — that text is file content.
- Very specific: line 119
Do NOT flatten interpreter one-liner payloads to <str> — hashInterpreterPayload must run before string parameterization.
- Very specific: line 120
Do NOT enforce signatures without residual identity — if normalization parameterized the whole command away (cmd <path> <str>, node <str> …
- Very specific: line 121
Do NOT keep cmd /c wrappers in signatures — unwrapCmdWrapper() normalizes the payload so identity and the diagnostic tier see the real verb
- Distinctive: line 122
Do NOT prune global index entries because the CURRENT scope lacks the key — the gate may live in another project's store.
- Very specific: line 123
Do NOT persist anything before sanitizeForStore() — terminal control chars in signatures/snippets/corrections are a bug (PowerShell colors …
- Very specific: line 124
Do NOT count aborted/cancelled executions as failures — filter with isNoiseError() at the event channel
- Very specific: line 125
Do NOT widen coerceGateShape drop rules casually — records it deems hopeless are silently dropped on every load.
- Very specific: line 126
Do NOT write gates.json directly — always runLocked + save() (atomicWrite).
- Very specific: line 127
Do NOT let withLock throw on CROSS-process contention — it degrades to unlocked after LOCK_WAIT_MS by design (pipeline must not hang).
- Very specific: line 128
Do NOT call load(true)/loadIndex(true) — the write-capable read is loadForMutation()/loadIndexForMutation(), and only under the store lock.
- Very specific: line 129
Do NOT reorder INTERPRETER_ONELINER alternatives shortest-first and do NOT add a code-passing interpreter flag without adding it to …
- Distinctive: line 130
Do NOT promise blocks in reminding-tier messages — tier-truthful wording only.
- Very specific: line 131
Do NOT read log.jsonl outside the log lock for rewrite-style operations (excise/rotate) — an unlocked read + locked rewrite drops …
- Very specific: line 134
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 …
≈ “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.
Files
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
| Task | File | Symbols |
| Call identity / gate keys | patterns.ts | callSignature → normalizeCommand/normalizeFilePath → patternKey |
| Interpreter one-liner identity | patterns.ts | hashInterpreterPayload — -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 protection | patterns.ts | splitChain (quote/paren-aware) → bashSegmentSignatures (unfolds cmd /c, $(...), backticks) |
| Free-form error collapsing | patterns.ts | parameterizeError (event channel) vs normalizeCommand (bash) |
| Near-duplicate merge | patterns.ts | fuzzySimilar = levenshteinCapped (early-exit) ≤ 0.3 + flag-subset rule + strict-flag-addition rescue on an absolute budget |
| Failure text scan | patterns.ts | detectFailure + FAILURE_SIGNATURES |
| Leaked tool-call serialization | patterns.ts | detectLeakedToolCall (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 detection | patterns.ts | detectStuckReasoning — letter-token run-length dominance / exact-duplicate lines / hedge density over a fence-stripped Unicode window; StuckVerdict |
| Loop recovery (opt-in) | loop-recovery.ts | checkLoopRecovery/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 filtering | patterns.ts | isNoiseError + NOISE_ERRORS (aborted/cancelled ≠ failed) |
| Diagnostic/intended-exit logic | patterns.ts | DIAGNOSTIC_VERBS, isIntendedNonzero, canBlock, canRemind, isUnixViewerSignature |
| Over-generic shape guard | patterns.ts | hasResidualIdentity — parameterized-away substance ⇒ watching only |
| Wrapper unwrapping | patterns.ts | unwrapCmdWrapper — cmd /c|/k payload normalizes as the inner command |
| Persistence boundary | patterns.ts | sanitizeForStore = stripControl (ANSI/C0) + scrubSecrets |
| Escalation scope policy | patterns.ts | isRepoLocal + REPO_LOCAL_VERBS — repo-local verbs never escalate globally |
| One scope (gates.json + index.json + log.jsonl) | store.ts | GateStore — load/loadForMutation/save/loadIndex/loadIndexForMutation/saveIndex/log/expire/extract/rotateLog/reconcile; deferred events deferEvent/flushDeferred/appendBatch + routeSalientTo |
| Two-scope logic + promotion | store.ts | Stores — findGate/recordFailure/migrate/enforcedGates/reconcileAll; mergeGate merges duplicate keys |
| Enforcement negative feedback | store.ts | checkFeedbackDemotion + retireTaught/retireAntiNag; thresholds DEMOTE_RECURRENCES/DEMOTE_OVERRIDES/DEMOTE_OVERRIDE_SESSIONS; counters overrideCount/overrideSessions/recurredAfterGate, grace via feedbackBaseline |
| Gate parse/repair boundary | validate.ts | coerceGateShape (strict parse), repairGate (mechanical coercion), hasNestedTokens (corruption fingerprint) |
| fs safety | fs.ts + store.ts | ntPath, atomicWrite (fs.ts — shared with the installer); withLock (store.ts — in-process queue + cross-process file lock) |
| Cross-harness contract | types.ts | NormalizedEvent/Verdict/OutboundDecision/HarnessAdapter — types only, zero imports |
| Enforcement entry points | before.ts / after.ts / event.ts | enforceBefore/enforceAfter/recordEventFailure/cleanupSession; verdicts out, never GateSignal (hosts translate) |
| Host-injected dependencies | context.ts | EnforceContext (stores/ephemeral/log/onHookError/platform/projectDir), EphemeralState + createEphemeralState (CLI degradation contract in its JSDoc), caps + dedup helpers |
| Host boot lifecycle | host-init.ts | initStores (ordered reconcile→migrate→expire + per-host opts), scheduleSweep (jittered TTL, returns disposer), rateLimitedErrorSink |
| Teaching texts | messages.ts | remindMessage/remindNote/blockMessage — verbatim wording, tier-truthful |
| Proactive guards | guards.ts | long-running/wait-loop/suppressed-spawn/inherited-spawn/orphan-job/snowball + bypass warnings |
| Repeat-series block | repeat.ts | repeatSeriesDecision — override kind FALLS THROUGH to gate processing |
| Repeat/loop-break transform channel | repeat-channel.ts | applyRepeatChannel — 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 mapping | adapters/*.ts | per-harness mapInbound/mapOutbound; adapters/shared.ts — internalTool/internalArgs/str/rec/extractOutput/errorSignalled/genericToolOutput/allowDecision/denyDecision |
| Hook-handler CLI | cli.ts | argv/stdin parse → adapter → engine → decision JSON; fail-open; registry ADAPTERS; session-start phase → SessionStart gate digest (claude-only, read-only) |
| OpenCode V2 host glue | opencode-v2.ts | v2Setup — 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_RULESmatters: quoted strings first, specific tokens (uuid/sha/ip/url/date), generic numbers last — reordering fragments signatures - Rule order in
normalizeCommandmatters 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 (elsehttps://xshatters intohttp+<path>); trailing# ...comments strip LAST, after the placeholder rules (their inserted spaces expose the#only then);unwrapCmdWrapperruns beforehashInterpreterPayloadso 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;recordFailurere-sanitizes defensively- Three enforcement tiers:
canBlock(bash && non-diagnostic && non-viewer && residual identity) is the ONLY path toblocking;canRemind((diagnostic OR Unix-viewer) bash && residual identity, OR atool-errorhead with ≥ 3 literal word tokens) is the only path toreminding; probe tools usePROMOTE_COUNT_PROBEand never leavewatching;hasResidualIdentityguards BOTH tiers — a fully parameterized shape may only watch - Feedback demotion is the negative twin of healing: recurrences (
DEMOTE_RECURRENCESacrossDEMOTE_REOFFENSE_SESSIONSdistinct reoffense sessions) OR overrides (DEMOTE_OVERRIDESacrossDEMOTE_OVERRIDE_SESSIONSdistinct bypassing sessions) past threshold demote towatching+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;reoffenseSessionskeeps 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;mergeGatesumsoverrideCountand baselines, unionsoverrideSessions, 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 stampedorphanCandidateSince, cleared the moment any scope holds the gate again, and deleted only afterORPHAN_CANDIDATE_DAYS(7) of continuous absence — a live gate in an unopened project clears its own candidacy on that project's sweep; the plainlastSeenTTL 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_VERBSserves 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 terminaltailproducer still counts; their never-block/remindable policy lives in the separateisUnixViewerSignature(canBlock/canRemind only). PowerShell read-only probes (Get-Process/Get-Item/Get-ChildItem/Get-Content/Test-Path/Resolve-Path/Measure-Object) ARE diagnostics — thelsclass, probe result not operation failure- Lock order is always project → global, gates → index (see
recordFailureescalation) — 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 (
withLocktracksacquired) — 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 (
findGatefuzzy +recordFailureconsolidation both guard it) — family noise must neither enforce nor pollute another gate's evidence bashSegmentSignaturesunfoldscmd /cpayloads AND$(...)/backtick substitutions recursively (depth-bounded) — inner-chain gates fire through the wrapper/substitution, and the before-hook honorsdejavu:proceedinside 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_ONELINERalternatives run longest-first —-cmatching inside-commandswallowed 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 ownprojectsarray 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
mergeGatepreserves session enforcement state (remindedSessions/failedSessions) — merging must never reset the remind→block chain- Fuzzy consolidation in
recordFailureprefers 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
runLockedalwaysloadForMutation(); OUTSIDE the gates lock always read-onlyload()—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); unlockedload()peeks are routing hints only, never a basis for mutation. The capability is in the NAME, not a boolean flag — theno-load-force-flagast-grep gate forbidsload(true)/loadIndex(true) - Hot-path reads use the 1s TTL cache + key index (
byKey/enforcedOnly); mutations inside locks useloadForMutation();save()refreshes the cache directly; removals go throughextract()(dropskeyIndex/enforcedCache) — a rawsplicestrands the index (the v2.35.0 escalation-fragmentation bug;no-raw-gates-spliceast-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" (erroredis the host's structural failure signal: adapters set it fromerrorSignalled; V2 routesevent.errorto 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/iteratedVersionare 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:
recordSuccessgrowssucceededAfterGateon an enforced gate; atHEAL_SUCCESSES(3) it retires towatchingand logshealed. A failure resets the streak inrecordFailure. Only bash successes heal (only bash gates enforce). A success ALSO clears the succeeding session fromremindedSessions/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 withsucceededAfterGate > 0skips 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 therecurredAfterGatemetric (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 viaremindedCount/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
overrideevent 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 < 2skip 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 withflushDeferred(CLI exit, host sweeps) — a crash may lose a lastSeen bump, never first evidence - Weak one-off patterns rot fast:
expire()appliesNOISE_TTL_DAYSONLY to watching gates withcount <= 1(never recurred); a twice-seen pattern has proven recurrence and gets the fullTTL_DAYSeven 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 —
expirecomparesDate.parse < cutoff, and NaN is never<anything (immortal gates) migrate()never re-promotesfeedbackDemotedgates (the watching→reminding catch-up checks the flag) — "never re-promotes mechanically" must hold on EVERY mechanical path, not justrecordFailure. The catch-up ALSO exemptsretireBaselinegates: 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 (viarecordFailure) may lift itrecordSuccessheals 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, sotsc | Select-Objectkeeps 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 barecd /bad/pathstill counts. A real non-diagnostic producer still breaks immunity (npm install | select-objectcounts). Position comes fromsplitChainTagged;||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.jsonwithLockverifies 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 accruerecurredAfterReminder); a succeeding run produces no note. Reminding taught retirement fires in the after-hook at one reminder ABOVETAUGHT_REMINDERSwithrecurredAfterReminder === 0—recurredAfterGateis 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_REMINDERS10, 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 ANDrecurredAfterReminder >= ANTI_NAG_REOFFENSE→ the gate NAGS instead of teaching: watching +feedbackDemoted, counters reset (a manual re-enforce starts fresh).feedbackDemotedblocks mechanical re-promotion; a human re-enforces manually.recurredAfterReminderaccrues for blocking (failedSessions branch) and reminding (ignored-note branch);repairGatezeroes 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 requirescount − 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 lifetimecount/sessionsalready clear the bar (promote→heal→promote oscillation).mergeGatepreserves an existing baseline,repairGateclamps 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_SESSIONSdistinct 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 /cwrappers 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
recordSuccessis 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 nextlog()/flushDeferred(); scripts (doctor/migrate) MUST callflushDeferred()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 fullmigrate()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 cacheslogAllscopes 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.detectedevents carry the producingharness(forensics: which harness taught a gate)- Deferred events bypass
logAll's routing, so the project store mirrors them itself:routeSalientTo(project→global, wired in theStoresconstructor; the global store gets NO peer) makeslog()/flushDeferred()forward the salient subset of the DRAINED deferred batch via the peer'sappendBatch, AFTER the store's own log lock releases (leaf locks, one at a time). Direct events are NEVER mirrored here —logAllalready routes them; mirroring the directeventinsidelog()would double-write it to the global log recordFailureuses 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+repairGateinload()— 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 arepaired/quarantinedlog event exciseCorruptLogLinesaccepts{…}-enveloped lines without a full JSON.parse — the corruption classes quarantine exists for (truncated writes, interleaved appends) always break the envelope;scripts/doctor.tsremains 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).fuzzySimilaruseslevenshteinCapped(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.tsproves the capped and reference implementations agree - Taught/anti-nag retirement MUTATIONS are shared (
retireTaught/retireAntiNagin 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:
failureSnippetis error-aware — for a non-zero exit it scans from the END for a failure-shaped line and never returns a success-shaped one (looksLikeSuccessrejects pass summaries);recordFailurenever overwrites a failure-shaped snippet with a success-shaped one (latest wins among failure-shaped);repairGateclears success-shaped snippets and re-derives machineLast 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 theisTransparentSegmentpredicate) 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 segmentHasIdentitytreats 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 baregit commitgate 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.tsall keep it)- Env assignments (
$env:X=…,FOO=bar) andstart-sleepare transparent producers (they cannot be the failing producer) — like navigation, they break neither exit-1 immunity nor attribution promotionCountincrements on every promotion and is never reset (mergeGatesums it) — the rot-proof FLAPPY measure (the log-based one rots with rotation); at 3 promotions AND 3 retirements (retiredCount, summed bymergeGate, incremented by heal +retireTaughtonly) promotion refuses mechanically — watching +feedbackDemoted, terminal;save()stampslastInitVersionwith the WRITER's own version — the durable drift signal (log init events rotate away); a newer-writer stamp self-surfaces at boot (warn +version-driftevent, 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 ridesadditionalContext(claude:hookEventName: "SessionStart") or the phase stays silent. An earlyaction === "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:
mapInboundnever throws (unrecognized →null→ no-op), and every string crossing into persistence goes through the samesanitizeForStore()boundary as the OpenCode channel (recordFailure re-sanitizes defensively) - Adapters normalize tool names/arg fields BEFORE
callSignature(viainternalTool/internalArgs) so signatures are harness-neutral — the unified store only works while a ClaudeBash{command}and an OpenCodebash{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:initStoresowns the reconcile→migrate→expire order (per-host reduction is explicit opts — CLI: no init event, no rotate, no health, no drift check),scheduleSweepreturns a disposer (V2 disposes; index/cline never call it),rateLimitedErrorSinkunifies 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.tsapplyRepeatChannelover structural messages) — hosts keep only hook registration, payload casts, and injection application (V1experimental.chat.messages.transform, V2generate); a new host wires the same call instead of copying ~200 lines
ANTI-PATTERNS
- Do NOT add a tool to
callSignaturewithout deciding its class:PROBE_TOOLS(higher bar, never blocks) or bash-class - Do NOT widen
FAILURE_SIGNATURESto cover file-tool output — that text is file content; extend the event channel instead - Do NOT flatten interpreter one-liner payloads to
<str>—hashInterpreterPayloadmust 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 /cwrappers 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
coerceGateShapedrop 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 vialog() - Do NOT let
withLockthrow on CROSS-process contention — it degrades to unlocked afterLOCK_WAIT_MSby 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 isloadForMutation()/loadIndexForMutation(), and only under the store lock; theno-load-force-flagast-grep gate enforces this - Do NOT reorder
INTERPRETER_ONELINERalternatives shortest-first and do NOT add a code-passing interpreter flag without adding it toCODE_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.jsonloutside 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.tsmayimport typefrom@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
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
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.

