For agentic workers: REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.
Goal: Rebuild extensions/leaks so provider-bound text is redacted per extensions/leaks/SPEC.md, local Pi behavior is restored when placeholders round-trip exactly, and every validation batch V0-V9 has executable evidence.
Architecture: Replace prototype internals with a small redaction engine plus Pi hook adapter.
State is in-memory only: settings, warning counters, learned exact values, placeholder maps, recent safe labels, and provider redaction counters.
Provider payload redaction is authoritative; context redaction is opportunistic; tool args and finalized assistant messages restore placeholders locally.
Tech Stack: TypeScript ESM, Node 22 built-ins, Pi extension API from @earendil-works/pi-coding-agent, Vitest, repo tasks via mise.
Roadmap: None.
Phase: Single-plan implementation.
Status: Archived on 2026-08-10.
This original in-memory rewrite plan conflicts with the current durable placeholder lifecycle in extensions/leaks/SPEC.md and the implemented code.
Its unchecked boxes are historical, not current TODO.
Replace obsolete setting tests for rejected enabled, keywords, exclude, and secretFiles with tests that assert:
default engine is active
non-text values pass through unchanged
images and binary-looking objects are not inspected as special media
detector exceptions fail open and add one warning
secret values never appear in warning text
Required test names:
creates active engine with empty volatile state
does not implement rejected compatibility settings
fails open when a detector throws
keeps warning text secret-free
Step 2: Run shell tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/unit.test.ts
Expected: FAIL with missing exports from __test or missing modules.
Step 3: Implement types and safety helpers
In src/types.ts, define exported types for:
LeaksSettings with only regex: CustomRegexInput[]
CustomRegexInput with pattern?: unknown, label?: unknown, and index signature for unsupported fields
WarningRecord with code, message, severity
SpanLabel with tag, priority, source
SecretSpan with start, end, value, labels, kind, confidence, wholeSpan
RedactionResult with text, count, labels, placeholders
EngineStats with all /leaks status counts required by the spec
In src/safety.ts, implement:
isPlainObject(value: unknown): value is Record<string, unknown>
sanitizeTag(raw: string): string
isExistingPlaceholder(text: string): boolean
maskDiagnostic(input: string): string returning only safe metadata such as counts and labels
isWeakValue(value: string): boolean for booleans, nullish words, plain numbers, short strings, ordinary hostnames, ordinary URLs without credentials, references, UUIDs, and filesystem-ish paths
Step 4: Implement minimal engine shell
In src/engine.ts, implement LeaksEngine with constructor accepting settings and env, reload(cwd), redactText(text, origin), redactDeep(value, origin), restoreText(text), restoreDeep(value), clear(), and stats().
For this task, return input unchanged unless a provided test detector throws; on throw, add one warning and return original input.
Step 5: Replace index.ts with new exports
index.ts must default-export the Pi extension from src/pi.ts after Task 10 exists.
Until Task 10, export a no-op default factory that registers no hooks and export __test with LeaksEngine, helpers, and type-level constants.
Step 6: Run shell tests and verify pass
Run: mise run test -- extensions/leaks/__tests__/unit.test.ts
Expected: PASS.
collision suffix _2 when HMAC collision is forced by injectable digest function
cap 8192 mappings
overflow creates non-restorable placeholders and warns once
restore lookup replaces only exact placeholders
Step 2: Run placeholder tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/placeholders.test.ts
Expected: FAIL with missing PlaceholderStore.
Step 3: Implement PlaceholderStore
PlaceholderStore must use node:cryptorandomBytes(32) and createHmac("sha256", key) by default.
Expose constructor injection for test digest only.
Store secret -> placeholder and placeholder -> secret maps.
Reject persistence by keeping every map private to the store instance.
Expose create(value, labels), restore(text), clear(), and stats().
Step 4: Wire engine to placeholder store
LeaksEngine.redactText must call the store for selected spans.
restoreText and restoreDeep must use the store.
clear() must clear mappings and counters that spec allows to reset.
Step 5: Run placeholder tests and engine tests
Run: mise run test -- extensions/leaks/__tests__/placeholders.test.ts extensions/leaks/__tests__/unit.test.ts
Expected: PASS.
identical spans merge labels before placeholder creation
component parser span wins over enclosing exact learned value
exact learned value wins over generic regex
smallest secret-bearing span wins for non-identical overlaps
private key block keeps whole span over smaller generic matches
JWT keeps whole span over smaller component-looking matches
existing placeholders are not redacted again
adjacent spans replace correctly without index drift
Step 2: Run selector tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/selector.test.ts
Expected: FAIL with missing selectSecretSpans.
Step 3: Implement selector
Implement selectSecretSpans(text, spans) in src/selector.ts.
Sort by start, end, confidence, priority, and span length.
First remove spans inside existing placeholders.
Merge identical ranges by combined label list.
For overlaps, choose by forced whole-span kinds (private-key, jwt), then component, then exact, then custom, then built-in, then generic, then shorter length.
Return non-overlapping spans sorted descending by start for safe replacement.
Step 4: Wire selector into engine
LeaksEngine.redactText must collect candidate spans from enabled detectors, pass them to the selector, create placeholders once per selected span, and replace from right to left.
Step 5: Run selector tests and placeholder tests
Run: mise run test -- extensions/leaks/__tests__/selector.test.ts extensions/leaks/__tests__/placeholders.test.ts
Expected: PASS.
Use d regex flag internally for match indices and g for iteration.
Do not accept user-provided flags.
Warnings must use safe codes and no raw secret value text.
Step 4: Wire custom regex into engine
Engine reload must compile custom regex once.
Custom regex spans must use source custom and label from sanitized CUSTOM_REGEX or valid user label.
Step 5: Run settings and selector tests
Run: mise run test -- extensions/leaks/__tests__/settings.test.ts extensions/leaks/__tests__/selector.test.ts
Expected: PASS.
only .env, .env.local, and .env.*.local are discovered in cwd
no recursive discovery
export KEY=value parses
single quotes, double quotes, and inline comments parse correctly
sensitive key plus non-weak value learns exact value
weak/common values are ignored
public prefixes suppress key-name sensitivity only
high-confidence secret shapes under public prefixes still redact
process env uses same classifier
process env labels collapse to ENV_KEY
status never reports env var names or values
learned exact value cap 8192 stops learning and warns once
Step 2: Run dotenv tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/dotenv.test.ts
Expected: FAIL with missing dotenv learner.
Step 3: Implement dotenv parser and learner
Implement fixed file discovery with node:fs and node:path only.
Implement parseDotenv(text) with shell-compatible enough parsing for one-line assignments.
Implement sensitive-key matching that is case-insensitive, treats _ and - as equivalent, and allows numeric suffixes.
Implement public-prefix suppression for PUBLIC_, NEXT_PUBLIC_, and VITE_.
Implement exact value cap 8192 and warning-once behavior.
Step 4: Wire learning into engine reload
LeaksEngine.reload(cwd, rawSettings, env) must load fixed dotenv files and process env.
Learned values must produce exact-value spans with dotenv key tag or ENV_KEY tag.
Credentialed URLs must be delegated to Task 6 component parsing before whole-value learning.
Step 5: Run dotenv and placeholder tests
Run: mise run test -- extensions/leaks/__tests__/dotenv.test.ts extensions/leaks/__tests__/placeholders.test.ts
Expected: PASS.
credentialed URL password redacts while username, host, db name, and scheme remain visible
sensitive query parameter value redacts while parameter name remains visible
URL without credentials is not secret even for DATABASE_URL, REDIS_URL, or MONGO_URL
Authorization: Bearer <value> redacts token only
Authorization: Basic <value> redacts credential only
X-API-Key: <value> redacts value only
Cookie: session=<value>; theme=dark redacts sensitive cookie only
assignments in env, properties, YAML, JSON, TOML, INI, HCL, XML-ish, and shell-ish text redact value only
shell command containing a header redacts the header value without redacting whole command
JWTs remain whole-token spans
private keys remain whole logical secret spans
Step 2: Run structure tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/structures.test.ts
Expected: FAIL with missing structure parsers.
Step 3: Implement component parsers
Implement functions that return SecretSpan[] with source structure:
findCredentialedUrlSpans(text)
findSensitiveQuerySpans(text)
findHeaderSpans(text)
findCookieSpans(text)
findAssignmentSpans(text)
Use URL where full URL parsing succeeds.
For text fragments and shell snippets, use bounded regexes with match indices.
Never return a whole shell command span.
Step 4: Wire component parsers before exact learned values
Engine span collection order must add component spans before exact learned values.
Dotenv/env URL values must learn parsed secret components instead of whole URL when parsing succeeds.
Step 5: Run structure, dotenv, and selector tests
Run: mise run test -- extensions/leaks/__tests__/structures.test.ts extensions/leaks/__tests__/dotenv.test.ts extensions/leaks/__tests__/selector.test.ts
Expected: PASS.
generic sensitive-key assignments including every key name listed in spec
Create negative controls for:
arbitrary account IDs
customer IDs
org IDs
project IDs
hostnames
domains
broad opaque keys named lineage and value
SSH public keys
public certificates
Step 2: Run detector tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/detectors.test.ts
Expected: FAIL with missing or incomplete built-in detectors.
Step 3: Implement detector definitions
In src/detectors.ts, export precompiled detector objects.
Each detector must define id, tag, family, regex, optional group, confidence, and whole-span kind.
Precompile regexes once at module load.
Avoid broad entropy-only detectors.
Private key armors must redact whole logical secret values; boundary text becomes tags only.
JWTs must redact whole token.
Step 4: Wire built-ins into engine
Engine must run structure parsers, learned exact values, custom regex, and built-ins as separate sources, then selector decides overlaps.
Built-in detector failures must fail open for that detector pass, warn once, and not block Pi.
Step 5: Run detector and false-positive-related tests
Run: mise run test -- extensions/leaks/__tests__/detectors.test.ts extensions/leaks/__tests__/structures.test.ts
Expected: PASS.
Create positive controls proving custom regex overrides negative policy and high-confidence provider-specific patterns still redact.
Step 2: Run false-positive tests and verify failure or pass
Run: mise run test -- extensions/leaks/__tests__/false-positives.test.ts
Expected before refinement: FAIL for any over-broad detector.
Expected after refinement: PASS.
Step 3: Tighten weak-value and reject logic
Refine isWeakValue, detector patterns, and selector priorities until all negatives stay visible and all positive controls redact.
Keep metadata visible aggressively.
Do not add user exclude lists.
Step 4: Run detector family tests again
Run: mise run test -- extensions/leaks/__tests__/detectors.test.ts extensions/leaks/__tests__/false-positives.test.ts
Expected: PASS.
deep traversal copies objects and does not mutate originals during redaction
cyclic object traversal terminates
object identity bounds prevent repeat work
depth 64 cap warns once and skips deeper values
bigint, symbol, function, null, number, boolean pass through
arrays and plain objects are traversed
learned-value cap 8192 is enforced
placeholder map cap 8192 is enforced
operation count is bounded by input size times rule count
precompiled rule count does not grow across redaction calls
detector throw fails open for that pass and warns once
Step 2: Run performance tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/performance.test.ts
Expected: FAIL until traversal and counters are complete.
Step 3: Implement bounded traversal
Implement recursive clone traversal with WeakMap<object, unknown> for cycles and identity.
Stop at depth 64.
Only redact string values.
Return { value, changed, count } from deep redaction.
Restore uses same traversal rules but replaces known placeholders.
Step 4: Implement operation and warning bounds
Track per-pass safe operation counters if useful for tests.
Use warning-once keys for cap overflow, depth overflow, regex failure, and detector failure.
Never include secret values in warning messages.
Step 5: Run full unit suite
Run: mise run test -- extensions/leaks/__tests__/unit.test.ts extensions/leaks/__tests__/placeholders.test.ts extensions/leaks/__tests__/selector.test.ts extensions/leaks/__tests__/settings.test.ts extensions/leaks/__tests__/dotenv.test.ts extensions/leaks/__tests__/structures.test.ts extensions/leaks/__tests__/detectors.test.ts extensions/leaks/__tests__/false-positives.test.ts extensions/leaks/__tests__/performance.test.ts
Expected: PASS.
session_start initializes settings, dotenv/env learning, status
context redacts message copies and does not mutate originals
before_provider_request redacts final provider payload authoritatively
provider authentication headers remain present
tool_call restores placeholders in mutable tool args before local execution
message_end restores placeholders in finalized assistant messages
no mappings are persisted through session entries
no tools are registered by leaks
only slash command leaks is registered
Step 2: Run harness tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/harness.test.ts
Expected: FAIL until Pi adapter exists.
Step 3: Implement Pi adapter
In src/pi.ts, default-export a factory taking ExtensionAPI.
Create one LeaksEngine per extension instance.
Register handlers for session_start, context, before_provider_request, tool_call, and message_end.
Do not call appendEntry.
Do not register tools.
Register command leaks only.
Use ctx.cwd for dotenv discovery.
Use settings from the runtime settings API when available and fallback to .pi/settings.json only if the current project is trusted or the harness has no settings API.
Step 4: Replace index.ts
index.ts must import the factory from src/pi.ts, export it as default, and export __test internals used by tests.
Step 5: Run harness tests
Run: mise run test -- extensions/leaks/__tests__/harness.test.ts
Expected: PASS.
Task 11: UX, Status, Commands, And Safe Diagnostics
Files:
Create: extensions/leaks/__tests__/ux.test.ts
Modify: extensions/leaks/src/pi.ts
Modify: extensions/leaks/src/engine.ts
Modify: extensions/leaks/src/types.ts
Step 1: Write UX tests
Create tests for:
one aggregate notification per provider turn with new leak values
no notification for a clean provider turn
footer/status shows enabled/on and last provider redaction count
/leaks status shows all required fields
/leaks status includes invalid regex count
/leaks status shows recent safe redaction labels
/leaks status shows latest safe placeholder tags only
process environment key names display only as ENV_KEY
/leaks reload reloads settings and dotenv/env learning
/leaks test <text> prints redacted diagnostic without secret values
/leaks clear asks for confirmation when UI can confirm
/leaks clear respects cancel
/leaks clear clears placeholder mappings when confirmed
Step 2: Run UX tests and verify failure
Run: mise run test -- extensions/leaks/__tests__/ux.test.ts
Expected: FAIL until command output is complete.
Step 3: Implement status model
Engine stats must expose:
active state
built-in rule count
custom regex count
regex warning/error count
learned dotenv/env value count
placeholder mapping count
last provider redaction count
total provider redaction count
recent safe redaction labels
latest safe placeholder tags
invalid regex count
Step 4: Implement command handlers
/leaks status formats a safe multi-line report.
/leaks reload reloads settings and learning from current cwd.
/leaks test <text> redacts the supplied local diagnostic text and reports counts, labels, and redacted output; missed secrets are possible by definition.
/leaks clear confirms when ctx.hasUI, clears mappings and volatile restore state on confirmation, and reports cancellation otherwise.
On session_start, set status to leaks on | last 0.
After each provider redaction, update status and notify once if count > 0.
Use warning severity only for faulty settings or detector failures; use info for reload/clear/test success.
Step 6: Run UX and harness tests
Run: mise run test -- extensions/leaks/__tests__/ux.test.ts extensions/leaks/__tests__/harness.test.ts
Expected: PASS.
Step 7: Commit UX
Run:
git add extensions/leaks/src/pi.ts extensions/leaks/src/engine.ts extensions/leaks/src/types.ts extensions/leaks/__tests__/ux.test.ts
git commit -m "feat(leaks): add safe status and commands"
Modify: extensions/leaks/SPEC.md only if new evidence records are explicitly desired by the user.
Step 1: Write validation batch test wrapper
Create validation-batches.test.ts that groups existing focused tests by V0-V9 labels and asserts each batch has at least one positive and one negative control where the spec requires controls.
Do not duplicate every fixture; import fixture builders from existing test files only if those builders are exported without secrets in names.
Step 2: Run validation batch tests
Run: mise run test -- extensions/leaks/__tests__/ledger.test.ts extensions/leaks/__tests__/validation-batches.test.ts
Expected: PASS.
Step 3: Run all leaks tests
Run: mise run test -- extensions/leaks/__tests__
Expected: PASS.
Modify: extensions/leaks/package.json only if description or keywords no longer match.
Test: markdown lint via repo lint task.
Step 1: Rewrite README
README must include:
mission: provider-bound plaintext redaction
threat model and non-goals
transparent local behavior and placeholder tradeoff
placeholder examples using fake values only
settings JSON with only regex
custom regex label rules
commands: /leaks status, /leaks reload, /leaks test <text>, /leaks clear
dotenv/env learning rules
false-positive policy
limitations for images, audio, binary, OCR, semantic secret-byte edits, DLP, sandboxing, permissions, repo scanning, and git history cleanup
no secret values in diagnostics guarantee
Step 2: Run README generation check only if repo requires it
Run: mise run readme -- leaks
Expected: README remains semantically aligned with manual content or generator updates it without adding unsupported settings.
If generator overwrites critical spec content, stop and ask human because build tooling conflicts with the spec.
Modify: any leaks files touched by failing checks.
Step 1: Run focused leaks tests
Run: mise run test -- extensions/leaks/__tests__
Expected: PASS.
Step 2: Run static extension checks
Run: mise run check
Expected: PASS.
Step 3: Run full CI
Run: mise run ci
Expected: PASS.
Step 4: Search for plan-forbidden placeholders in implementation
Run: grep -R "TO[D]O\|TB[D]\|secretFiles\|keywords\|exclude\|enabled" extensions/leaks --exclude=SPEC.md
Expected: no matches for unfinished-marker words or unsupported settings in runtime code; README may mention rejected settings only as rejected.
Step 5: Verify mappings are not persisted
Run: grep -R "appendEntry\|sessionManager.*append\|writeFile.*LEAK\|localStorage\|sessionStorage" extensions/leaks --exclude=SPEC.md
Expected: no runtime persistence of placeholder mappings.
Step 6: Verify secret-safe diagnostics by test names
Run: mise run test -- extensions/leaks/__tests__/ux.test.ts extensions/leaks/__tests__/settings.test.ts extensions/leaks/__tests__/performance.test.ts
Expected: PASS with tests that assert fixture secret strings are absent from diagnostics.
Custom regex capture semantics: zero captures full match, one capture group 1, multiple group 1 with warning; labels must match [A-Z0-9_]{1,64} or fall back to CUSTOM_REGEX.
V3
Task 4 tests capture counts and label fallback.
Built-ins
Always active high-confidence detector families cover AI, VCS/package, cloud, payment/messaging/webhook/mail, auth/OAuth/JWT/cookie/session, DB/cache URLs, private keys, and sensitive assignments.
V4
Task 7 has positive controls for each minimum detector family.
Built-ins
Credential-like IDs redact only for reliable provider-specific patterns; arbitrary account/customer/org/project IDs, hostnames, and domains stay visible.
V4/V7
Tasks 7 and 8 include explicit negative controls.
Dotenv/env
Learn exact values from fixed cwd files .env, .env.local, .env.*.local; no recursive discovery or user-configured file list.
V5
Task 5 discovery tests fixed file behavior.
Dotenv/env
Process env uses same classifier; status collapses env key names to ENV_KEY; values and names never print.
V5/V8
Tasks 5 and 11 test env learning and UX collapse.
Dotenv/env
Sensitive keys are case-insensitive with _/- equivalence and numeric suffixes; public prefixes suppress key-name sensitivity only; weak/common values ignored.
V5/V7
Tasks 5 and 8 cover key classifier and weak metadata negatives.
Dotenv/env and structures
Credentialed URL, query, header, cookie, and assignment parsing redacts only secret components while preserving safe structure.
JWTs and private key material redact as whole logical secrets; public keys and certificates remain metadata.
V6/V7
Tasks 6, 7, and 8 include whole-span positives and public-material negatives.
False positives
Metadata is leaked aggressively; no entropy-only redaction; names, hosts, domains, ordinary URLs, references, IDs, codenames, and internal domains remain visible unless custom regex matches.
V7
Task 8 negative corpus and custom-regex override tests enforce this policy.
UX and commands
Notify once per redacting provider turn, not per secret, and no notification for clean turns.
V8
Task 11 UX tests aggregate notifications.
UX and commands
/leaks status reports active state, rule counts, warning/error counts, learned count, mapping count, last/total counts, recent labels, latest tags, and invalid regex count without secret values.
V8
Task 11 implements and tests the full status model.
UX and commands
/leaks reload, /leaks test <text>, and /leaks clear operate safely; clear respects cancellation.
V8
Task 11 command tests cover reload/test/clear and confirmation behavior.
Validation ledger
Every validation batch records command, fixture class, and result; detector batches have positive and negative controls; demo corpus evidence reports only paths/key names/labels/classes/counts.
V0/V4/V7
Tasks 0 and 12 test ledger presence and batch mapping; Tasks 7 and 8 provide controls.