repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/PLAN.md

Raw

Leaks Spec Implementation Plan

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.

Plan Location: extensions/leaks/PLAN.md.


Spec Coverage Map

Spec section Planned tasks
Authority Tasks 0, 14
Mission Tasks 1, 10, 11
Core requirements Tasks 1, 2, 9, 10, 12, 13
Core model Tasks 2, 3, 9
Pi integration strategy Tasks 10, 11
Settings Task 4
Built-in detection Task 7
Dotenv and environment values Tasks 5, 6
False positives Tasks 6, 8
UX and commands Task 11
Validation ledger Tasks 0, 12, 14
Non-goals Tasks 1, 14

File Structure

Invariants For All Tasks

Task 0: Validation Ledger Baseline

Files:

Create extensions/leaks/__tests__/ledger.test.ts with this structure so V0 scope and authority are executable instead of narrative-only:

import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";

const specPath = path.resolve(import.meta.dirname, "../SPEC.md");
const spec = readFileSync(specPath, "utf8");

const expectedHeadings = [
  "Authority",
  "Mission",
  "Core requirements",
  "Core model",
  "Pi integration strategy",
  "Settings",
  "Built-in detection",
  "Dotenv and environment values",
  "False positives",
  "UX and commands",
  "Validation ledger",
  "Non-goals",
];

const batches = [
  "V0 scope",
  "V1 provider boundary",
  "V2 placeholders",
  "V3 settings",
  "V4 built-ins",
  "V5 learned values",
  "V6 component parsers",
  "V7 false positives",
  "V8 UX",
  "V9 performance/failure",
];

const sectionBatchMap = new Map<string, string[]>([
  ["Authority", ["V0 scope"]],
  ["Mission", ["V0 scope", "V1 provider boundary"]],
  [
    "Core requirements",
    ["V1 provider boundary", "V8 UX", "V9 performance/failure"],
  ],
  ["Core model", ["V2 placeholders"]],
  ["Pi integration strategy", ["V1 provider boundary"]],
  ["Settings", ["V3 settings", "V9 performance/failure"]],
  ["Built-in detection", ["V4 built-ins"]],
  [
    "Dotenv and environment values",
    ["V5 learned values", "V6 component parsers", "V7 false positives"],
  ],
  ["False positives", ["V6 component parsers", "V7 false positives"]],
  ["UX and commands", ["V8 UX"]],
  ["Validation ledger", ["V0 scope"]],
  ["Non-goals", ["V0 scope"]],
]);

const normativeMarker =
  /\b(must|must not|should|do not|never|only|requires?|required|accepted|planned|rejected|out of scope|non-goals?|always|at worst|when|on)\b/i;

function sections() {
  const result: Array<{ name: string; body: string }> = [];
  const matches = [...spec.matchAll(/^## (.+)$/gm)];
  for (let index = 0; index < matches.length; index++) {
    const match = matches[index];
    const next = matches[index + 1];
    result.push({
      name: String(match[1]),
      body: spec.slice(match.index! + match[0].length, next?.index),
    });
  }
  return result;
}

function normativeSentences(body: string) {
  return body
    .replace(/```[\s\S]*?```/g, "")
    .split(/(?<=[.!?])\s+|\n+-\s+/g)
    .map((line) => line.trim())
    .filter((line) => normativeMarker.test(line));
}

describe("leaks spec validation ledger", () => {
  it("keeps the spec section map stable", () => {
    const headings = sections().map((section) => section.name);
    expect(headings).toEqual(expectedHeadings);
  });

  it("records every validation batch in the ledger and evidence table", () => {
    for (const batch of batches) {
      expect(spec).toContain(`| ${batch}`);
    }
  });

  it("maps every normative sentence to at least one validation batch", () => {
    const misses = sections().flatMap((section) => {
      const mappedBatches = sectionBatchMap.get(section.name) ?? [];
      return normativeSentences(section.body)
        .filter(() => mappedBatches.length === 0)
        .map((sentence) => ({ section: section.name, sentence }));
    });
    expect(misses).toEqual([]);
  });

  it("keeps V0 authority and scope requirements explicit", () => {
    expect(spec).toContain("This spec is the source of truth");
    expect(spec).toContain("current implementation is a prototype/reference");
    expect(spec).toContain("Implementation must be fresh and spec-shaped");
    expect(spec).toContain("Avoid creating `extensions/leaks-ref`");
    expect(spec).toContain("Non-goals");
  });
});

Use regexes over headings and table rows; never parse or print secret fixture values.

Run: mise run test -- extensions/leaks/__tests__/ledger.test.ts Expected: PASS, because the current spec already records V0-V9 evidence.

Run:

git add extensions/leaks/__tests__/ledger.test.ts
git commit -m "test(leaks): lock spec validation ledger"

Task 1: Fresh Engine Shell And Public Types

Files:

Replace obsolete setting tests for rejected enabled, keywords, exclude, and secretFiles with tests that assert:

Required test names:

Run: mise run test -- extensions/leaks/__tests__/unit.test.ts Expected: FAIL with missing exports from __test or missing modules.

In src/types.ts, define exported types for:

In src/safety.ts, implement:

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.

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.

Run: mise run test -- extensions/leaks/__tests__/unit.test.ts Expected: PASS.

Run:

git add extensions/leaks/index.ts extensions/leaks/src/types.ts extensions/leaks/src/safety.ts extensions/leaks/src/engine.ts extensions/leaks/__tests__/unit.test.ts
git commit -m "refactor(leaks): add spec-shaped engine shell"

Task 2: Placeholder Store

Files:

Create tests for:

Run: mise run test -- extensions/leaks/__tests__/placeholders.test.ts Expected: FAIL with missing PlaceholderStore.

PlaceholderStore must use node:crypto randomBytes(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().

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.

Run: mise run test -- extensions/leaks/__tests__/placeholders.test.ts extensions/leaks/__tests__/unit.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/placeholders.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/placeholders.test.ts
git commit -m "feat(leaks): add volatile placeholder store"

Task 3: Span Selector

Files:

Create tests for:

Run: mise run test -- extensions/leaks/__tests__/selector.test.ts Expected: FAIL with missing selectSecretSpans.

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.

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.

Run: mise run test -- extensions/leaks/__tests__/selector.test.ts extensions/leaks/__tests__/placeholders.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/selector.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/selector.test.ts
git commit -m "feat(leaks): select secret spans by confidence"

Task 4: Settings And Custom Regex

Files:

Create tests for:

Run: mise run test -- extensions/leaks/__tests__/settings.test.ts Expected: FAIL with missing settings compiler.

Implement:

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.

Engine reload must compile custom regex once. Custom regex spans must use source custom and label from sanitized CUSTOM_REGEX or valid user label.

Run: mise run test -- extensions/leaks/__tests__/settings.test.ts extensions/leaks/__tests__/selector.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/settings.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/settings.test.ts
git commit -m "feat(leaks): compile safe custom regex settings"

Task 5: Dotenv And Process Environment Learning

Files:

Create tests for:

Run: mise run test -- extensions/leaks/__tests__/dotenv.test.ts Expected: FAIL with missing dotenv 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.

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.

Run: mise run test -- extensions/leaks/__tests__/dotenv.test.ts extensions/leaks/__tests__/placeholders.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/dotenv.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/dotenv.test.ts
git commit -m "feat(leaks): learn dotenv and env secret values"

Task 6: Structured Component Parsers

Files:

Create tests for:

Run: mise run test -- extensions/leaks/__tests__/structures.test.ts Expected: FAIL with missing structure parsers.

Implement functions that return SecretSpan[] with source structure:

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.

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.

Run: mise run test -- extensions/leaks/__tests__/structures.test.ts extensions/leaks/__tests__/dotenv.test.ts extensions/leaks/__tests__/selector.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/structures.ts extensions/leaks/src/dotenv.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/structures.test.ts
git commit -m "feat(leaks): redact secret structure components"

Task 7: Built-In Detectors

Files:

Create positive controls for all minimum families:

Create negative controls for:

Run: mise run test -- extensions/leaks/__tests__/detectors.test.ts Expected: FAIL with missing or incomplete built-in detectors.

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.

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.

Run: mise run test -- extensions/leaks/__tests__/detectors.test.ts extensions/leaks/__tests__/structures.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/detectors.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/detectors.test.ts
git commit -m "feat(leaks): add high-confidence built-in detectors"

Task 8: False Positive Policy

Files:

Create hand negative controls for:

Create positive controls proving custom regex overrides negative policy and high-confidence provider-specific patterns still redact.

Run: mise run test -- extensions/leaks/__tests__/false-positives.test.ts Expected before refinement: FAIL for any over-broad detector. Expected after refinement: PASS.

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.

Run: mise run test -- extensions/leaks/__tests__/detectors.test.ts extensions/leaks/__tests__/false-positives.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/safety.ts extensions/leaks/src/detectors.ts extensions/leaks/src/structures.ts extensions/leaks/src/selector.ts extensions/leaks/__tests__/false-positives.test.ts
git commit -m "fix(leaks): keep metadata visible"

Task 9: Deep Redaction, Restoration, Caps, And Failure Bounds

Files:

Create tests for:

Run: mise run test -- extensions/leaks/__tests__/performance.test.ts Expected: FAIL until traversal and counters are complete.

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.

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.

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.

Run:

git add extensions/leaks/src/engine.ts extensions/leaks/src/placeholders.ts extensions/leaks/src/types.ts extensions/leaks/__tests__/performance.test.ts
git commit -m "feat(leaks): bound redaction traversal and caps"

Task 10: Pi Provider Boundary Hooks

Files:

Replace harness tests with cases for:

Run: mise run test -- extensions/leaks/__tests__/harness.test.ts Expected: FAIL until Pi adapter exists.

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.

index.ts must import the factory from src/pi.ts, export it as default, and export __test internals used by tests.

Run: mise run test -- extensions/leaks/__tests__/harness.test.ts Expected: PASS.

Run:

git add extensions/leaks/src/pi.ts extensions/leaks/index.ts extensions/leaks/__tests__/harness.test.ts
git commit -m "feat(leaks): enforce provider-bound redaction hooks"

Task 11: UX, Status, Commands, And Safe Diagnostics

Files:

Create tests for:

Run: mise run test -- extensions/leaks/__tests__/ux.test.ts Expected: FAIL until command output is complete.

Engine stats must expose:

/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.

Run: mise run test -- extensions/leaks/__tests__/ux.test.ts extensions/leaks/__tests__/harness.test.ts Expected: PASS.

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"

Task 12: End-To-End Validation Batches V0-V9

Files:

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.

Run: mise run test -- extensions/leaks/__tests__/ledger.test.ts extensions/leaks/__tests__/validation-batches.test.ts Expected: PASS.

Run: mise run test -- extensions/leaks/__tests__ Expected: PASS.

Run:

git add extensions/leaks/__tests__/ledger.test.ts extensions/leaks/__tests__/validation-batches.test.ts
git commit -m "test(leaks): map spec validation batches"

Task 13: README And User Documentation

Files:

README must include:

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.

Run: mise run lint Expected: PASS.

Run:

git add extensions/leaks/README.md extensions/leaks/package.json
git commit -m "docs(leaks): document spec-shaped redaction"

Task 14: Final Integration Gate

Files:

Run: mise run test -- extensions/leaks/__tests__ Expected: PASS.

Run: mise run check Expected: PASS.

Run: mise run ci Expected: PASS.

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.

Run: grep -R "appendEntry\|sessionManager.*append\|writeFile.*LEAK\|localStorage\|sessionStorage" extensions/leaks --exclude=SPEC.md Expected: no runtime persistence of placeholder mappings.

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.

Run:

git status --short
git commit --allow-empty -m "chore(leaks): complete spec implementation gate"

Use the empty commit only if all implementation commits already captured file changes.

Normative Requirement Ledger

Spec area Requirement group V batch Plan coverage
Authority Treat extensions/leaks/SPEC.md as source of truth and current implementation as obsolete reference. V0 Task 0 locks spec ledger; Task 1 replaces obsolete settings/runtime assumptions; Task 14 checks rejected legacy names.
Authority Use a fresh spec-shaped implementation; overwrite index.ts, tests, and README in place; do not create extensions/leaks-ref. V0 File Structure and Tasks 1, 10, 13 replace files in place and never add a reference extension directory.
Mission Protect provider-bound plaintext while preserving provider auth headers and selected provider call ability. V1 Task 10 tests authoritative before_provider_request redaction and provider auth preservation.
Mission Keep local Pi session and tool behavior unredacted except exact placeholder round trips. V1/V2 Tasks 2, 9, and 10 implement restore maps, tool_call restore, and message_end restore.
Mission and Non-goals Exclude exfiltration guard, sandboxing, DLP, permissions, repo scanning, git cleanup, binary/OCR/image/audio redaction, and homomorphic or symbolic secret-byte editing. V0 Tasks 1, 13, and 14 document and check excluded scope; no tools or permission gates are registered.
Core requirements Normal Pi workflows remain transparent by default; local visible/session behavior preserves original values where possible. V1/V8 Tasks 10 and 11 test context copy redaction, local restoration, and non-spam UX.
Core requirements Run every provider turn and touch user/tool/assistant text fields; context redaction is opportunistic and provider payload redaction authoritative. V1 Task 10 wires context and before_provider_request and tests provider-bound payloads.
Core requirements Bound hot path by input size, rule count, match count, mapping caps, object identity, and depth 64; avoid O(n²); precompile regexes. V9 Tasks 7 and 9 precompile rules and test traversal/cap/performance bounds.
Core requirements Faulty user regex and detector failures must warn, fail open, and never prevent Pi from loading. V3/V9 Tasks 4 and 9 test unsafe input rejection, warning counters, and detector failure-open behavior.
Core requirements UX must never print classified or learned secret values; local restoration may show original values only because Pi already had them. V8 Task 11 status/command tests assert fixture secrets and env names are absent.
Core model Provider sees placeholders; local Pi keeps mappings in memory only; reload/new session/exit/clear can make placeholders unrestorable. V2/V8 Tasks 2, 10, 11, and 14 implement volatile maps, no appendEntry, and /leaks clear.
Core model Placeholder format uses tags, HMAC12, random in-memory key, collision suffix, stable same-value mapping, frozen tags, and overflow non-restorable placeholders. V2 Task 2 tests format, HMAC, stability, tag ordering/caps, collision suffix, and overflow.
Core model Tags derive from dotenv/env, custom labels, built-ins, structure components, and service/type labels, with semantic priority and caps. V2/V5/V6 Tasks 2, 5, 6, and 7 generate tags from every source and verify ordering.
Core model Select component spans before enclosing exact learned values, exact before generic regexes, smallest secret-bearing overlap, private key/JWT whole spans, and never replace inside existing placeholders. V2/V6/V7 Tasks 3, 6, 7, and 8 test selector behavior and false-positive policy.
Pi integration Use session_start, context, before_provider_request, tool_call, and message_end; do not persist mappings or register tools; register only /leaks. V1/V8 Task 10 harness tests all hooks plus no persistence/no tools/one command.
Settings Accept only leaks.regex with pattern and label; reject flags and unsupported fields; cap pattern and label lengths. V3 Task 4 settings tests cover accepted and rejected settings.
Settings Reject cheap unsafe regex constructs; faulty settings warn without breaking startup or provider requests. V3/V9 Task 4 implements heuristic rejection; Task 9 tests failure-open behavior.
Settings 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. V6/V7 Task 6 structure parser tests cover URL/header/cookie/assignment components and shell snippets.
Dotenv/env and structures 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.

Reviewer Checklist

Markdown source
File outline
# Leaks Spec Implementation Plan

> **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.

**Plan Location:** `extensions/leaks/PLAN.md`.

---

## Spec Coverage Map

| Spec section                  | Planned tasks             |
| ----------------------------- | ------------------------- |
| Authority                     | Tasks 0, 14               |
| Mission                       | Tasks 1, 10, 11           |
| Core requirements             | Tasks 1, 2, 9, 10, 12, 13 |
| Core model                    | Tasks 2, 3, 9             |
| Pi integration strategy       | Tasks 10, 11              |
| Settings                      | Task 4                    |
| Built-in detection            | Task 7                    |
| Dotenv and environment values | Tasks 5, 6                |
| False positives               | Tasks 6, 8                |
| UX and commands               | Task 11                   |
| Validation ledger             | Tasks 0, 12, 14           |
| Non-goals                     | Tasks 1, 14               |

## File Structure

- Create `extensions/leaks/src/types.ts`.
  Owns public internal types: settings, warnings, spans, labels, status, redaction result.
- Create `extensions/leaks/src/safety.ts`.
  Owns safe text helpers, label sanitization, weak-value classification, placeholder detection.
- Create `extensions/leaks/src/settings.ts`.
  Owns Pi settings loading, custom regex validation, regex compilation warnings.
- Create `extensions/leaks/src/placeholders.ts`.
  Owns HMAC placeholder creation, collision suffixing, caps, restore mapping, no persistence.
- Create `extensions/leaks/src/structures.ts`.
  Owns URL, query-param, header, cookie, and assignment component parsing.
- Create `extensions/leaks/src/dotenv.ts`.
  Owns fixed dotenv discovery, dotenv parsing, process env learning, env key collapse to `ENV_KEY`.
- Create `extensions/leaks/src/detectors.ts`.
  Owns built-in detector definitions and positive/negative detector classes.
- Create `extensions/leaks/src/selector.ts`.
  Owns span merge, priority ordering, smallest-span overlap selection, existing-placeholder exclusion.
- Create `extensions/leaks/src/engine.ts`.
  Owns redaction orchestration, deep traversal, failure-open handling, stats, status state.
- Create `extensions/leaks/src/pi.ts`.
  Owns Pi hook wiring and `/leaks` command handling.
- Replace `extensions/leaks/index.ts`.
  Export Pi extension factory and `__test` internals from the new modules.
- Replace `extensions/leaks/__tests__/unit.test.ts`.
  Keep only high-signal core engine tests or delegate to new focused test files.
- Replace `extensions/leaks/__tests__/harness.test.ts`.
  Test actual Pi hook behavior through the existing harness.
- Create focused tests under `extensions/leaks/__tests__/`: `settings.test.ts`, `placeholders.test.ts`, `structures.test.ts`, `dotenv.test.ts`, `detectors.test.ts`, `selector.test.ts`, `ux.test.ts`, `performance.test.ts`, `ledger.test.ts`.
- Replace `extensions/leaks/README.md`.
  Document behavior, threat model, settings, commands, limitations, and no secret values.

## Invariants For All Tasks

- Never print secret values in tests, expected output, README examples, notifications, logs, status, or diagnostics.
- Test fixture secret strings may exist in source tests only as controlled fixture inputs; assertions must check absence from output.
- Mappings stay in memory only; do not call `pi.appendEntry`.
- Do not add tools.
- Do not implement rejected settings: `enabled`, `keywords`, `exclude`, `secretFiles`.
- Use `mise run test -- <path>` for tests.
- Use `mise run lint` and `mise run ci` only through `mise`.

### Task 0: Validation Ledger Baseline

**Files:**

- Create: `extensions/leaks/__tests__/ledger.test.ts`
- Modify: `extensions/leaks/SPEC.md` only if the spec itself is contradictory and user approves first.

- [ ] **Step 1: Write a ledger coverage test**

Create `extensions/leaks/__tests__/ledger.test.ts` with this structure so V0 scope and authority are executable instead of narrative-only:

````ts
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";

const specPath = path.resolve(import.meta.dirname, "../SPEC.md");
const spec = readFileSync(specPath, "utf8");

const expectedHeadings = [
  "Authority",
  "Mission",
  "Core requirements",
  "Core model",
  "Pi integration strategy",
  "Settings",
  "Built-in detection",
  "Dotenv and environment values",
  "False positives",
  "UX and commands",
  "Validation ledger",
  "Non-goals",
];

const batches = [
  "V0 scope",
  "V1 provider boundary",
  "V2 placeholders",
  "V3 settings",
  "V4 built-ins",
  "V5 learned values",
  "V6 component parsers",
  "V7 false positives",
  "V8 UX",
  "V9 performance/failure",
];

const sectionBatchMap = new Map<string, string[]>([
  ["Authority", ["V0 scope"]],
  ["Mission", ["V0 scope", "V1 provider boundary"]],
  [
    "Core requirements",
    ["V1 provider boundary", "V8 UX", "V9 performance/failure"],
  ],
  ["Core model", ["V2 placeholders"]],
  ["Pi integration strategy", ["V1 provider boundary"]],
  ["Settings", ["V3 settings", "V9 performance/failure"]],
  ["Built-in detection", ["V4 built-ins"]],
  [
    "Dotenv and environment values",
    ["V5 learned values", "V6 component parsers", "V7 false positives"],
  ],
  ["False positives", ["V6 component parsers", "V7 false positives"]],
  ["UX and commands", ["V8 UX"]],
  ["Validation ledger", ["V0 scope"]],
  ["Non-goals", ["V0 scope"]],
]);

const normativeMarker =
  /\b(must|must not|should|do not|never|only|requires?|required|accepted|planned|rejected|out of scope|non-goals?|always|at worst|when|on)\b/i;

function sections() {
  const result: Array<{ name: string; body: string }> = [];
  const matches = [...spec.matchAll(/^## (.+)$/gm)];
  for (let index = 0; index < matches.length; index++) {
    const match = matches[index];
    const next = matches[index + 1];
    result.push({
      name: String(match[1]),
      body: spec.slice(match.index! + match[0].length, next?.index),
    });
  }
  return result;
}

function normativeSentences(body: string) {
  return body
    .replace(/```[\s\S]*?```/g, "")
    .split(/(?<=[.!?])\s+|\n+-\s+/g)
    .map((line) => line.trim())
    .filter((line) => normativeMarker.test(line));
}

describe("leaks spec validation ledger", () => {
  it("keeps the spec section map stable", () => {
    const headings = sections().map((section) => section.name);
    expect(headings).toEqual(expectedHeadings);
  });

  it("records every validation batch in the ledger and evidence table", () => {
    for (const batch of batches) {
      expect(spec).toContain(`| ${batch}`);
    }
  });

  it("maps every normative sentence to at least one validation batch", () => {
    const misses = sections().flatMap((section) => {
      const mappedBatches = sectionBatchMap.get(section.name) ?? [];
      return normativeSentences(section.body)
        .filter(() => mappedBatches.length === 0)
        .map((sentence) => ({ section: section.name, sentence }));
    });
    expect(misses).toEqual([]);
  });

  it("keeps V0 authority and scope requirements explicit", () => {
    expect(spec).toContain("This spec is the source of truth");
    expect(spec).toContain("current implementation is a prototype/reference");
    expect(spec).toContain("Implementation must be fresh and spec-shaped");
    expect(spec).toContain("Avoid creating `extensions/leaks-ref`");
    expect(spec).toContain("Non-goals");
  });
});
````

Use regexes over headings and table rows; never parse or print secret fixture values.

- [ ] **Step 2: Run ledger test and verify current baseline**

Run: `mise run test -- extensions/leaks/__tests__/ledger.test.ts`
Expected: PASS, because the current spec already records V0-V9 evidence.

- [ ] **Step 3: Commit ledger baseline**

Run:

```bash
git add extensions/leaks/__tests__/ledger.test.ts
git commit -m "test(leaks): lock spec validation ledger"
```

### Task 1: Fresh Engine Shell And Public Types

**Files:**

- Create: `extensions/leaks/src/types.ts`
- Create: `extensions/leaks/src/safety.ts`
- Create: `extensions/leaks/src/engine.ts`
- Replace: `extensions/leaks/index.ts`
- Test: `extensions/leaks/__tests__/unit.test.ts`

- [ ] **Step 1: Replace unit test with engine shell tests**

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.

- [ ] **Step 7: Commit engine shell**

Run:

```bash
git add extensions/leaks/index.ts extensions/leaks/src/types.ts extensions/leaks/src/safety.ts extensions/leaks/src/engine.ts extensions/leaks/__tests__/unit.test.ts
git commit -m "refactor(leaks): add spec-shaped engine shell"
```

### Task 2: Placeholder Store

**Files:**

- Create: `extensions/leaks/src/placeholders.ts`
- Create: `extensions/leaks/__tests__/placeholders.test.ts`
- Modify: `extensions/leaks/src/engine.ts`
- Modify: `extensions/leaks/index.ts`

- [ ] **Step 1: Write placeholder tests**

Create tests for:

- placeholder format `__LEAK_<TAG>[_<TAG>...]_<HMAC12>[_N]__`
- HMAC12 lowercase hex length
- random per-store key makes same value produce different HMACs across stores
- same value remains stable inside one store
- tags freeze after first mapping
- semantic priority orders tags as dotenv/env, structure, custom regex, built-in, generic
- max 6 tags per placeholder
- max 64 chars per sanitized tag
- 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:crypto` `randomBytes(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.

- [ ] **Step 6: Commit placeholder store**

Run:

```bash
git add extensions/leaks/src/placeholders.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/placeholders.test.ts
git commit -m "feat(leaks): add volatile placeholder store"
```

### Task 3: Span Selector

**Files:**

- Create: `extensions/leaks/src/selector.ts`
- Create: `extensions/leaks/__tests__/selector.test.ts`
- Modify: `extensions/leaks/src/engine.ts`
- Modify: `extensions/leaks/index.ts`

- [ ] **Step 1: Write selector tests**

Create tests for:

- 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.

- [ ] **Step 6: Commit selector**

Run:

```bash
git add extensions/leaks/src/selector.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/selector.test.ts
git commit -m "feat(leaks): select secret spans by confidence"
```

### Task 4: Settings And Custom Regex

**Files:**

- Create: `extensions/leaks/src/settings.ts`
- Create: `extensions/leaks/__tests__/settings.test.ts`
- Modify: `extensions/leaks/src/engine.ts`
- Modify: `extensions/leaks/index.ts`

- [ ] **Step 1: Write settings tests**

Create tests for:

- only `leaks.regex` is accepted
- unsupported fields on regex entries warn and are ignored
- `flags` warns and is ignored
- pattern length 512 accepted
- pattern length 513 rejected
- label `[A-Z0-9_]{1,64}` accepted
- missing label loads with `CUSTOM_REGEX` warning
- invalid label falls back to `CUSTOM_REGEX` warning
- invalid regex syntax rejected with warning
- zero captures redacts full match
- one capture redacts group 1
- multiple captures redact group 1 and warn
- unsafe regex rejection: backreference, lookaround, nested quantifier, quantified alternation, empty alternative, dot-star catchall
- warning text never includes secret fixture values

- [ ] **Step 2: Run settings tests and verify failure**

Run: `mise run test -- extensions/leaks/__tests__/settings.test.ts`
Expected: FAIL with missing settings compiler.

- [ ] **Step 3: Implement settings loader and compiler**

Implement:

- `loadLeaksSettings(raw: unknown): LoadedSettings`
- `compileCustomRegex(settings: LoadedSettings): CompiledCustomRule[]`
- `countCaptures(pattern: string): number`
- `isUnsafeRegex(pattern: string): boolean`

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.

- [ ] **Step 6: Commit settings**

Run:

```bash
git add extensions/leaks/src/settings.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/settings.test.ts
git commit -m "feat(leaks): compile safe custom regex settings"
```

### Task 5: Dotenv And Process Environment Learning

**Files:**

- Create: `extensions/leaks/src/dotenv.ts`
- Create: `extensions/leaks/__tests__/dotenv.test.ts`
- Modify: `extensions/leaks/src/engine.ts`
- Modify: `extensions/leaks/index.ts`

- [ ] **Step 1: Write dotenv/env tests**

Create tests for:

- 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.

- [ ] **Step 6: Commit dotenv/env learning**

Run:

```bash
git add extensions/leaks/src/dotenv.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/dotenv.test.ts
git commit -m "feat(leaks): learn dotenv and env secret values"
```

### Task 6: Structured Component Parsers

**Files:**

- Create: `extensions/leaks/src/structures.ts`
- Create: `extensions/leaks/__tests__/structures.test.ts`
- Modify: `extensions/leaks/src/dotenv.ts`
- Modify: `extensions/leaks/src/engine.ts`
- Modify: `extensions/leaks/index.ts`

- [ ] **Step 1: Write structure parser tests**

Create tests for:

- 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.

- [ ] **Step 6: Commit structures**

Run:

```bash
git add extensions/leaks/src/structures.ts extensions/leaks/src/dotenv.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/structures.test.ts
git commit -m "feat(leaks): redact secret structure components"
```

### Task 7: Built-In Detectors

**Files:**

- Create: `extensions/leaks/src/detectors.ts`
- Create: `extensions/leaks/__tests__/detectors.test.ts`
- Modify: `extensions/leaks/src/engine.ts`
- Modify: `extensions/leaks/index.ts`

- [ ] **Step 1: Write detector corpus tests**

Create positive controls for all minimum families:

- AI provider keys with distinctive prefixes or key context
- VCS and package-manager tokens
- cloud access keys and credential-like IDs
- payment, messaging, webhook, and mail service tokens
- auth, OAuth, JWT, cookie, and session secrets
- database and cache credentialed connection strings
- private key material: PEM, OpenSSH, PGP private, encrypted cosign, PuTTY PPK private section, age secret key, minisign secret key
- 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.

- [ ] **Step 6: Commit built-ins**

Run:

```bash
git add extensions/leaks/src/detectors.ts extensions/leaks/src/engine.ts extensions/leaks/index.ts extensions/leaks/__tests__/detectors.test.ts
git commit -m "feat(leaks): add high-confidence built-in detectors"
```

### Task 8: False Positive Policy

**Files:**

- Create: `extensions/leaks/__tests__/false-positives.test.ts`
- Modify: `extensions/leaks/src/safety.ts`
- Modify: `extensions/leaks/src/detectors.ts`
- Modify: `extensions/leaks/src/structures.ts`
- Modify: `extensions/leaks/src/selector.ts`

- [ ] **Step 1: Write false-positive tests**

Create hand negative controls for:

- branch names
- package names
- ordinary URLs
- URLs needing semantic host/path edits
- usernames
- distinguished names
- UUIDs
- short hex strings
- long non-provider hex strings without secret context
- comments and defaults
- endpoint labels
- network ranges
- environment references `$API_KEY`, `${API_KEY}`, `${{ secrets.PROD_TOKEN }}`, `process.env.API_KEY`
- private names and project codenames
- internal domains
- SSH public key
- TLS certificate block

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.

- [ ] **Step 5: Commit false-positive policy**

Run:

```bash
git add extensions/leaks/src/safety.ts extensions/leaks/src/detectors.ts extensions/leaks/src/structures.ts extensions/leaks/src/selector.ts extensions/leaks/__tests__/false-positives.test.ts
git commit -m "fix(leaks): keep metadata visible"
```

### Task 9: Deep Redaction, Restoration, Caps, And Failure Bounds

**Files:**

- Create: `extensions/leaks/__tests__/performance.test.ts`
- Modify: `extensions/leaks/src/engine.ts`
- Modify: `extensions/leaks/src/placeholders.ts`
- Modify: `extensions/leaks/src/types.ts`

- [ ] **Step 1: Write performance and traversal tests**

Create tests for:

- 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.

- [ ] **Step 6: Commit bounded engine**

Run:

```bash
git add extensions/leaks/src/engine.ts extensions/leaks/src/placeholders.ts extensions/leaks/src/types.ts extensions/leaks/__tests__/performance.test.ts
git commit -m "feat(leaks): bound redaction traversal and caps"
```

### Task 10: Pi Provider Boundary Hooks

**Files:**

- Create: `extensions/leaks/src/pi.ts`
- Replace: `extensions/leaks/__tests__/harness.test.ts`
- Modify: `extensions/leaks/index.ts`

- [ ] **Step 1: Write harness tests for hooks**

Replace harness tests with cases for:

- extension loads in real Pi runtime
- `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.

- [ ] **Step 6: Commit Pi hooks**

Run:

```bash
git add extensions/leaks/src/pi.ts extensions/leaks/index.ts extensions/leaks/__tests__/harness.test.ts
git commit -m "feat(leaks): enforce provider-bound redaction hooks"
```

### 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.

- [ ] **Step 5: Implement footer/status notification updates**

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:

```bash
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"
```

### Task 12: End-To-End Validation Batches V0-V9

**Files:**

- Modify: `extensions/leaks/__tests__/ledger.test.ts`
- Create: `extensions/leaks/__tests__/validation-batches.test.ts`
- 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.

- [ ] **Step 4: Commit validation batches**

Run:

```bash
git add extensions/leaks/__tests__/ledger.test.ts extensions/leaks/__tests__/validation-batches.test.ts
git commit -m "test(leaks): map spec validation batches"
```

### Task 13: README And User Documentation

**Files:**

- Replace: `extensions/leaks/README.md`
- 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.

- [ ] **Step 3: Run markdown lint through repo lint**

Run: `mise run lint`
Expected: PASS.

- [ ] **Step 4: Commit README**

Run:

```bash
git add extensions/leaks/README.md extensions/leaks/package.json
git commit -m "docs(leaks): document spec-shaped redaction"
```

### Task 14: Final Integration Gate

**Files:**

- 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.

- [ ] **Step 7: Final commit**

Run:

```bash
git status --short
git commit --allow-empty -m "chore(leaks): complete spec implementation gate"
```

Use the empty commit only if all implementation commits already captured file changes.

## Normative Requirement Ledger

| Spec area                 | Requirement group                                                                                                                                                                                         | V batch  | Plan coverage                                                                                                          |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| Authority                 | Treat `extensions/leaks/SPEC.md` as source of truth and current implementation as obsolete reference.                                                                                                     | V0       | Task 0 locks spec ledger; Task 1 replaces obsolete settings/runtime assumptions; Task 14 checks rejected legacy names. |
| Authority                 | Use a fresh spec-shaped implementation; overwrite `index.ts`, tests, and README in place; do not create `extensions/leaks-ref`.                                                                           | V0       | File Structure and Tasks 1, 10, 13 replace files in place and never add a reference extension directory.               |
| Mission                   | Protect provider-bound plaintext while preserving provider auth headers and selected provider call ability.                                                                                               | V1       | Task 10 tests authoritative `before_provider_request` redaction and provider auth preservation.                        |
| Mission                   | Keep local Pi session and tool behavior unredacted except exact placeholder round trips.                                                                                                                  | V1/V2    | Tasks 2, 9, and 10 implement restore maps, `tool_call` restore, and `message_end` restore.                             |
| Mission and Non-goals     | Exclude exfiltration guard, sandboxing, DLP, permissions, repo scanning, git cleanup, binary/OCR/image/audio redaction, and homomorphic or symbolic secret-byte editing.                                  | V0       | Tasks 1, 13, and 14 document and check excluded scope; no tools or permission gates are registered.                    |
| Core requirements         | Normal Pi workflows remain transparent by default; local visible/session behavior preserves original values where possible.                                                                               | V1/V8    | Tasks 10 and 11 test context copy redaction, local restoration, and non-spam UX.                                       |
| Core requirements         | Run every provider turn and touch user/tool/assistant text fields; context redaction is opportunistic and provider payload redaction authoritative.                                                       | V1       | Task 10 wires `context` and `before_provider_request` and tests provider-bound payloads.                               |
| Core requirements         | Bound hot path by input size, rule count, match count, mapping caps, object identity, and depth 64; avoid O(n²); precompile regexes.                                                                      | V9       | Tasks 7 and 9 precompile rules and test traversal/cap/performance bounds.                                              |
| Core requirements         | Faulty user regex and detector failures must warn, fail open, and never prevent Pi from loading.                                                                                                          | V3/V9    | Tasks 4 and 9 test unsafe input rejection, warning counters, and detector failure-open behavior.                       |
| Core requirements         | UX must never print classified or learned secret values; local restoration may show original values only because Pi already had them.                                                                     | V8       | Task 11 status/command tests assert fixture secrets and env names are absent.                                          |
| Core model                | Provider sees placeholders; local Pi keeps mappings in memory only; reload/new session/exit/clear can make placeholders unrestorable.                                                                     | V2/V8    | Tasks 2, 10, 11, and 14 implement volatile maps, no `appendEntry`, and `/leaks clear`.                                 |
| Core model                | Placeholder format uses tags, HMAC12, random in-memory key, collision suffix, stable same-value mapping, frozen tags, and overflow non-restorable placeholders.                                           | V2       | Task 2 tests format, HMAC, stability, tag ordering/caps, collision suffix, and overflow.                               |
| Core model                | Tags derive from dotenv/env, custom labels, built-ins, structure components, and service/type labels, with semantic priority and caps.                                                                    | V2/V5/V6 | Tasks 2, 5, 6, and 7 generate tags from every source and verify ordering.                                              |
| Core model                | Select component spans before enclosing exact learned values, exact before generic regexes, smallest secret-bearing overlap, private key/JWT whole spans, and never replace inside existing placeholders. | V2/V6/V7 | Tasks 3, 6, 7, and 8 test selector behavior and false-positive policy.                                                 |
| Pi integration            | Use `session_start`, `context`, `before_provider_request`, `tool_call`, and `message_end`; do not persist mappings or register tools; register only `/leaks`.                                             | V1/V8    | Task 10 harness tests all hooks plus no persistence/no tools/one command.                                              |
| Settings                  | Accept only `leaks.regex` with `pattern` and `label`; reject `flags` and unsupported fields; cap pattern and label lengths.                                                                               | V3       | Task 4 settings tests cover accepted and rejected settings.                                                            |
| Settings                  | Reject cheap unsafe regex constructs; faulty settings warn without breaking startup or provider requests.                                                                                                 | V3/V9    | Task 4 implements heuristic rejection; Task 9 tests failure-open behavior.                                             |
| Settings                  | 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.                                                                           | V6/V7    | Task 6 structure parser tests cover URL/header/cookie/assignment components and shell snippets.                        |
| Dotenv/env and structures | 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.                                 |

## Reviewer Checklist

- V0 scope: spec authority honored; obsolete prototype treated as reference only; non-goals excluded.
- V1 provider boundary: both `context` and `before_provider_request`; provider auth preserved; local restore hooks present.
- V2 placeholders: HMAC, tags, caps, collision suffix, restore, stability, no persistence.
- V3 settings: only `regex`; unsafe patterns rejected; warnings safe.
- V4 built-ins: minimum detector families covered by positive and negative controls.
- V5 learned values: fixed dotenv files and process env classifier; caps; env key collapse.
- V6 component parsers: URL/header/cookie/assignment components preserve safe structure.
- V7 false positives: metadata remains visible; no entropy-only redaction.
- V8 UX: safe status, reload, test, clear, aggregate notifications.
- V9 performance/failure: precompile, cap, depth bound, cycle safety, fail-open warnings.