Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

converge machine-identity/PII redaction tables onto one shared pattern list (#7474)

[._.]/ Adam Eivye390fea53c73
diff --git a/server/lib/README.md b/server/lib/README.md
index b34f9844ec..8253de7924 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -569,7 +569,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `dispatchLabels.js` | slashdo dispatch-hint contract: `model:light/medium/heavy` + `effort:low/medium/high/xhigh/max` vocabulary, prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), the read-side inverse (`dispatchHintFromLabels` — recovers `{model, effort}` from a raw label-name list, used by branch-reconcile's per-branch routing hint), GitHub/GitLab vs Jira label formatting, optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`, and released at claim time by `formatContributorLabelReleaseCommands` — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (`volunteerClaimLabels` / `formatVolunteerClaimCommands` — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp `in-progress` and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (`planner:<model>`, `normalizePlannerId` / `resolvePlannerId` / `formatPlannerLabelGuidance` — records WHICH model wrote the plan, prefix-matched by `dispatchLabelSpec` so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (`EPIC_LABEL`/`EPIC_DECOMPOSED_LABEL` and `IN_PROGRESS_LABEL` — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional `--label` slots a rendered `issue create` example offers (`OPTIONAL_ISSUE_LABEL_FLAG_SLOTS` / `formatOptionalIssueLabelFlags` — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `MANDATORY_DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`, `MANDATORY_JIRA_DISPATCH_HINT_GUIDANCE`, `REFERENCE_WATCH_LABEL_CONTRACT`, plus the consumer-side pair `DISPATCH_HINT_READING_GUIDANCE` / `DISPATCH_HINT_FANOUT_GUIDANCE` — what the labels mean to an agent that RECEIVES them (the preloaded `open-issues` task data input) and, for an orchestrator only, how to route each sub-agent by its own issue (the swarm block); the fan-out form is the reading form plus one line, never a second copy of the vocabulary). All forge filing callers require both dispatch axes and verify labels after creation; help wanted requires specific hardware validation or valuable input from real users; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. |
| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. |
| `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. |
-| `federationSafety.js` | "Does this JSON-shaped payload carry anything that must not leave the install?" — the structured, REFUSAL-side counterpart to the scrubbers (`secretText.js`, `homePath.js`) that rewrite text for a log. `federationSafetyFindings(value, { limit })` walks every string AND every object key, returning `{ code, path, detail }` for a home/Windows path, IPv4 or IPv6 literal, `.ts.net`/`.local` host, MAC, email, phone number, labelled GPS coordinate, credential-shaped value (`scrubSecretTokens`) or credential-NAMED key (`secretKeys.js#isSecretKey` — the half no value-shape scan can see). Deliberately over-refuses rather than under-detects: a payload leaving the machine should fail on "looks like an address", and the finding names the exact JSON path to fix. `walkJsonText` / `describeJsonPath` are the reusable path-reporting walk. Pure; reads no environment. |
+| `federationSafety.js` | "Does this JSON-shaped payload carry anything that must not leave the install?" — the structured, REFUSAL-side counterpart to the scrubbers (`secretText.js`, `homePath.js`) that rewrite text for a log. `federationSafetyFindings(value, { limit })` walks every string AND every object key, returning `{ code, path, detail }` for a home/Windows path, IPv4 or IPv6 literal, `.ts.net`/`.local` host, MAC, email, phone number, labelled GPS coordinate (the shared table is `piiRedactionPatterns.js`), credential-shaped value (`scrubSecretTokens`) or credential-NAMED key (`secretKeys.js#isSecretKey` — the half no value-shape scan can see). Deliberately over-refuses rather than under-detects: a payload leaving the machine should fail on "looks like an address", and the finding names the exact JSON path to fix. `walkJsonText` / `describeJsonPath` are the reusable path-reporting walk. Pure; reads no environment. |
+| `piiRedactionPatterns.js` | `PII_PATTERNS` — the machine-identity/PII `{ code, pattern, replacement }` table shared by `federationSafety.js` (detection, via `pattern.test()`) and `services/agentContextMcp.js#redactAgentContextText` / `services/agentErrorAnalysis.js#redactFailureSnippet` (replacement, via `redactPii(text)`). One list for home/Windows paths, IPv4/IPv6, MAC, `.ts.net`/`.local` hosts, email, phone, and labelled GPS coordinates, so a correction reaches every consumer instead of drifting across independent copies (#7474). `globalPattern(pattern)` derives a global-flagged copy for a `.replace()` caller without mutating the shared (deliberately non-global) regex object. Dependency-free leaf — credential-shaped/-named checks stay in `secretText.js`/`secretKeys.js`. Pure; reads no environment. |
| `secretKeys.js` | `isSecretKey(key)` — does a payload KEY name hold a credential (`api_key`/`apiKey`/`API-KEY` all normalize to `apikey`; a trailing `Key`/`Keys` counts; short names like `auth`/`env` match only whole). The key-side half of the pair whose value side is `secretText.js#scrubSecretTokens`. Split out of `services/userActions.js` so `lib/federationSafety.js` can reach it; deliberate over-redaction (losing `tokenCount` beats shipping `refreshToken`). |
| `eidoverseFoundations.js` | Local-vs-baseline ownership for Eidoverse world foundations and the promote-candidate packaging gate (#7455). `EIDOVERSE_FOUNDATION_LAYERS` (`runtime` / `baseline` / `vernacular`, defaulting to `vernacular` so nothing is shared by omission) and `layerPromoteRefusal`; the record / input / candidate-envelope Zod schemas, where a foundation is `{ body, style }` BY CONSTRUCTION — packaging carries `body` and drops `style`, so an inheriting peer never receives its author's cosmetics, and `styleLeakFindings` REFUSES an unambiguously cosmetic key smuggled into `body` (spatial/asset keys stay allowed — they are a district template's substance). `assayEvidenceFromVerdict` folds an agent-free resilience verdict (#7460) into the evidence the gate reads, including the binding that it ran against the contribution this foundation names. `packageFoundationCandidate` and `verifyFoundationCandidate` are the one gate seen from the sending and receiving sides, over a content-addressed `fingerprint` hashed from the payload AS SENT; federation safety comes from `federationSafety.js`. Pure: callers pass `now`. |
| `eidoverseWorldDesign.js` | Immutable Eidoverse World Design V1/V2/V3 registry, override migration, semantic districts, 48-signal ceiling, and install-local asset locks for PortOS Commons. |
diff --git a/server/lib/federationSafety.js b/server/lib/federationSafety.js
index 7b0cb879c5..4f9e235d81 100644
--- a/server/lib/federationSafety.js
+++ b/server/lib/federationSafety.js
@@ -29,31 +29,13 @@
import { scrubSecretTokens } from './secretText.js';
import { isSecretKey } from './secretKeys.js';
+import { PII_PATTERNS } from './piiRedactionPatterns.js';
-// Derived from the two redaction tables already in the tree —
-// `services/agentContextMcp.js#redactAgentContextText` and
-// `services/agentErrorAnalysis.js#SNIPPET_REDACTIONS` — so this gate is not
-// weaker than what a log line already gets. Those two still own their own
-// REPLACEMENT strings; converging all three onto this list is #7474.
-const PRIVACY_PATTERNS = Object.freeze([
- // `/Users/<name>/…`, `/home/<name>/…` — the OS username by another name.
- ['home-path', /(?:^|[\s"'`(])(?:\/Users|\/home)\/[^/\s"'`]+/i],
- // `C:\Users\<name>` and any other Windows drive-absolute path.
- ['windows-path', /\b[A-Za-z]:[\\/](?:Users[\\/])?[^\s"'`]+/],
- ['ip-literal', /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/],
- // IPv6, which also matches a MAC and a `14:25:30` clock time. Both are
- // over-refusals this module accepts on purpose: the finding names the field,
- // and a timestamp belongs in a typed date field rather than loose in a body.
- ['ip-literal', /\b(?:[A-Fa-f0-9]{1,4}:){2,7}[A-Fa-f0-9]{0,4}\b/],
- // Tailscale MagicDNS and mDNS names, all labels (not just the leading one).
- ['network-host', /\b[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.(?:ts\.net|local)\b/i],
- ['mac-address', /\b[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5}\b/],
- ['email-address', /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/],
- ['phone-number', /\b\+?\d[\d ().-]{8,}\d\b/],
- // Only the LABELLED form: a bare decimal pair is indistinguishable from any
- // other two numbers, and refusing every such pair would be noise.
- ['gps-coordinate', /\b(?:latitude|longitude|lat|lon|lng)\s*[:=]\s*-?\d{1,3}(?:\.\d+)?/i],
-]);
+// The machine-identity / PII regex table itself now lives in the shared leaf
+// `piiRedactionPatterns.js` (#7474), which `services/agentContextMcp.js` and
+// `services/agentErrorAnalysis.js` also read — a correction here (a
+// multi-label host, a Windows path, IPv6) reaches every consumer instead of
+// drifting across three independently-maintained copies.
/** `a.b.0.c`, or `<root>` for a bare string handed in with no path. */
export const describeJsonPath = (path) => (path.length === 0 ? '<root>' : path.join('.'));
@@ -95,7 +77,7 @@ export function federationSafetyFindings(value, { limit = 40 } = {}) {
const findings = [];
walkJsonText(value, ({ text, path, kind }) => {
const at = describeJsonPath(path);
- for (const [code, pattern] of PRIVACY_PATTERNS) {
+ for (const { code, pattern } of PII_PATTERNS) {
if (pattern.test(text)) findings.push({ code, path: at, detail: `a ${code.replace('-', ' ')} may not cross the federation layer` });
}
if (scrubSecretTokens(text) !== text) {
diff --git a/server/lib/index.js b/server/lib/index.js
index 4ded7123c8..aa41c816a4 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -290,6 +290,7 @@ export * from './spawnCwd.js';
export * from './sshHostAlias.js';
export * from './schemaVersions.js';
export * from './secretText.js';
+export * from './piiRedactionPatterns.js';
export * from './imageClean.js';
export * from './imageFrameStats.js';
export * from './imageRgba.js';
diff --git a/server/lib/piiRedactionPatterns.js b/server/lib/piiRedactionPatterns.js
new file mode 100644
index 0000000000..6736be27f3
--- /dev/null
+++ b/server/lib/piiRedactionPatterns.js
@@ -0,0 +1,73 @@
+/**
+ * Shared machine-identity / PII pattern table for free text — the pieces
+ * `server/services/agentContextMcp.js#redactAgentContextText`,
+ * `server/services/agentErrorAnalysis.js#redactFailureSnippet`, and
+ * `federationSafety.js#federationSafetyFindings` each need to recognize a
+ * home path, network host, IP/MAC literal, email, phone number, or labelled
+ * GPS coordinate before it lands in a log line, an LLM prompt, or a
+ * federated payload. Three copies of this table drifted independently
+ * (#7474) — a fix to one (a multi-label host, a Windows path, IPv6) never
+ * reached the others. This is now the one list all three read.
+ *
+ * Two ways to use an entry:
+ * - DETECTION (`federationSafety.js`): `pattern.test(text)` as-is.
+ * - REPLACEMENT (the two services): `text.replace(globalPattern(pattern),
+ * replacement)` to rewrite every match before the text is emitted.
+ *
+ * Every `pattern` here is intentionally non-global — `federationSafetyFindings`
+ * calls `.test()` on the SAME regex object across many strings in one walk,
+ * and a global flag makes that stateful: a later call can silently miss a
+ * match because `lastIndex` didn't reset to 0. `globalPattern()` derives a
+ * fresh global copy for a `.replace()` caller instead of mutating the shared
+ * regex object.
+ *
+ * Deliberately its own dependency-free leaf (see AGENTS.md "Watch the import
+ * budget") rather than living inside `federationSafety.js`: that module also
+ * reaches `secretText.js`/`secretKeys.js` for the credential-shaped/-named
+ * checks that stay OUTSIDE this table, and this leaf must not become the
+ * vehicle that pulls those into every free-text redactor in the tree. Pure;
+ * reads no environment.
+ */
+
+export const PII_PATTERNS = Object.freeze([
+ // `/Users/<name>/…`, `/home/<name>/…` — the OS username by another name.
+ // Matches ONLY the leading path segment (not the rest of the path), so a
+ // caller can drop the username in place while keeping the rest legible.
+ Object.freeze({ code: 'home-path', pattern: /(?<=^|[\s"'`(])\/(Users|home)\/[^/\s"'`]+/i, replacement: '/$1/<user>' }),
+ // Any Windows drive-absolute path (`C:\Users\<name>\…`, `D:\secrets\…`).
+ Object.freeze({ code: 'windows-path', pattern: /\b[A-Za-z]:[\\/](?:Users[\\/])?[^\s"'`]+/, replacement: '<path>' }),
+ Object.freeze({
+ code: 'ip-literal',
+ pattern: /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/,
+ replacement: '<ip>',
+ }),
+ // IPv6, which also matches a MAC and a `14:25:30` clock time — an accepted
+ // over-redaction: the shape is rare enough in free text that collapsing it
+ // to `<ip>` costs nothing a reader needs.
+ Object.freeze({ code: 'ip-literal', pattern: /\b(?:[A-Fa-f0-9]{1,4}:){2,7}[A-Fa-f0-9]{0,4}\b/, replacement: '<ip>' }),
+ // Tailscale MagicDNS / mDNS hostnames — consume ALL leading labels so a
+ // multi-label name like `machine.tailnet.ts.net` doesn't leak `machine`.
+ Object.freeze({ code: 'network-host', pattern: /\b[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.(?:ts\.net|local)\b/i, replacement: '<host>' }),
+ Object.freeze({ code: 'mac-address', pattern: /\b[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5}\b/, replacement: '<mac>' }),
+ Object.freeze({ code: 'email-address', pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/, replacement: '<email>' }),
+ Object.freeze({ code: 'phone-number', pattern: /\b\+?\d[\d ().-]{8,}\d\b/, replacement: '<phone>' }),
+ // Only the LABELLED form: a bare decimal pair is indistinguishable from any
+ // other two numbers. Keeps the label so the redaction still reads as a
+ // coordinate rather than an unexplained placeholder.
+ Object.freeze({ code: 'gps-coordinate', pattern: /\b(latitude|longitude|lat|lon|lng)\s*[:=]\s*-?\d{1,3}(?:\.\d+)?/i, replacement: '$1=[REDACTED]' }),
+]);
+
+/** A global-flagged copy of `pattern`, safe for a `.replace()` caller to reuse. */
+export function globalPattern(pattern) {
+ return new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);
+}
+
+/**
+ * Apply every `{ pattern, replacement }` entry in `PII_PATTERNS` to `text`, in
+ * table order. Shared by both redaction consumers so a correction to the
+ * table (or the order patterns apply in) reaches both without a second copy
+ * of this loop.
+ */
+export function redactPii(text) {
+ return PII_PATTERNS.reduce((out, { pattern, replacement }) => out.replace(globalPattern(pattern), replacement), text);
+}
diff --git a/server/lib/piiRedactionPatterns.test.js b/server/lib/piiRedactionPatterns.test.js
new file mode 100644
index 0000000000..35924c006c
--- /dev/null
+++ b/server/lib/piiRedactionPatterns.test.js
@@ -0,0 +1,76 @@
+/**
+ * This table is the convergence target for #7474: three independently
+ * maintained redaction tables (`federationSafety.js`, `agentContextMcp.js`,
+ * `agentErrorAnalysis.js`) drifted apart, so a fix to one never reached the
+ * others. The regressions worth pinning here are the ones that would let
+ * that drift resume: every machine-identity/PII shape the union of the old
+ * three tables caught must still be caught by `redactPii`, and the pattern
+ * objects must stay safe for `federationSafetyFindings` to reuse across many
+ * `.test()` calls without a stateful `lastIndex` bug.
+ */
+import { describe, expect, it } from 'vitest';
+import { PII_PATTERNS, globalPattern, redactPii } from './piiRedactionPatterns.js';
+
+// One sample per CODE the table declares (not per pattern — `ip-literal`
+// covers both an IPv4 and an IPv6 entry, exercised separately below). If a
+// future entry adds a code with no sample here, this map is the thing to
+// extend — the loop below fails loudly on a missing key rather than skipping it.
+const SAMPLE_BY_CODE = {
+ 'home-path': { text: 'notes live at /Users/exampleuser/journal', leak: 'exampleuser' },
+ 'windows-path': { text: 'checkout at C:\\Users\\exampleuser\\portos', leak: 'exampleuser' },
+ 'ip-literal': { text: 'reachable at 203.0.113.5 today', leak: '203.0.113.5' },
+ 'network-host': { text: 'peer is host-example.ts.net', leak: 'host-example' },
+ 'mac-address': { text: 'interface de:ad:be:ef:00:11 up', leak: 'de:ad:be:ef:00:11' },
+ 'email-address': { text: 'reach [email protected]', leak: '[email protected]' },
+ 'phone-number': { text: 'call +1 555 010 4477', leak: '555 010 4477' },
+ 'gps-coordinate': { text: 'recorded latitude: 37.4219', leak: '37.4219' },
+};
+
+describe('PII_PATTERNS / redactPii', () => {
+ it('declares a sample for every code it exports (fixture stays in sync with the table)', () => {
+ const codes = new Set(PII_PATTERNS.map((entry) => entry.code));
+ expect(Object.keys(SAMPLE_BY_CODE).sort()).toEqual([...codes].sort());
+ });
+
+ it('redacts every code the union of the three old tables caught', () => {
+ for (const [code, { text, leak }] of Object.entries(SAMPLE_BY_CODE)) {
+ const out = redactPii(text);
+ expect(out, `code ${code}`).not.toContain(leak);
+ }
+ });
+
+ it('catches an IPv6 literal as well as IPv4 under the same "ip-literal" code', () => {
+ // Both entries share a code, so the coverage loop above only exercises
+ // one of the two patterns — pin the IPv6 side, which neither
+ // agentContextMcp.js nor agentErrorAnalysis.js redacted before #7474.
+ expect(redactPii('address fe80::1ff:fe23:4567:890a active')).not.toContain('fe80::1ff:fe23:4567:890a');
+ });
+
+ it('applies patterns in table order over one string carrying several kinds at once', () => {
+ const out = redactPii('[email protected] from /Users/alice/notes, host node.ts.net');
+ expect(out).not.toContain('[email protected]');
+ expect(out).not.toContain('/Users/alice');
+ expect(out).not.toContain('node.ts.net');
+ });
+
+ it('keeps every pattern non-global, so federationSafetyFindings can .test() it across many strings without a stateful lastIndex miss', () => {
+ // A 'g'-flagged regex object remembers `lastIndex` between calls; the
+ // second `.test()` on a matching string can come back false purely
+ // because the first call advanced past it. This is the bypass this table
+ // exists to prevent: catch it here before it reaches federationSafety.js.
+ for (const { code, pattern } of PII_PATTERNS) {
+ expect(pattern.global, `code ${code} must not carry the 'g' flag`).toBe(false);
+ }
+ const emailPattern = PII_PATTERNS.find((entry) => entry.code === 'email-address').pattern;
+ expect(emailPattern.test('[email protected]')).toBe(true);
+ expect(emailPattern.test('[email protected]')).toBe(true);
+ });
+
+ it('globalPattern derives a replace-safe copy without mutating the shared regex object', () => {
+ const homePathPattern = PII_PATTERNS.find((entry) => entry.code === 'home-path').pattern;
+ const asGlobal = globalPattern(homePathPattern);
+ expect(asGlobal.global).toBe(true);
+ expect(homePathPattern.global).toBe(false);
+ expect('/Users/alice/a and /Users/bob/b'.replace(asGlobal, '/$1/<user>')).toBe('/Users/<user>/a and /Users/<user>/b');
+ });
+});
diff --git a/server/services/agentContextMcp.js b/server/services/agentContextMcp.js
index e393d36b39..4a92307be9 100644
--- a/server/services/agentContextMcp.js
+++ b/server/services/agentContextMcp.js
@@ -4,6 +4,7 @@ import { BRAIN_SEARCH_TYPES, getBrainProjections } from './brainSearchIndex.js';
import { listContexts } from './workspaceContext.js';
import { previewLegacyExport, redactSecrets } from './legacyExport.js';
import { NAV_COMMANDS, resolveNavCommand } from '../lib/navManifest.js';
+import { redactPii } from '../lib/piiRedactionPatterns.js';
import {
AGENT_CONTEXT_DEFAULT_SCOPES,
AGENT_CONTEXT_DEFAULT_ACTIONS,
@@ -36,17 +37,7 @@ const normalizedText = (value) => String(value ?? '').replace(/\s+/g, ' ').trim(
const searchableText = (value) => normalizedText(value).slice(0, 2_000);
export function redactAgentContextText(value) {
- return cap(redactSecrets(normalizedText(value))
- .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '[REDACTED EMAIL]')
- .replace(/\b[A-Z0-9-]+(?:\.[A-Z0-9-]+)*\.ts\.net\b/gi, '[REDACTED HOST]')
- .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, '[REDACTED IP]')
- .replace(/\b(?:[A-F0-9]{1,4}:){2,7}[A-F0-9]{0,4}\b/gi, '[REDACTED IP]')
- .replace(/\b(?:[A-F0-9]{2}:){5}[A-F0-9]{2}\b/gi, '[REDACTED MAC]')
- .replace(/(?:\/Users\/|\/home\/)[^/\s]+/g, '~')
- .replace(/\b(?:\+?\d[\d ().-]{8,}\d)\b/g, '[REDACTED PHONE]')
- .replace(/\b(?:latitude|lat)\s*[:=]\s*-?\d{1,3}(?:\.\d+)?/gi, 'latitude=[REDACTED]')
- .replace(/\b(?:longitude|lon|lng)\s*[:=]\s*-?\d{1,3}(?:\.\d+)?/gi, 'longitude=[REDACTED]'),
- AGENT_CONTEXT_LIMITS.maxSummaryChars);
+ return cap(redactPii(redactSecrets(normalizedText(value))), AGENT_CONTEXT_LIMITS.maxSummaryChars);
}
export function resolveAgentContextConfig(settings = {}) {
diff --git a/server/services/agentContextMcp.test.js b/server/services/agentContextMcp.test.js
index c4fce84473..b034367a6c 100644
--- a/server/services/agentContextMcp.test.js
+++ b/server/services/agentContextMcp.test.js
@@ -42,6 +42,7 @@ vi.mock('./cosToolRegistry.js', () => ({
}));
import { AGENT_CONTEXT_LIMITS } from '../lib/agentContextValidation.js';
+import { PII_PATTERNS } from '../lib/piiRedactionPatterns.js';
import {
callAgentContextTool,
getAgentContextManifest,
@@ -166,8 +167,11 @@ describe('agentContextMcp service', () => {
}]);
const result = await callAgentContextTool('list_context', { scope: 'brain' });
const serialized = JSON.stringify(result);
- expect(serialized).toContain('[REDACTED EMAIL]');
- expect(serialized).toContain('[REDACTED IP]');
+ // Canonical redaction tokens moved to the shared table's placeholders
+ // (#7474) — the strings themselves are no longer this service's own,
+ // but the leak-proofing the assertions below check is unchanged.
+ expect(serialized).toContain('<email>');
+ expect(serialized).toContain('<ip>');
expect(serialized).not.toContain('[email protected]');
expect(serialized).not.toContain('/Users/alice');
expect(serialized).not.toContain('sk-12345678901234567890');
@@ -217,4 +221,18 @@ describe('agentContextMcp service', () => {
it('keeps redacted summaries within the advertised cap', () => {
expect(redactAgentContextText('x'.repeat(1_000))).toHaveLength(AGENT_CONTEXT_LIMITS.maxSummaryChars);
});
+
+ it('reaches codes this file never redacted before #7474 (Windows paths, .local hosts)', () => {
+ // redactAgentContextText's own regex chain (pre-#7474) had no Windows
+ // drive-path pattern and only matched `.ts.net`, not `.local` mDNS
+ // hosts — both reached an agent-context summary verbatim. It now
+ // composes lib/piiRedactionPatterns.js's full table via redactPii, so a
+ // later table addition reaches this consumer with no code change here —
+ // this pins that it does today for the codes gained by converging.
+ for (const code of ['windows-path', 'network-host']) {
+ expect(PII_PATTERNS.some((entry) => entry.code === code), `table still declares ${code}`).toBe(true);
+ }
+ expect(redactAgentContextText('checkout at C:\\Users\\exampleuser\\portos')).not.toContain('exampleuser');
+ expect(redactAgentContextText('short-host printer.local timed out')).not.toContain('printer');
+ });
});
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 750f4e2c5c..f4668738ab 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -11,6 +11,8 @@ import { addTask, updateTask } from './cos.js';
import { cosEvents } from './cosEvents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { redactOutput } from '../lib/commandSecurity.js';
+import { scrubSecretTokens } from '../lib/secretText.js';
+import { redactPii } from '../lib/piiRedactionPatterns.js';
import { stripAnsi } from '../lib/ansiStrip.js';
import { describeOllamaContextOverflow, parseOllamaContextOverflow } from '../lib/ollamaContext.js';
import { retryHoldMetadata } from '../lib/taskRetryHold.js';
@@ -40,37 +42,24 @@ const SNIPPET_MAX_CHARS = 240;
// which is useful at a glance and unreadable at full length.
const CONFIG_EXPECTED_MAX_CHARS = 120;
-// Machine-identity / network / PII fragments stripped before a captured failure
-// snippet (or any interpolated free text) lands in a human-facing — and possibly
-// federated — investigation task body. See the "Sensitive Data & Privacy" section
-// in AGENTS.md: the *shape* of the failure is what a human needs, never the live
-// hostnames, paths, addresses, or secrets pulled off the running instance.
-const SNIPPET_REDACTIONS = [
- // Home-dir paths that embed an OS username → strip the user segment only.
- // Handles both POSIX (`/Users/alice`) and Windows (`C:\Users\alice`) checkouts.
- [/[\\/](Users|home)[\\/][^\\/\s"']+/gi, '/$1/<user>'],
- // Email addresses.
- [/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '<email>'],
- // Tailscale MagicDNS / mDNS hostnames — consume ALL leading labels so a
- // multi-label name like `machine.tailnet.ts.net` doesn't leak `machine`.
- [/\b[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.(?:ts\.net|local)\b/gi, '<host>'],
- // IPv4 addresses (LAN / Tailscale / public alike).
- [/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, '<ip>'],
- // Bearer tokens and common secret-key formats.
- [/\bbearer\s+[\w.\-/+=]{12,}/gi, 'bearer <token>'],
- [/\bsk-[A-Za-z0-9\-_]{16,}/g, '<token>'],
-];
-
/**
* Redact machine identity, network info, PII, and secrets from free text before
* it is embedded in an investigation-task body. Also normalizes whitespace and
* caps length so a captured multi-line snippet stays a single readable line.
* Pure — safe to unit-test directly.
+ *
+ * The machine-identity / PII patterns (home/Windows paths, IPv4/IPv6, MAC,
+ * `.ts.net`/`.local` hosts, email, phone, GPS) live in the shared
+ * `lib/piiRedactionPatterns.js` table so a fix reaches `agentContextMcp.js`
+ * and `federationSafety.js` too (#7474), rather than drifting here alone.
+ * Credential-shaped values (bearer headers, `sk-`/`ghp_`/JWT-style tokens)
+ * go through `scrubSecretTokens`, the same leaf `federationSafety.js` uses.
*/
export function redactFailureSnippet(text) {
if (typeof text !== 'string' || !text.trim()) return '';
let out = redactOutput(text); // JSON secret key/value pairs
- for (const [re, replacement] of SNIPPET_REDACTIONS) out = out.replace(re, replacement);
+ out = scrubSecretTokens(out); // credential-shaped values pasted into free text
+ out = redactPii(out);
out = out.replace(/\s+/g, ' ').trim();
return out.length > SNIPPET_MAX_CHARS ? `${out.slice(0, SNIPPET_MAX_CHARS)}…` : out;
}
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index ad7feeb879..34de17f2f7 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -29,6 +29,7 @@ import {
INVESTIGATION_STORM_HOLD_THRESHOLD,
resolveInvestigationApproval,
} from '../lib/investigationTasks.js';
+import { PII_PATTERNS } from '../lib/piiRedactionPatterns.js';
import { detectImmediateFallbackSignal } from '../lib/aiToolkit/errorDetection.js';
import { API_ACCESS_ERROR_CATEGORIES } from './agentErrorAnalysis.js';
import { ENVIRONMENTAL_ERROR_CATEGORIES } from './taskLearning/metrics.js';
@@ -1071,6 +1072,22 @@ describe('redactFailureSnippet', () => {
expect(out.length).toBeLessThanOrEqual(241);
expect(out.endsWith('…')).toBe(true);
});
+
+ it('reaches codes this file never redacted before #7474 (phone, MAC, GPS)', () => {
+ // agentErrorAnalysis's own SNIPPET_REDACTIONS table (pre-#7474) had no
+ // phone, MAC, or GPS entries, so a bare MAC address or lat/long pair
+ // reached the investigation body verbatim. redactFailureSnippet now
+ // reads lib/piiRedactionPatterns.js's full table via redactPii, so a
+ // later addition there reaches this consumer automatically — this pins
+ // that it does today, for the codes this file gained by converging.
+ const newlyCoveredCodes = ['mac-address', 'phone-number', 'gps-coordinate'];
+ for (const code of newlyCoveredCodes) {
+ expect(PII_PATTERNS.some((entry) => entry.code === code), `table still declares ${code}`).toBe(true);
+ }
+ expect(redactFailureSnippet('nic de:ad:be:ef:00:11 reset')).not.toContain('de:ad:be:ef:00:11');
+ expect(redactFailureSnippet('call +1 555 010 4477')).not.toContain('555 010 4477');
+ expect(redactFailureSnippet('recorded latitude: 37.4219')).not.toContain('37.4219');
+ });
});
describe('analyzeAgentFailure — snippet & escalation enrichment', () => {