> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase40-session03-shared-redaction-foundation/spec.md).

# Session Specification

**Session ID**: `phase40-session03-shared-redaction-foundation` **Phase**: 40 - Claude OS v2.10.1 Semantic Port **Status**: Not Started **Created**: 2026-07-02 **Base Commit**: 21f047d314119f0dbe2f5b55a73a61dd6b986e1c

***

## 1. Session Overview

This session establishes the shared redaction layer that Phase 40 needs before adding new command, chat, MoA save, and config-write output paths. The work extends the existing `scripts/lib/sanitize.ts` owner instead of adding a Hermes-only sanitizer, then migrates current Hermes bridge redaction call sites that already expose browser-visible command output, chat output, validation warnings, or bridge errors.

The session is next because Session 01 recorded `DEC-012`, `MAP-003`, and `INV-009`, and Session 02 expanded provider/model output while proving no-leak bridge behavior. Session 03 turns those decisions into reusable code and focused tests so later endpoint sessions can consume one tested redaction contract.

This is not the command endpoint, MoA save endpoint, or chat override session. It creates the helper and adoption points those later sessions must use.

***

## 2. Objectives

1. Add shared bridge-output redaction and secret-detection helpers to `scripts/lib/sanitize.ts`.
2. Cover ANSI/CSI escapes, home and realpath home variants, key/value secrets, token shapes, emails, account IDs, user/channel/chat IDs, and long opaque strings while preserving ordinary model IDs, provider IDs, and prose.
3. Replace current Hermes admin-local secret redaction and warning detection with the shared sanitizer contract.
4. Preserve existing sanitize behavior and Phase 40 Session 02 no-leak model output behavior with focused regression tests.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase40-session01-baseline-and-port-invariants` - Provides `INV-009`, `DEC-012`, `MAP-003`, and `CLS-006` for shared redaction ownership.
* [x] `phase40-session02-models-and-provider-readiness` - Provides expanded model/provider bridge output and no-leak tests that this session must not regress.

### Required Tools Or Knowledge

* Bun 1.3.14 package/runtime baseline.
* Existing sanitizer owner in `scripts/lib/sanitize.ts`.
* Existing Hermes admin bridge redaction in `scripts/lib/hermes-admin-bridge.ts`.
* Existing focused tests in `scripts/lib/__tests__/sanitize.test.ts`, `scripts/lib/__tests__/hermes-admin-bridge.test.ts`, and `scripts/lib/__tests__/hermes-dev-bridge.test.ts`.

### Environment Requirements

* Local checkout with dependencies installed or installable through `bun install`.
* No credentials, live providers, third-party dashboards, or local Hermes installation required; tests should use temp fixtures and synthetic output.

***

## 4. Scope

### In Scope (MVP)

* AI OS maintainers get a reusable bridge-output sanitizer that removes control escapes, private paths, emails, account IDs, token/key values, and opaque secret-like strings before text reaches browser-visible bridge responses.
* AI OS maintainers get a narrow secret detector that can warn on likely secret values without flagging safe provider slugs, model IDs, normal diagnostics, or ordinary prose.
* Existing Hermes admin command/chat output redaction and persona/YAML warning detection use the shared helper instead of the local `SECRET_PATTERN`.
* Existing Hermes dev bridge no-leak behavior remains intact for model and configured-provider output.
* Focused sanitizer and bridge tests cover upstream-style command/chat/MoA/YAML samples and AI OS private-path patterns.

### Out Of Scope (Deferred)

* Adding the command endpoint - Reason: Session 05 owns the token/admin-gated command execution endpoint.
* Adding the MoA save endpoint - Reason: Session 06 owns safe local MoA persistence.
* Adding chat model/provider override payloads - Reason: Session 04 owns chat override wiring and streaming safeguards.
* Redesigning unrelated sanitizer consumers outside current bridge-output paths
  * Reason: this session must preserve existing sanitize behavior and avoid broad product-surface churn.

***

## 5. Technical Approach

### Architecture

Keep shared redaction in `scripts/lib/sanitize.ts` and build on the existing `sanitize()` home-path, name, and email behavior. Add exported helpers for bridge-output redaction and likely-secret detection, then have Hermes bridge owners import those helpers instead of retaining endpoint-local regexes.

The helpers should be conservative by default: redact clearly unsafe values and escape sequences, but avoid replacing legitimate model names such as `gpt-5.5`, provider slugs such as `openai-codex`, ordinary warnings, and short diagnostic codes. Tests should include positive and negative fixtures before and after bridge adoption so later sessions can reuse the contract with confidence.

### Design Patterns

* Shared boundary helper: Bridge code calls one sanitizer for browser-visible output instead of copying regexes.
* Narrow detector: Secret warnings rely on a reusable predicate that is strict enough to avoid provider/model false positives.
* Compatibility preservation: Existing `sanitize()` and Session 02 model no-leak behavior stay covered by regression tests.
* Existing owner mapping: Implement in current AI OS split bridge files, not upstream monolithic route or Vite middleware.

***

## 6. Deliverables

### Files To Create

| File | Purpose                                        | Est. Lines |
| ---- | ---------------------------------------------- | ---------- |
| None | No new source files expected for this session. | 0          |

### Files To Modify

| File                                                | Changes                                                                                                                                          | Est. Lines |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
| `scripts/lib/sanitize.ts`                           | Add bridge-output redaction, control-sequence stripping, and likely-secret detector helpers.                                                     | \~170      |
| `scripts/lib/__tests__/sanitize.test.ts`            | Add positive and negative fixture coverage for shared bridge redaction and secret detection.                                                     | \~180      |
| `scripts/lib/hermes-admin-bridge.ts`                | Replace local command/chat output redaction and persona/YAML secret scanning with shared helpers.                                                | \~45       |
| `scripts/lib/__tests__/hermes-admin-bridge.test.ts` | Add regression tests for shared redaction in command/chat output, stderr failure details, and validation warnings.                               | \~110      |
| `scripts/lib/hermes-dev-bridge.ts`                  | Reuse the shared detector for model/configured output safety where it can replace duplicate unsafe-output logic without changing response shape. | \~35       |
| `scripts/lib/__tests__/hermes-dev-bridge.test.ts`   | Preserve Session 02 no-leak behavior and add detector false-positive coverage for safe model/provider IDs if needed.                             | \~50       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Shared bridge-output redaction removes ANSI/CSI escapes, home paths, symlink-realpath home variants, key/value secrets, token shapes, emails, account IDs, user/channel/chat IDs, and long opaque strings.
* [ ] Non-secret provider IDs, model IDs, safe MoA preset names, short warning codes, and ordinary diagnostics survive redaction.
* [ ] Hermes admin command stdout/stderr, chat stream output, chat failure detail handling, and persona/YAML validation warnings use the shared helper.
* [ ] Existing Hermes dev bridge model/configured output no-leak behavior is preserved.
* [ ] Existing sanitize behavior used outside Hermes does not regress.

### Testing Requirements

* [ ] Unit tests cover shared redaction positive and negative cases.
* [ ] Hermes admin bridge tests cover redacted command/chat output and warning detection without leaking tokens or private paths.
* [ ] Hermes dev bridge tests prove safe model/provider IDs are not over-redacted and unsafe configured fields remain excluded.
* [ ] Focused checks pass: `bunx vitest run scripts/lib/__tests__/sanitize.test.ts scripts/lib/__tests__/hermes-admin-bridge.test.ts scripts/lib/__tests__/hermes-dev-bridge.test.ts`.
* [ ] `bun run typecheck:scripts` passes.

### Non-Functional Requirements

* [ ] No credentials, auth JSON, environment values, raw home-directory paths, prompts, transcripts, or secret-shaped strings are added to committed artifacts.
* [ ] Redaction output stays deterministic and bounded for browser-visible bridge responses.
* [ ] Later command and MoA sessions can reuse the helper without introducing a parallel sanitizer.
* [ ] No product route, public demo fixture, package metadata, asset, or docs claim changes in this foundation session.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] No upstream monolithic route or Vite middleware file copied

***

## 8. Implementation Notes

### Working Assumptions

* Shared sanitizer ownership belongs in `scripts/lib/sanitize.ts`: the Session 03 stub explicitly says to extend that file, Session 01 recorded `DEC-012` and `MAP-003`, and current Hermes bridge code already imports `sanitize()` from that module. Planning can proceed because this is the least disruptive path and matches existing ownership.
* The session should create a reusable helper and migrate existing call sites, not add future endpoints: the Session 03 stub scopes command and MoA endpoints out while naming command/chat/MoA/future bridge output as consumers of the redaction layer. Planning can proceed by creating the helper and applying it to current command/chat/persona bridge paths.

### Conflict Resolutions

* Session 03 mentions MoA save details, but Session 06 owns the MoA save endpoint. The chosen interpretation is to add MoA-style fixtures and helper coverage now, then leave actual MoA endpoint wiring to Session 06. This preserves dependency order without creating planned endpoint behavior early.

### Key Considerations

* Preserve current `sanitize()` behavior for existing non-Hermes consumers.
* Keep helper names and exports general enough for future bridge output, but do not invent a broad framework.
* Use synthetic fixture values and placeholders shorter than real key patterns in docs and session artifacts.

### Potential Challenges

* Over-redaction of provider and model IDs: Mitigate with negative tests for `openai-codex`, `googlegemini`, `gpt-5.5`, `claude-sonnet-4.6`, `openrouter`, and safe MoA names.
* Under-redaction of opaque strings and account IDs: Mitigate with positive tests for key/value secrets, token-shaped samples, email, home paths, `acct_`/`user_`/`chan_`/`chat_` identifiers, and long random strings.
* Existing tests use placeholder secret strings: Keep samples synthetic and avoid adding real key-shaped values to committed artifacts.

### Relevant Considerations

* \[P38] **Upstream ports are semantic, not wholesale**: Translate upstream redaction behavior into AI OS bridge owners instead of copying upstream route files.
* \[P38] **Local control-plane gates are defense in depth**: Bridge output redaction complements loopback, Host-header, token/admin, body-size, timeout, and safe-error gates.
* \[P21] **Do not let token-shaped strings or auth headers reach browser state or logs**: Shared redaction must remove OAuth/auth/token details from bridge output and validation warnings.
* \[P02] **Do not expose secret env values through `VITE_` variables or browser state**: Browser-facing bridge output may expose labels and presence only, never raw environment values.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Unsafe bridge output misses a token, account ID, private path, or ANSI-hidden content and leaks it into browser-visible JSON or SSE.
* The detector over-redacts legitimate provider/model IDs and breaks Session 02 model readiness behavior.
* A future bridge endpoint adds its own local regex because the shared helper contract is too narrow or unclear.

***

## 9. Testing Strategy

### Unit Tests

* Add `scripts/lib/__tests__/sanitize.test.ts` coverage for bridge-output redaction, likely-secret detection, existing sanitize behavior, and safe negative examples.

### Integration Tests

* Add `scripts/lib/__tests__/hermes-admin-bridge.test.ts` coverage for command stdout/stderr redaction, chat SSE output redaction, chat failure detail sanitization, and persona/YAML warning detection.
* Keep `scripts/lib/__tests__/hermes-dev-bridge.test.ts` no-leak coverage passing and add safe model/provider false-positive coverage if the shared detector replaces duplicate model safety logic.

### Runtime Verification

* Run focused Vitest checks for sanitizer, Hermes admin bridge, and Hermes dev bridge tests.
* Run `bun run typecheck:scripts`.

### Edge Cases

* ANSI and CSI sequences wrapped around secrets.
* Current home path, generic `/home/<user>`, `/Users/<user>`, Windows `C:\Users\<user>`, and realpath-like home aliases.
* Token/key values with `api_key=`, `token:`, `secret=`, bearer auth text, and PEM private key markers.
* Account/user/channel/chat IDs and long opaque strings.
* Safe provider/model IDs, safe warning words, MoA preset names, and ordinary prose.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase40-session01-baseline-and-port-invariants`, `phase40-session02-models-and-provider-readiness`
* Depended by: `phase40-session04-chat-overrides-and-runtime`, `phase40-session05-command-endpoint`, `phase40-session06-moa-save-endpoint`, `phase40-session13-command-ux-and-slash-actions`, `phase40-session15-ministry-config-analytics-and-save-ux`, `phase40-session18-full-validation-and-handoff`

***

## Next Steps

Run the `implement` workflow step to begin implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase40-session03-shared-redaction-foundation/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
