Commit Graph
76 Commits
Author SHA1 Message Date
yetone e8d42c02db gateway: a masked request tells the model its placeholders are used as written (treeMan)
treeMan on Discord: with masking on, weaker models refuse to search
with a {{NAME_xxxxxxxx}} placeholder, ask to verify it, or rewrite it as
"an example name", which breaks long tasks. A request in which masking
swapped a value (maskHits.n > 0) now carries one short note, on each try:

  Values written like {{NAME_ab12cd34}} are placeholders for real values.
  Use them exactly as written, in replies and in tool calls alike: they
  are filled in with the real values before anything runs. Don't ask to
  verify them, and don't replace them with examples.

It names neither magpie nor a vendor or client (TestPlaceholderNoteIsNeutral
fails on magpie, Codex, Claude, a vendor's name, "provider", "gateway"...).
Its example uses a '1', outside the placeholder alphabet, so it is never
taken for a real placeholder or restored.

Where: where placeholders first appear, so it is new text the first time
and the same text on every later turn (the cached prefix holds). In the
instructions when they or the tools hold one (Anthropic system's last
block, Chat's first system/developer message, Gemini systemInstruction's
parts); otherwise on the earliest message that holds one, as a block or
part after its content (a string content becomes [text, note] blocks on
Anthropic, a paragraph on Chat), and on Responses as a developer message
after that item and the tool outputs following it. Responses
`instructions` (Codex's base_instructions) is never touched. A note
appended after text starts with a blank line, so a translator that joins
blocks (Anthropic to Chat) keeps it apart from the user's words.

Not added:
- a Claude subscription: the bridge puts the caller's instructions into
  the run's first message, which Anthropic classifies; text added there is
  risk for no gain;
- a ChatGPT/Codex sign-in (Account.Agent codex); Codex's own turns on
  codexUpstreamOn don't pass this loop either;
- a Responses turn with previous_response_id: the note would pile up in
  the stored conversation.
count_tokens counts without it.

A first version put the note in the system prompt. The full suite showed
TestMaskedConversationKeepsItsCachedPrefix red (a secret first found in a
tool output changed the system at turn 1 and rewrote the cache), hence
the first-appearance placement.

Run (mote, through mote-run):
- go test ./internal/gateway ./internal/redact -run
  'TestPlaceholderNote|TestMaskedRequestTold|TestMaskedConversation|
  TestUnredacted|TestRedacted|TestMask|TestMiddlewareThroughGateway': ok.
- Full suite at 46bdbad8f (-timeout 45m, log kept whole): red in
  internal/gateway TestMiddlewareThroughGateway (mine: its fake echoes the
  last message, which now holds the note; the fake strips it now), and
  five tests red alone on origin/main cc81ad4ea too, filed as #4362
  (TestAntigravityTurnsCodexsGPT5ThreadAwayOnce, TestAntigravityTurnedAway*,
  TestCodexSpentGrokFailingIsTold); internal/gui TestMainWindowCorners
  (#3949). Every other package ok.
- At 79c6a487c (this change on cc81ad4ea): go test -timeout 45m
  ./internal/gateway ./internal/redact ./internal/masking/...: redact and
  masking ok; gateway red only in the five #4362 tests.
- go vet ./internal/gateway ./internal/redact on macOS, CGO_ENABLED=0
  GOOS=windows go vet ./... on mote, go vet of both in WSL (Linux): ok.
  (CGO_ENABLED=0 GOOS=linux go vet ./... stops in wails' menu_linux.go on
  main too, so Linux was vetted natively.)

Broken by hand:
- note always in Anthropic's system (`if true ||`):
  TestMaskedConversationKeepsItsCachedPrefix, TestPlaceholderNotePlaces,
  TestMaskedRequestTold and the TestUnredacted* echo tests red.
- wiring off in serve: TestMaskedRequestTold red.
- the claude/previous_response_id skips removed:
  TestPlaceholderNoteNotOnClientPaths red.

Not tried: no real vendor or weak model was run with the note, so whether
it stops the refusals treeMan saw is not measured; no real Claude
subscription or Codex sign-in request (both skipped by design).
2026-10-30 14:08:22 +08:00
yetone 7632e1be1d redact: a text sent on a route goes on it as it went, the model's late finds too (vvrfxyz on X)
vvrfxyz on X: "脱敏功能是不是会降低缓存命中率 我开了脱敏后 dsh命中率暴跌".

Cause: the local model (AstrLink Guard, on by default) is waited for
2s a request (masking's defaultWait). A tool's output it hasn't read
by then goes with the rules' masking alone (pii.Partial). On the next
turn the model has read it, finds the names in it, and the same history
text now goes with {{PERSON_…}} in it. Everything from that message on
is a new prompt to the vendor, so its prefix cache misses. 50f52b540
(10-23) kept the known values of a text sent before as they went, but
not the model's finds.

Reproduced with real dsh 0.2.1-rc.2 (headless profile, sandbox HOME):
three turns in one session (read team.md, customers.csv and
notes/standup.md; check contracts.md; summarise the customers) through
a sandbox magpie with masking and the default model on, to a recording
Chat Completions upstream. dsh's own request bodies were recorded and
replayed in order, 3s apart, through a fresh sandbox magpie (found
cache cleared) on Linux (WSL2 magpie-desktop, -tags nogui).
- Old (origin/main without this change): "the local model read 5 of a request's
  7 texts in 2s". At request 7, message 6 (customers.csv's tool output)
  changed at byte 252: "1000,Fatima Rossi,Client 0 GmbH" became
  "1000,{{PERSON_2rmvxto6}},Client 0 GmbH". 4,793 of that request's
  18,380 history bytes were sent as before (26%). Over the whole
  conversation 97,815 of 111,402 resent bytes (87.8%) were the same.
  It happened on both runs.
- New: 108,378 of 108,378 (100%), the same Partial in the log.
- On mote (M5 Pro, CoreML) the model read everything inside 2s. Old
  code kept 100% of the prefix over the same 3 turns, and after a
  restart of magpie too (suspect 3, the key and the in-memory maps,
  was not the cause). Suspects 1 (known values) and 4 (re-encoding)
  were not the cause either: every other request kept its prefix byte
  for byte.

Fix:
- redact: sentKnownSpans becomes sentSpans. It remembers, per text and
  options, both the known values and the model's finds the text first
  went with (sentModel, sentKnown). The key now includes Options.Route,
  and for the model also the threshold, whether there is a model, and
  NamesByModel.
- learnLate: what the model finds in such a text since is made known
  (placeholder, scores) without being put in the text, so new text has
  it masked as before.
- The gateway gives masking each request's route (maskedFor,
  masking.WithRoute): the providers its model, the model's fallbacks or
  a group's members are served by, the same set unredactedRoute walks.
  Codex's own sign-in passes "codex", or the account's provider.
- A request with no route (search, embeddings, a text prompt) keeps
  the model's finds of now, and its known values as before.

Trade-off: a name the model reads late in a text sent before keeps
going as written on that route. That route's vendor was sent it as
written already. Within a route of several providers (fallbacks, a
group), a member that wasn't the first to get it may be sent it in
that form, as it could have been on the first turn's failover. In the
Linux replay, customers.csv's ~110 names stay as written on later
turns, where old code masked them from turn 2 on. The new turns'
masking is unchanged (the same placeholder counts in messages 9, 12
and 14). Another route, never sent the text, gets it masked with what
is known and found now. That is stricter than before for known values,
which were kept whatever the vendor. The alternative, waiting for the
model before any text goes, is what defaultWait was cut to 2s to stop
(shensmart, 10-28).

Tests:
- TestModelReadingLateKeepsTheSentPrefix (internal/masking): a model
  that reads a text only after its first request. Turn 2's history must
  be byte-identical, the name masked in new text, and masked on another
  route and with no route.
- TestMaskedPrefixKeptOnlyOnItsRoute (internal/gateway): a system
  prompt kept as written on its provider, masked on another.
- Broken by hand on mote, each red:
  - sentModel not remembered: "turn 2 rewrote message 2";
  - learnLate removed: "the new turn has the name the model found as
    written";
  - maskedFor returning ctx without a route: "another provider, never
    sent it, got the value as written".
  Each was green restored. TestMaskedConversationKeepsItsCachedPrefix
  and TestSentTextKeepsItsMasking stay green.

What was run, at this commit on origin/main 4b4c4a806, on mote
(after rebasing on e863f520c, which touches internal/gateway: gofmt, vet
of gateway/masking/redact, redact and masking whole, and gateway -run
"Mask|Redact|Sent|Effort|Route" ok again):
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- Targeted at this head: go test ./internal/redact ./internal/masking
  ./internal/gateway (ok), with the two new tests and
  TestMaskedConversationKeepsItsCachedPrefix, TestSentTextKeepsItsMasking.
- Full suite (go test -timeout 45m ./...) was still running on mote at
  push (load ~110, other sessions), pushed per the ship-at-once rule; its
  result goes on the release and any red gets its own issue.
- GUI suite not run: no GUI file, API or string changed.

Not tried: vvrfxyz's own machine and vendor (DeepSeek's real cache_hit
counts), and Windows.
2026-10-30 10:26:50 +08:00
yetone 95b40fb2f1 redact: a URL's password that is also its user, host or database goes as written (xuanwo on X)
xuanwo on X, 10-29: "我的很多项目名被识别成了 password,一天脱敏了 26M
次". The screenshot: a Codex summary where geodatafusion went as a
made-up word (bsssqojjdekwi) in every path, in rust/geodatafusion/,
geodatafusion.toml and cargo test -p geodatafusion; GEODATAFUSION in
capitals was left. Settings listed it under Passwords.

Cause, reproduced with the repo's own bytes: the geodatafusion repo's
PostGIS test (testing/postgis/README.md, rust/geodatafusion/tests/
postgis/README.md, .github/workflows/postgis-differential.yml) runs on
  postgresql://geodatafusion:geodatafusion@127.0.0.1:55432/geodatafusion
The URL PASSWORD rule (user:password@) took the password. Once masked a
value is known (knownSpans) and is masked wherever it is written, case
as written, so the project's name went as a password in every request
for the rest of the run. Neither the local model nor b9f1fcddd's
words-only check is involved: this is a rule's find, which is known
whatever its look. Other projects set up the same way (name:name@)
each made their name known.

The rule: masking a URL's password hides nothing when the same URL has
it written as its user, a label of its host or a part of its path
(postgres:postgres@, root:root@, guest:guest@, app:shopdb@…/shopdb,
geo:geo@db/geo). hiddenInURL leaves such a password as written, so it
is never known. Whole parts only: geo:geod@…/geodb is masked. A
password not written elsewhere in its URL is masked as before, whatever
it looks like, there and as known everywhere after
(postgresql://geo:opensesame@…: opensesame is masked in a later path
too). This is scoped by where the value is in the URL, not by how it
looks: a URL in a tool call's arguments is judged the same way, and a
random password there (Tr0ub4dor3) is masked.

What the user gets: after updating (a restart forgets every known
value, the store is in memory) the project's name goes as written. The
user's ask, choosing what is masked without one exception at a time,
is already in Settings › Privacy: each kind (Passwords among them) has
Mask / Warn / Block, and Warn sends that kind as written while still
recording it; Never mask takes values. Yayoi_no_yume asked under the
same tweet for a switch per kind; that row is it. No new control is added: an Off
that records nothing would be a fourth state beside Warn with little
more to it.

The 26M: maskrec counts every place masked in every request's whole
body, and an agent resends its history each turn, so one known word in
a long Codex history was counted hundreds of times a turn. Filed as
#4193 (with the unmeasured CPU question of MaskJSON having no memo).

Tests: url_password_test.go.
TestURLPasswordWrittenElsewhereGoesAsWritten: the repo's README and
workflow lines, then the screenshot's summary text, then a Codex body
with the URL in exec_command's arguments and "cargo test -p
geodatafusion", each unchanged with 0 masked; postgres:postgres@,
root:root@, guest:guest@, app:shopdb@…/shopdb, redis://:cachebox@cachebox,
geo:geo@db/geo unchanged. TestURLPasswordStillMasked: hunter2pass,
geo:opensesame@…/geodata, geo:geod@…/geodb and redis's r3disPass
masked; Tr0ub4dor3 in a tool call's arguments masked; opensesame
masked again as known in a later path.

Broken by hand: the rule without hiddenInURL: red, both URL lines
masked, the summary 9 places masked as the screenshot shows
(/f745/<made-up>, rust/<made-up>/tests, -p <made-up>), the body 4, and
each of the six same-word URLs masked; green with it.

Run (mote, at 033b17baf + this commit): go test -run
'URLPassword|URLUserinfo|Known' ./internal/redact ok; gofmt -l clean;
GOOS=linux and GOOS=windows go vet ./internal/redact ok. Full suite
go test -count=1 -timeout 45m ./... started on mote; at push time it was
still in internal/agent and internal/gateway (load 60 to 225 from four
suites of other sessions), internal/access ok so far. Shipped without
waiting on it, as the owner asks; any red it names gets its own issue.

Not tried: a real Codex session with the geodatafusion repo; no GUI
change, so no GUI run.
2026-10-29 15:53:04 +08:00
yetone 2eee5d6d1e redact: a folder or a program's word is no one's name or address (kekek711 on X)
kekek711 on X, 10-29: "node_modules给识别成姓名了". With the local
model on, node_modules went to the vendor as a placeholder of personal
data, and the agent couldn't read or list the folder.

Where it came from: the model's PERSON spans were already held to a
name's shape (personFits: no underscore, a capital; modelTakes: no
snake_case word), so a person's name can't take node_modules on main.
Its ADDRESS spans were not: modelFits only turned away an ASCII value
with a slash and no space, so node_modules, site-packages, __pycache__,
dist, vendor, "ls node_modules" and "node_modules 太" (the span running
on into the sentence) all went as {{ADDRESS_…}}, which Settings lists
under the same model as names ("姓名、地址"). A lone SECRET span over
"node_modules/" or "__pycache__" also went, as b9f1fcddd's wordsOnly
didn't read a folder's slash or Python's underscores.

- programWords: a value with an underscore, or Latin letters in lower
  case with no digit, is a program's words; an ADDRESS that is one goes
  as written. A real address has its number or capitals (42 Wallaby
  Way), a Chinese one its characters.
- wordsOnlyRe takes underscores around a word and a slash after it
  (node_modules/, __pycache__), so a secret the model alone found there
  goes as written unless assigned to a secret's name, as b9f1fcddd does.

Neither real model labels node_modules in what I could give it: AstrLink
Guard (MAGPIE_GUARD_DIR) and Privacy Filter (pf-serve pf-v2 with the q8
GGUF, on mote's GPU) were run on the literal texts below and on an
ls -la, a du, a .gitignore, a Cannot find module trace and four Chinese
sentences, and found only names (John Smith, Rina Kowalczyk, and kekek
in ls -la, which personFits drops). The reporter gave no screenshot, so
which label it had is not known; the tests drive each label over each
span with the fake model.

Tests: program_words_test.go.
TestModelLeavesProgramWords: a Claude Code body (Bash tool_use
"ls node_modules", a tool_result with node_modules/.bin/tsc, the user's
"node_modules 太大了"), each of PERSON/ADDRESS/SECRET over node_modules,
node_modules/, "node_modules 太" and "ls node_modules"; then
site-packages, __pycache__, dist, vendor, rm -rf node_modules and the
reporter's own sentence. TestModelStillMasksNamesBesideProgramWords:
Rina Kowalczyk, 42 Wallaby Way, Sydney and 建国路88号 beside the folder
are masked still (3 of 3).

Broken by hand: the tests run with model.go at a14f5c9c9 (the fix
stashed): red, 15 failures (ADDRESS over every span and word, SECRET
over node_modules/ and __pycache__); green with it.

Run (mote-run, this tree on a14f5c9c9): gofmt -l internal/redact
internal/pii clean; go vet ./internal/redact ./internal/pii/...; go test
./internal/redact ./internal/pii/... ./internal/masking ok.
Then go test -timeout 45m over the packages that use redact: gateway,
otlp, settings, sessions, redact, masking, pii/... ok; gui red on
TestCoreScriptBudget (#4133, 1531446 > 1530861, main's) and
TestMainWindowCorners/macOS_26_SDK (#3949, main's on macOS 27); this
change touches no gui file. GOOS=linux and GOOS=windows go vet
./internal/redact ./internal/pii ok. Not run: the full ./... suite (mote
was busy with another session's suite).

Not changed: a SECRET span with other words in it ("ls node_modules",
"node_modules 太") still goes as a secret: a passphrase is lower-case
words with spaces too, and the shape doesn't tell the two apart.
2026-10-29 09:20:38 +08:00
yetone b9f1fcddde redact: words in lower case the model took for a secret go as written unless assigned to a secret's name (dniray on Discord)
dniray, on v0.1.1976 after 300b7eee0: drizzle-orm still went out as
{{SECRET_o2tu7vej}}, now in a tsup config in a Markdown fence:
  external: [/@nestjs/, 'reflect-metadata', 'rxjs', 'mysql2', 'drizzle-orm'],
v0.1.1932 and v0.1.1976 each let a package's name go in more places
(import lines, manifests, errors, installs, pins); a list in a build
config was none of them, and the places can't all be listed.

Cause, reproduced with the real model on mote: AstrLink Guard finds
drizzle-orm as a secret on that line alone at 0.515 (and pieces of it,
"zzle-orm" 0.755, "-orm", which modelFits already drops, elsewhere in
the block). Under Guard's default slider (0.8) it isn't masked; with the
slider at or below 0.515 origin/main masks it ('{{SECRET_…}}'), and once
masked it is known and masked in the whole block and every later
request. Privacy Filter finds nothing in it.

The rule, by shape instead of place:
- modelFits: a secret the model found that is lower-case letters only,
  words joined by - . or _ (wordsOnly: drizzle-orm, reflect-metadata,
  lodash.merge) is masked only where it is assigned to a secret's name
  (assignedSecret: a name holding password/pass/pwd/key/token/secret/
  credential or 密码/密钥/令牌, then =, :, is/was, 是/为, right before
  it). A list's comma is no assignment: 'jsonwebtoken', 'drizzle-orm'
  is not cued, where secretCued would take the token in it.
- knownSpans: a known SECRET of that shape whose score is the model's
  alone (scores < ruleFound) is masked again only where assigned. A
  rule's find, the user's rules' and a value with a digit, a capital or
  a symbol are matched as before. magpie's own SECRET rules already ask a
  digit of a value after password= (secretValue).
- Old data: the known store is in memory only, so updating (a restart)
  forgets a remembered drizzle-orm anyway; in a magpie still running,
  the knownSpans check lets one the model remembered go on the next
  request with no action from the user.
- Cost: a lower-case-letters-only password the model alone found under a
  password's name stays masked there, but where it comes back with no
  name before it (an echo in prose) it now goes as written.

Tests: package_words_test.go. TestModelWordsArentSecrets: the literal
block in a user message as Markdown, in a Read tool_result with Claude
Code's line numbers, prose and the name alone, with a fake model at
0.93; red on origin/main ({{SECRET_…}} in all). TestKnownModelWordsGoAsWritten:
drizzle-orm and reflect-metadata remembered as the model's, then the
block with no model and in a body; red on origin/main; and
"DB_PASSWORD: drizzle-orm" still masked. TestWordSecretsStillMasked:
PASSWORD=opensesame, {"password": "letmeinplease"}, "the wifi password
is purplemonkey", api_key: correct-horse-battery, hunter2pass,
Zq8vR2mT6wLp, Tr0ub4dor&3xq still masked by the model; a rule's
"token 是 bluewhalesinging" masked again as known in prose.

Run, at 926ef769f + this change, on mote:
- go test -count=1 -timeout 45m ./internal/redact/... ./internal/masking/...
  ./internal/otlp/... ./internal/pii/... ./internal/sessions/...
  ./internal/settings/... ./internal/gwmw/... ./plugins/redact/...: ok
  (TestMaskEval's recordings pass unchanged, no Known entry flipped)
- go test -run "Redact|Mask|Privacy|Unredact|Known|Restore"
  ./internal/gateway ./internal/gui: ok
- gofmt -l internal/redact: clean; go vet, GOOS=linux -tags nogui and
  GOOS=windows go vet on ./internal/redact/ ./internal/masking/: ok
- the real AstrLink Guard and Privacy Filter (zzcache) over the literal
  block, a fragment, the lone line, the block in a Markdown doc and a
  .env, each also with Read line numbers, slider at 0.3: origin/main
  masks drizzle-orm in the lone line (Guard); with this change nothing
  masks it, and PASSWORD=opensesame (Guard 0.908/0.962), hunter2pass and
  the JWT secret are masked still.

Broken by hand, each red: the modelFits check off
(TestModelWordsArentSecrets, all five); the knownSpans check off
(TestKnownModelWordsGoAsWritten, both); assignedSecret always false
(TestWordSecretsStillMasked, four cued cases, and the assigned case).

Not tried: dniray's own text and slider setting (the screenshot's block
is cut off at the top); the full go test ./... and the whole gateway
and gui suites; Windows and Linux runs (vet only). No eval case added
(recordings not re-recorded).
2026-10-29 08:45:58 +08:00
yetone 300b7eee08 redact: a package's name goes as written where it was masked before, and in manifests and errors (dniray on Discord)
dniray, on v0.1.1965 after v0.1.1932's fix: "问题还在", with
import { and, eq } from ' drizzle-orm ' still going out as
from ' {{SECRET_o2tu7vej}} '.

v0.1.1932 let the module an import loads go as written only where the
local model found it on that line (moduleAt in modelFits). A value
masked once is known (knownSpans) and masked wherever it is, with no
look at what is around it. So once the model took drizzle-orm for a
secret anywhere in a request (package.json's dependencies, a tsc
error, a sentence: none of those was exempt), the import line was
masked as known: in the same request (MaskJSON walks the texts in
order) and in every later one.

- knownSpans skips a known value where packageAt says it is a
  package's name.
- packageAt: moduleAt, plus a manifest's dependency pinned at a version
  ("drizzle-orm": "^0.36.4", workspace:*, TOML x = "9";
  dependencyAt), a folder under node_modules or site-packages, the
  module an error could not find (Cannot find module 'x', No module
  named 'x', Can't resolve 'x'; missingModuleAt), a package an install
  names (pnpm add x, npm i -D x, pip install x, cargo add x;
  installedAt, not after a --token-like flag), one pinned with @
  (x@0.36.4, lower case, not an IPv4 address; pinnedAt). A piece of a
  name (drizzle-orm of drizzle-orm/pg-core, of @acme/drizzle-orm) is
  judged as the whole name.
- moduleAt reads past an editor's line number and a diff's mark
  (codeHead): Claude Code's Read gives "     1→import drizzle from
  'drizzle-orm'", and a default import there wasn't an import line.

Tests: package_known_test.go.
TestKnownPackageNameGoesAsWrittenWhereCodeLoadsIt has the reporter's
literal line in a Claude Code tool_result after a sentence with the
name, in one Anthropic body, then alone (Mask, no model) and in a
second body: red on the old code at all three
(from ' {{SECRET_…}} '). TestModelPackageNamesInManifestsAndOutput: 22
shapes, red on the old code. TestPackageShapesKeepSecrets: a JSON key
with a non-version value, a password before @ip, a quoted secret on a
numbered line, prose with "install", a known secret in prose and on a
numbered line are masked still.

Run, at 936bdccfa + this change, on mote:
- go test -count=1 -timeout 45m ./internal/redact/... ./internal/masking/...
  ./internal/otlp/... ./internal/pii/... ./internal/sessions/...
  ./internal/settings/... ./internal/gwmw/...: ok (TestMaskEval's
  recordings pass unchanged)
- go test -run "Redact|Mask|Privacy|Unredact|Known|Restore"
  ./internal/gateway ./internal/gui: ok
- go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
  ./internal/redact/... ./internal/masking/...: ok; gofmt -l: clean
- the real AstrLink Guard and Privacy Filter on mote (zzcache), at
  their default thresholds, over 12 texts: the literal line, a
  numbered Read of a drizzle file, package.json, pnpm add, a tsc
  error, node_modules path, prose, a .env: neither model found
  drizzle-orm anywhere, and the .env's password and JWT secret were
  still masked with the change.

Broken by hand, each red: the packageAt check in knownSpans off
(TestKnownPackageNameGoesAsWrittenWhereCodeLoadsIt, all three);
codeHead off and missingModuleAt/installedAt/pinnedAt off
(TestModelPackageNamesInManifestsAndOutput, 11 cases).

Not tried: what made the model take drizzle-orm for a secret on
dniray's machine. Neither real model does on any text tried, so the
fix is held by the fake model; the known path is the one way found
that v0.1.1932's check is passed by. No eval case added (recordings not
re-recorded); the full ./internal/gateway and ./internal/gui suites;
Windows and Linux runs (vet only).
2026-10-29 08:00:53 +08:00
yetone 5a85a9836c redact: a value at the end of a tool call's arguments keeps its closing quote (xiaojiang091499 on X)
xiaojiang091499 on X (v0.1.1808): "隐私脱敏误把 Codex 工具参数结尾的引号和
花括号一起替换了,破坏了参数格式,导致会话一直报错重连". Still the case on
main before this commit.

Cause, outbound: a tool call's arguments are masked as JSON text
(MaskJSON, escaped). A span is kept out of escapes (#3022) but not inside
its JSON string, so a span that runs past the string's end took the
closing quote with it. The local model does this: Privacy Filter's
tokenizer merges a punctuation run, so in {"cmd":"export
DB_PASSWORD=Hunt3r!"} the real model's SECRET span is `Hunt3r!"`, and a
secret's edges are kept by design (#3591). Same with "the api key is
AbC…!?\"", "ship to 221B Baker Street, London.\"", "pwd=Qq123456@#\"".
A user rule like `tok-\S+` does the same. The vendor got
{"cmd":"export DB_PASSWORD={{SECRET_…}}}: arguments no longer JSON, so
Codex's turn failed and reconnected. The model is on by default since
v0.1.1858, so this hits every user from then.

Fix: inStrings (redact.go) moves each span in escaped text onto the JSON
string it starts in and ends it where that string ends. A span that is a
whole bare value (a number a rule finds, "acct": 12345678901) is kept and
its placeholder goes in quoted (span.bare); any other span outside a
string is dropped. Text that isn't valid JSON is left as before. This is the
path for Responses function_call and Chat tool_calls arguments (JSON
text); Anthropic tool_use input and Gemini functionCall args are
objects, masked string by string, so a span there never leaves its
string.

Sibling, inbound: Writer.event and restoreJSON read an event's "type" as
the walk reached it, so a Responses function_call_arguments.delta whose
"delta" key comes before "type" (as a Go map or any key-sorting proxy
writes it) had its value put back unescaped: a password with a quote in
it ended the arguments' string. typeOf now reads the type first, and the
Writer falls back to the SSE event name. Chat tool_calls and Anthropic
input_json_delta were already right (key "arguments"/"partial_json").

Tests (internal/redact/argstail_test.go):
- TestArgumentsValueAtEndKeepsQuote: the real model's four spans
  (captured from Privacy Filter on mote) and a \S+ rule, in Responses and
  Chat bodies; arguments stay JSON, the value is gone, Restore gives the
  original back.
- TestArgumentsBareValueQuoted: a bare number is masked as a string.
- TestWriterStreamArgumentsValueAtEnd: a value with a quote and a
  backslash, at the end of the arguments, split at every byte after its
  placeholder starts, through Responses deltas (delta before type),
  Chat tool_calls and Anthropic input_json_delta.
- TestRestoreJSONDeltaBeforeType: the whole-body path.

Broken by hand: without inStrings, the first two fail; with the type
read in the walk again in writer.go, the stream test fails at cuts 28-43
({"cmd":"export DB_PASSWORD=Hunt3r!"\x"}); the same in json.go fails
TestRestoreJSONDeltaBeforeType.

Real model: a probe (not committed) ran Privacy Filter on mote over 36
argument texts through MaskJSON as the gateway does; before, the
arguments were broken for each case above; after, all 36 are valid JSON
with the value masked.

Run on mote (mote-run): go test ./... -timeout 45m -count=1 at this
change on 655f8dbd1: every package ok except two reds already filed and
outside redact: internal/gui TestMainWindowCorners/macOS_26_SDK (#3949)
and internal/provider TestClaudeAccountServesModelsListedSinceItsFetch
(#3174). Rebased on 362774210/e5e2aa58e (gateway and routes only), then
internal/redact, internal/pii and internal/masking again at the pushed
head: ok. go vet ./..., GOOS=linux go vet -tags
nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build
-tags nogui, GOOS=windows go build: ok. gofmt -l: nothing.

Not tried: a real Codex session through the gateway with a masked
password; Gemini's functionCall with the real model (its args are an
object, masked string by string, never as JSON text). No docs/subsystems
page describes where spans are placed, so none changed.
2026-10-29 01:17:04 +08:00
yetone 7a79318337 redact: a package's name goes as written, an import's module first (dniray on Discord)
dniray (v0.1.1917): "脱敏会把包名给替换了", with the case
import { and, eq } from ' drizzle-orm ' going out as
from ' {{SECRET_…}} '. The SECRET came from the local model; the rules
left it. AstrLink Guard reproduces the class on mote with
require( ' jsonwebtoken ' ) -> {{SECRET_…}} and a requirements.txt
django-rest-passwordreset==1.4.0 -> {{SECRET_…}}==1.4.0; Privacy Filter
took a pnpm-lock integrity hash (sha512-…==}) for one, eating the }.

A probe of ~60 package shapes (npm scoped and pinned, Java/Android ids,
Go module paths, Python modules, purls, Debian, Cargo, Gradle, Maven,
CocoaPods, lock files) through Preview, rules alone and with both real
models, default kinds and all kinds, found these and fixed each class:

- model, any kind: the module a line of code loads is never PII
  (moduleAt): a quoted specifier after from on an import/export line or
  after } or *, import 'x', require('x'), import('x'), and unquoted
  from x import / import x / use x:: / extern crate x at a line's start.
  A from in prose ("the token from 'Zq8v…'", "copy it from Zq8v…") is
  judged as before.
- model SECRET: a name a version is pinned after (==, >=, ~=, !=, <=,
  ===; pinnedAfter); @ is left out so s3cretPass@10.0.0.5 still masks.
- model SECRET: an SRI hash (sriRe in namesThing).
- secret-named field rule (fieldAt, keyAt, modelTakes): a version or a
  range is no secret value: "js-tokens": "^4.0.0-beta.1",
  jsonwebtoken = "9.2.0-beta1", secretVersion = '2.1.0-alpha03'
  (versionValue).
- user@host (off by default): js-tokens@4.0.0: in pnpm-lock.yaml went
  as a user and a host (notPackagePin); alice@10.0.0.5 still masks.

Left as is: SECRET_PACKAGE=@acme/secret-store-v2 and
PASSWORD_LIB=passlib-1.7.4 (a value under a secret's name, not told
apart from a password), and Privacy Filter's "Dagger Hilt" as a person.

Tests: package_names_test.go. TestPackageNamesGoAsWritten (rules,
default and all kinds), TestPackagePinIsNoLogin,
TestModelPackageNamesNotMasked (dniray's literal bytes first, through
fakeModel), TestPackageNameChecksKeepRealValues (emails, an ssh host,
password=, API_KEY=, a secret-named field with a real value, alice@ip,
a model secret in prose after from, before ==, before @ip).

Run, at b692de9c8 + this change, on mote:
- go test -count=1 -timeout 45m ./internal/redact/... ./internal/masking/...: ok
- go test ./internal/otlp/... ./internal/pii/... ./internal/sessions/...
  ./internal/settings/...: ok; -run "Redact|Mask|Privacy|Unredact"
  ./internal/gateway ./internal/gui: ok
- go vet ./internal/redact/... darwin, GOOS=linux -tags nogui, GOOS=windows: ok
- gofmt -l internal/redact: clean
- probe with real AstrLink Guard and Privacy Filter (MAGPIE_EVAL_CACHE):
  every shape above as written; emails, ssh host and the author's email
  still masked.

Broken by hand, each red: moduleAt off (TestModelPackageNamesNotMasked:
drizzle-orm, reflect-metadata, jsonwebtoken), notPackagePin always true
(TestPackagePinIsNoLogin), versionValue false
(TestPackageNamesGoAsWritten), pinnedAfter off and sriRe off
(TestModelPackageNamesNotMasked).

Not tried: dniray's own text didn't make either model fire alone on
mote (the model reads context), so the fix is held by the fake-model
test and the jsonwebtoken case the real model does fire on; the eval
recordings were not re-recorded (no eval case added); the full
./internal/gateway and ./internal/gui suites.
2026-10-29 00:45:18 +08:00
yetone c2aad3db02 redact: a wallet address goes as written, and an IP as a documentation address the agent can use
0x0_air on X (10-28): with masking on, the agent stopped and asked again.
Their EVM address (0x89dfBD9b…, public) went as a secret placeholder and
the vendor's model told them to rotate it in case it was a private key;
the server IP they typed went as {{IP_…}} and the model refused to ssh
to it and asked for the real host.

- model.go: the local model's SECRET/ACCOUNT span on 0x and 40 hex
  digits (evmRe) is left as written; no rule matched it, the model's
  label did (the 0x prefix and mixed case got past hexRe). A 64-hex
  private key is masked still, and so is a 40-hex value called a key
  (secretCued).
- shape.go: an IP the IP rule masks goes as an address from the
  documentation ranges (192.0.2/198.51.100/203.0.113 .101-.254, IPv6
  2001:db8::/32), stable for the value, never shared by two values
  (falls back to {{IP_…}} past 462 IPv4 ones), and put back only as a
  whole address in replies and streamed tool calls (restoreAddr).
  Preview shows the same stand-in.
- docs: gateway-routing.md, and masking.html in en/zh/ja.

Run:
- Real models through the local gateway, the screenshot's ssh prompt
  with the placeholder vs a documentation address: with
  {{IP_k3v9x2mq}}, deepseek-v4-pro, glm-5.3, kimi-k3 and
  claude-sonnet-5-5 mostly searched ~/.ssh or asked for the real IP;
  with 203.0.113.147 or 192.0.2.183 all 20 runs over 5 models ran ssh
  at once.
- New tests (internal/redact/standin_ip_test.go): the screenshot's
  message, the tool call restored whole and streamed cut at every byte,
  boundary cases, IPv6, 472 addresses never sharing, the screenshot's
  address under labels secret and account_number with every category
  on, and a 64-hex key still masked. gateway TestRedactedKinds now
  wants a documentation address upstream.
- Broken by hand: without the evmRe check TestEVMAddressGoesAsWritten
  is red for every text and label; without restoreAddr the boundary
  cases are red; without the IP stand-in all three IP tests and
  gateway TestRedactedKinds are red.
- On mote at this head (rebased on 27bf14790): gofmt -l, go vet
  ./... for darwin, linux (-tags nogui) and windows, go test -count=1 -timeout 45m
  -tags nogui ./... (and go build for
  darwin, linux -tags nogui and windows): every package ok, exit 0.
  The run before at 56602426d had TestMoreKinds red, which wanted
  {{IP_…}}; it now wants the documentation address.
- Rebased again on 56d26f0bb (two gateway commits, #4004): go vet
  and go test -tags nogui of internal/redact, internal/gateway and
  internal/maskrec on mote at this head: ok.

Not tried:
- the real AstrLink model on an EVM address (the fake model gives it
  the labels it can give);
- a host name (user@host) still goes as {{HOSTNAME_…}};
- a documentation address the user writes themselves can match a
  stand-in in a reply and be put back as the real one;
- stand-ins are not kept across a restart or once their slot is
  evicted, like every placeholder.
2026-10-28 20:23:38 +08:00
yetone a5315c70d5 redact: the local model doesn't read an agent's tool definitions (niuniu_8964 on X)
码妞 on X: the official container on a 4-core, 8 GB server, AstrLink Guard
on, Claude Code's requests sat at 脱敏中 for minutes and timed out, load
1.78, a short conversation. aca0f0d8a made Guard read a text's windows
at once; this takes away most of what it reads.

MaskJSON asked the model about every text it masks, the tools'
descriptions and their schemas' too. On Claude Code 2.1.296's own request
(internal/gateway/testdata/workdir) that was 67,532 bytes, 52,577 of them
definitions: the agent's or a tool server's text, the same in every
request. The per-text cache only helps after the first request has been
read whole, so a fresh install (or new tools, or a Claude Code update)
paid for all of it at once, past the gateway's 2 minutes on a slow CPU.

Now what is under the request's definitions (defKeys, defItems) is never
sent to the model; it is masked as with the model off, by the rules
alone (emails, phones, keys, the user's words still are). It is masked
after the rest of the request, so a value the model found in a message
is masked in a definition too, as known. The system prompt and messages
are read as before.

Measured on magpie-desktop (WSL, Ryzen AI Max+ 395, taskset to the CPUs
named), real Guard model (rev 7216b6a3, sha256s checked), that request
through redact.MaskJSON with guardBackend, cold cache:
  4 CPUs: 129 texts, 67,532 bytes, 11.5s before; 7 texts, 14,955 bytes, 2.6s now
  2 CPUs: 20.9s before, 4.9s now
  rules alone 13-15ms; the same body warm 13ms, the next turn 36-44ms,
  before and after.
On three real Claude Code requests (claude-code-2.1.296.json,
context/claude-code.json, dsh-gateway messages-turn.json), masked with
the model at 0.8 and with the rules alone, every top-level key came out
the same: the model masked nothing in their definitions that the rules
didn't.

No time cap was added. The reporter turned the model on (the default-on
model is from today, ae0327945), so a request there is held for the
model and never falls back to the rules; a cap would only turn the wait
into an error. Less to read is the fix.

Tests:
- TestModelNotAskedAboutDefinitions (new): on Claude Code 2.1.296's and
  Codex 0.162.1's own requests no definition's text is asked about, and
  every long text said is.
- TestDefinitionMaskedAsWithoutModel (new): a tool's description and a
  schema property's come out as with no model; the email, the key and
  the phone in them are masked.
- TestModelAskedOnceForRequest: now asks about the message only, and the
  description's name is still masked (as known).

Run:
- mote-run: go vet ./internal/redact ./internal/masking, GOOS=linux and
  GOOS=windows go vet of them: ok. go test ./internal/redact/...
  ./internal/masking/... ./internal/pii/... ./internal/gwmw/...: ok.
  go test -run "Mask|Redact|Privacy|Unmasked|Masked|Placeholder"
  ./internal/gateway ./internal/middleware ./internal/gui: ok.
- wsl-run: go test ./internal/redact ./internal/masking: ok; the stage
  timings above (a scratch test, not committed).
- gofmt -l: clean.
- The vet and the test lines above ran again after rebasing onto
  d6df72a2b (its own redact change), and redact, masking and the
  gateway masking tests again on 25fc92d59: ok.

Broken by hand:
- Definitions sent to the model again: TestModelNotAskedAboutDefinitions
  red ("the model was asked about a definition's "Launch a new agent…""),
  and TestModelAskedOnceForRequest red.
- Definitions masked in the first pass, before the messages:
  TestModelAskedOnceForRequest red ("description":"find Rina Kowalczyk"
  went as written).

Not tried: the reporter's server, the Docker image itself, or a real
Claude Code session through it; a Chinese full name only in a tool's
description is no longer masked (the model was what found one; the rules
mask Chinese names only beside the model). The full go test ./... wasn't
run: mote had another session's full suite on it at load ~216, and only
internal/redact changed.
2026-10-28 17:36:40 +08:00
yetone d6df72a2ba redact: a disassembly's symbols (system@plt, foo@@GLIBC_2.2.5, system@got) are no email
ch35tnut_ on X: reversing, symbols like system@plt were masked as
emails, so masking had to be turned off for reverse engineering.

The rule's regexp already needs a dot and a mail TLD (mailTLD), so
system@plt, puts@got.plt and memcpy@GLIBC_2.14 went as written by it at
origin/main. The local model's EMAIL spans pass realEmail too, which
never asked for a dot: .got is an ICANN top-level domain, so a model
span on system@got (IDA's "; system@got") was masked. And a
foo@plt.got ends in .got with a dot, so the rule masked that too.

realEmail now asks mailHost first, for the rule and the model alike: the
host has a dot, every label is letters, digits and hyphens (or non-ASCII,
an IDN's), no label empty, the local part does not end in @ (foo@@VER),
and the host is not made of linker table words alone (plt, got, sec,
iplt, igot: free@plt.got, memcpy@plt.sec). A version with an underscore
(@GLIBC_2_2_5) or no dot (@Base, @GLIBC_PRIVATE) is no host.

TestSymbolIsNoEmail has objdump, readelf, nm, gdb and IDA lines as they
print them, for the rule and for a fake model flagging each symbol as
private_email, and checks that rina.k@fastmail.com in code and
ops@build01.acme.io beside a symbol are still masked by both.

Run at this head (origin/main aca0f0d8a), through mote-run:
- go test ./internal/redact ./internal/pii ./internal/masking
  -count=1 -timeout 45m: ok, ok, ok.
- gofmt -l clean; go vet of the three on darwin, GOOS=linux -tags nogui
  and GOOS=windows: clean.

Broken by hand:
- mailHost's call made `false &&`: TestSymbolIsNoEmail red, the model
  masked "; system@got" as {{EMAIL_…}}.
- linker check made `return true || !linker`: red, rule and model both
  masked <free@plt.got>.

Not tried: the real local model (AstrLink / Privacy Filter) on a
disassembly; the fake model stands in for its spans. Full go test ./...
not run; this touches internal/redact and its doc only.
2026-10-28 17:23:59 +08:00
yetone eb6d1d8d97 redact: a colour or an ordinary word is no personal name (黄绿色, 关键词)
hh05928822 on X after v0.1.1850: names were found in ordinary Chinese,
"黄绿色" the worst, with 边••, 应••, 关••, 尚• in the screenshot.
wangjunxiao128: "关键词" taken for a name.

Both ways a Chinese name is found (the model's PERSON spans in
modelSpans, and the cue rules in zhNameSpans) now go through one check,
zhWordNotName: a span that is an ordinary word is no name, unless a role
before it or a title after it says a person is meant (客户方圆, 江山老师).
A word is (zhWordShaped):
- a colour: Han colour characters alone, or anything ending in 色
  (黄绿色, 红色, 金黄色, 浅蓝色);
- a two-character word starting with a surname, from zhWords or the new
  zhDict (边界, 应该, 尚可, 关心);
- such a word with a noun ending after it (关键词, 关键字, 应用层,
  毛利率, 时间戳, 文件名).
zhDict is zhdict.txt, embedded: ~1,550 two-character words from jieba
v0.42.1's dict.txt (MIT, in THIRD_PARTY_NOTICES), the first character a
surname, frequency >= 100, tag not nr/nrt/nrfg, and a list left out by
hand (陆游, 关露, 欧阳, 司徒...) in its header. The surname list keeps
黄, 关, 边: they are real surnames, so 黄晓明, 关羽 and 毛利兰 are still
masked. modelTakes' own zhWords check moved into the shared one.

Run on mote at 761e0e010 + this change:
- go test -timeout 45m ./internal/redact/... ./internal/pii/...
  ./internal/masking/... ./internal/maskrec/...: all ok
- go test -run TestNotices . : ok
- go test -run "Mask|Redact|Privacy|Person|Name|Known" ./internal/gateway: ok
- gofmt -l internal/redact: clean
- GOOS=linux and GOOS=windows go vet of redact, pii, masking: ok

Broken by hand, each red:
- zhWordNotName returning false (at 761e0e010 too):
  TestChineseWordsAreNoNames, TestModelWordsAreNoNames,
  TestModelNamesBesideWords.
- The colour rule, zhDict and the noun-ending rule each turned off:
  TestModelWordsAreNoNames and TestModelNamesBesideWords.
- The role/title exception removed: TestModelNamesBesideWords.
- The old model.go and zhname.go with the new tests: both new tests red
  (the cue rules alone masked 请黄绿, 发给黄绿, 张伟和黄绿).

The real AstrLink Guard model on mote (MAGPIE_GUARD_DIR) found 黄晓明,
关羽, 张飞, 毛利兰 and 工藤新一 with this change, and flagged none of
long agent-style prompts with 黄绿色, 关键词, 边界线, 边距, 应用层, 尚可,
on the old code or the new.

Not tried: the reporters' own texts (not in the reports), so their
exact false positive was not reproduced with the real model; Privacy
Filter; the GUI. 高峰期 is still masked: jieba tags 高峰 as a name.
2026-10-28 17:01:49 +08:00
yetone ae03279458 masking: the local model is on by default; the rules mask alone until it is downloaded
The owner's plan (10-28, after the xuanwo/_kaichen reports under the
masking demo): with AstrLink Guard picked, the Chinese-name heuristic
is off and only nicknames like 小王/老李 stay a rule; with Privacy Filter
it is as before; every format rule stays; the model is on by default,
masks with the rules alone until its download finishes, and no longer
answers 503 for it.

- masking.ModelWanted(st): on when the user turned it on, off when the
  user turned it off (new RedactModelOff, set by SetRedactModel(false),
  remove, and cancelling the default's own download), on when the
  default's download finished (RedactModelAuto). A settings file from
  before this, with a model name picked or files on disk and the model
  off, reads as the user's off: magpie's default doesn't override it.
- Until the picked model is installed, requests are masked by the rules
  alone and fetch starts its download (one try per model per hour,
  never under testing.Testing(), nothing where the model can't run).
  When it finishes, settings.UseDefaultRedactModel records the default
  (it refuses when the user has set anything) and the model warms.
- model(..., strict): a model that fails holds requests back (503)
  only when the user turned it on; under the default the rules mask
  alone. The Privacy page says which ("…the rules mask requests alone"
  in en, zh, zh-TW, ja, de; /api/privacy-model has `chosen`).
- redact.Options.NamesByModel (AstrLink Guard picked): zhNameSpans
  keeps only zhNick candidates (小/老 + a surname).
- KeepOwn and POST /api/settings keep both new fields.
- Docs: gateway-routing.md, site masking docs (en, zh, ja).

Run (mote, Go 1.26.8):
- gofmt clean; go vet of masking, settings, redact, gui; GOOS=linux go
  vet of masking, settings, redact; GOOS=windows go vet of the four.
  (GOOS=linux vet of internal/gui needs cgo, as on main.)
- go test -count=1 -timeout 45m ./... at base 7fd77a944: every package
  ok except internal/gui. Its reds: TestCoreScriptBudget (+64 bytes,
  fixed by dropping a comment, budget not raised), TestPrivacyModelPick
  and TestSettingsSaveKeepsWhatItDoesNotSend (updated for the new
  default and fields), TestMainWindowCorners (#3949, red on origin/main
  e8c7dddcb too), and three AppKit tests killed at 20-30s under load
  just before mote rebooted, which pass in the rerun.
- Rerun at base 6bec526f7: internal/gui (only #3949 red), masking,
  settings, redact ok. GUI node tests privacy-model, masking-records,
  masking-demo, routing-masking, i18n-keys, gui-zh-tw, gui-ja, gui-de:
  Chromium 199/199, WebKit 106/106.
- At the pushed base 9e33962c0: TestCoreScriptBudget, TestSettingsSave*,
  TestPrivacyModel* ok; i18n-keys and privacy-model 68/68 in both
  engines.
- At the pushed base 7fcf642ee (masking in the request archive):
  -run 'Mask|Redact|Archive|Privacy' in masking, gateway, redact ok.

Broken by hand, each red: the nick filter off
(TestChineseNamesByModelOnlyNicks), ModelWanted needing RedactModel
(TestModelOnByDefault), strict ignored (TestDefaultModelFailingIsTheRules,
TestNoModelYetMasksByTheRules).

Not tried: a real default download in a sandbox HOME (the tests fake the
model). Known limit: a user who turned the model on before model picks
existed and then deleted it has no name or files left, so reads as new
and gets the default on.
2026-10-28 16:55:24 +08:00
yetone 189db9ba5b redact: ids, digests and 毛利 go as written; the slider reaches known values; a user name goes as a made-up name
Reports on X under the masking demo (10-28):

_kaichen: "hash类型也会被过滤…长int,假如以1为开头的…会被当作电话被mask;
"毛利低"也会被当作人名被mask。即使把匹配拉到 0.95,也是一样行为".

- Hex digests: 16 to 31 hex digits in one case, with letters and digits
  both (a cache key, a short commit), are ids now (digestShaped in
  ids.go), like UUIDs and 32+ hex. The rules' SECRET keeps one only under
  a credential's field or a CJK/prose key with no field word (密钥为…);
  the model's SECRET is dropped under a field named for something else
  (cache_key, commit, object, blob, file, content, revision, partition,
  shard, bucket, dedup, lookup, row, sort) and on a JSON object's key
  (nameOfField). A bare `key` after api/access/secret/private/signing/
  license is still a credential (keyPhrase). The IBAN case kept its mask
  through the letter/digit minimums.
- 11-digit 1x numbers (phone.go, phoneAt): a phone with +86/86, as the
  value of a field whose name says phone (phone, mobile, tel, cell,
  contact, 手机, 电话, `number`), or in prose with no id word right
  before it (order, id, no., #, 订单号, 编号, 单号, 流水号…). Under
  order_id/uid, after 订单号, or with a letter or digit against it, it
  goes as written. PHONE and BANK_CARD are bounded by alnum, not digits,
  in the rule and in known values.
- 毛利: zhWords gained 毛利, 毛重, 毛坯, 毛巾, 毛衣, so 毛利低 (a margin)
  is no surname+name. The model still finds 毛利兰 (Guard). 毛利小五郎
  (indekkusu141209) is masked by neither model nor the rules now.
- The slider: a value masked once was masked again as known whatever the
  threshold. Each value now remembers the highest score it was found
  with (rules count as sure, ruleFound), and knownSpans skips one under
  Options.MinScore, which masking sets from pii.Threshold.

eerttreeeert: with mimo-v2.6-flash the home folder went as
C:\Users\{{USERNAME_…}}; the model took it for a temp folder and set out
to delete it. With the user name switch on, it now goes as a made-up name
of 8 lowercase letters (HMAC of the name, same every turn, standIn in
shape.go), restored in replies and tool calls like any placeholder;
Preview shows the same name.

Docs: docs/subsystems/gateway-routing.md masking bullets, and the site's
masking page (en, zh, ja) on mobile ids and the user name.

Run (mote, at this tree on base 6af83172d; rebased onto b01193ef9, which
changes nothing in redact, masking or pii, and redact, masking and
pii/... run again ok at the pushed head):
- gofmt -l clean; go vet ./... and GOOS=darwin/linux/windows go vet of
  redact, masking, pii: ok.
- go test -count=1 -timeout 45m redact, masking, pii/..., gateway, otlp,
  sessions, settings: all ok but internal/gateway's
  TestPluginStreamsPastTheBudgetWait (connection reset by peer, 183 of
  192), red the same alone at fresh origin/main b01193ef9 (169 of 192);
  #3946, commented.
- Real models on mote (AstrLink Guard and Privacy Filter, cached): the
  reporter's hashes, ids and every 毛利低 sentence kept; a prose phone
  masked; 毛利兰是谁 masked by Guard; 毛利小五郎姓什么 kept by both.

Broken by hand, each red: phoneAt off; the phone bound back to digits;
digestShaped off; "cache" out of the field list; nameOfField off; the
model's field check off; 毛利 out of zhWords; the slider check out of
knownSpans; standIn off.

Not tried: a real mimo-v2.6-flash session with the made-up name; the
Windows box; the GUI suite (no GUI file changed). 毛利小五郎 stays
unmasked by rules and both models, said in the doc.
2026-10-28 16:05:19 +08:00
yetone f02d92c7be redact: a file's lines, a path, a skill and a name in code after token: are no secret
Three reports on X (10-28), each a value the SECRET rule took (Insights >
Masking: 机密, 规则). The rule takes a name with token, secret, password
or api_key in it, then : or =, then 8 characters or more with a letter and
a digit. Prompts and code have that shape where nothing is secret:

- AlpsNowX: L643-669. was masked, in two requests. A file whose name has
  one of those words, then :L643-669. (internal/auth/token.go:L643-669.)
  read as a field token.go and its value, and once masked the lines went
  as {{SECRET_…}} wherever they came again (by known). Now a name that is
  a source file's (.go, .ts, .py, .md, .json …, not .txt/.env/.key) or a
  path's last part is no field, and a line or range (L643, L643-669,
  L12-L40, 643:12) is no value. Siblings: token.go:643-669 and #L643-L669
  were never masked (no letter / no colon); file.go:L12-40 was, and isn't.
- binary4cat: function names masked. access_token = get_access_token_v2,
  max_tokens=max_tokens_v3, secret: env.SECRET_V2, refreshToken2;,
  fn(token=token_v2), secretKey:=base64Encode(raw) all masked the name.
  A value written as code writes a name (lower-case start, or _ or .
  between words) of two words or more, one of them token/secret/password/
  key/credential, is a name now; a value starting with = is Go's :=.
- AkinoNya: folders and skills with a random string replaced. Found two
  routes: a path after such a name (PRIVATE_KEY_PATH=~/.ssh/id_ed25519,
  token_dir=/private/tmp/claude-501/x7k2p9q1-skill,
  GOOGLE_APPLICATION_CREDENTIALS=/Users/…/legacy_credentials/x7k2p9q1/…,
  私钥 ~/.ssh/…), and Claude Code's plugin:skill when the plugin's name
  has one of the words (design-tokens:generate-v2, secret-scan:
  audit-x7k2p9q1). A path from ~/, ./, ../ or a root folder (/Users,
  /tmp, /private …) with no + or = goes as written, in the CJK key rules
  too; slug:slug with no space is a skill. The ~1100 real folder and skill
  names on this machine (~/.claude, ~/.codex, $TMPDIR, Claude's
  claude-501 dirs) in five contexts masked nothing before or after, so
  the reporter's exact names are not reproduced.

Still masked (TestSecretsBesideLinesAndNames): password=hunter2pass9,
API_KEY=AbC123dEf456GhI789, token=t0k3nValue2, Passw0rd123, password123,
SuperSecret2024 (PascalCase stays a password), token: Lk8x9QmP2vR4,
secret.txt:hunter2pass9, x-api-key:k9x2mp4qr7st1vw3 and :ab12cd34ef56,
Password=Abc12345; in a connection string, 密钥为12231241, 私钥 ab12…,
django-insecure-…; vendorchecks and the existing code tests unchanged.

Run (mote): go vet ./internal/redact for darwin, linux, windows; go test
-count=1 ./internal/redact ./internal/masking ./internal/pii/...
./internal/otlp ./internal/sessions ./internal/settings ./internal/gateway
at base ea53eb126: all ok (gateway 551s). After the rebase onto
bc3ddc661 (zhname): vet (3 OSes) and redact, masking ok. gofmt -l clean.
Broken by hand: the two SECRET rules back on notCode and keyAt without
the path check: 28 of the new tests' cases red (every reported shape),
the still-masked test green.

Not tried: the full ./... suite (mote at load ~50 with two other full
suites); the reporters' own prompts; the local-model path, unchanged.
Tradeoff: a password written as code writes a name (myPassword1,
MY_SECRET_2) now goes as written.
2026-10-28 15:16:59 +08:00
yetone bc3ddc661a redact: 文案 and words like it are no Chinese names (zeewell on X)
zeewell on X: tasks kept going wrong because 文案 was masked as a name,
so they turned names (and birthdays) off. 文 is a surname, and zhName
took a cue around 文案 that says nothing about a person. Probing words
that start with a surname (文档, 方案, 关键, 项目, 成本, 段落, 颜色, 查询,
时区, 简历, 林间, …, ~130 of them) in the places a prompt has 文案, about
110 were masked, through two cues:

- 一下 before it (改一下文案, 检查一下文案,) counted as "a person comes
  next". 一下 follows any verb, so it now counts only after one that asks
  a person (zhAskVerbs: 问, 找, 联系, 通知, 提醒, 回复, …): 问一下张伟
  still is one, 改一下文案 is not.
- At a sentence's start, a word after it that any subject takes (已经,
  明天, 今天, 昨天, 他, 她, 提交, 负责, 回复) counted alone: 文案已经改好了,
  文案明天给你, 文案他们说. Those (zhAnyAfter) now count only with a
  person's cue before (客户张伟已经到了). 说明, 说法, 讲解, 讲座, 讲义, 讲究
  are words, not 说 (文案说明), but for 说明天 (张伟说明天来).
- zhWords gets ~150 more common words (文案, 文风, 关键, 项目, 段落, 林间,
  …) for where a real cue is before a word (发给文案, 请文案), and is a
  set looked up by a candidate's first two characters rather than a scan.
- The model's own PERSON span that is such a word whole (文案) is
  dropped too (modelTakes), the other route a word reaches a name.

Old data: masked values are remembered in memory only, and 文案 (6
bytes) is under minKnown, so nothing stays masked after the update.

Fixtures are prompts with 文案 where the report gives no sentence (帮我
改一下这段文案, 文案:…, 把首页文案换成英文, ### 文案, 文案和图片, 文案已经改好了,
文案说明要简短, 这张图发给文案。), beside names in the same places that
still mask (问一下张伟,, 张伟说明天来, 客户张伟已经到了, 发给张伟。);
TestChineseWordsAreNoNames runs 25 listed words in 10 shapes plus the
model's label, and 5 unlisted ones (文创, 方位, 高铁, 安防, 林荫) through the
cue shapes alone. Every TestChineseNames case stays green.

Run (mote, mote-run, at this tree): go vet ./internal/redact for darwin,
linux and windows ok; gofmt clean; go test -timeout 45m of
internal/redact, masking, pii/..., otlp, sessions, settings, gateway
ok; internal/gui red on TestMainWindowCorners/macOS_26_SDK only, the
macOS 27 red filed as #3949 (no redact in it).
After rebasing onto 8edb9dbb7 (gateway, provider only): redact and
masking again ok at the pushed head.
Broken by hand, each red: the 一下 rule always true (改一下文创), the
zhAnyAfter check off (文创已经好了, 文创明天给你, 文创他们定), the 说明 words
off (文创说明), the model's word check off (the model's 文案, 文档, …), 文案
out of zhWords (发给文案, 请文案).
Not tried: the real model on zeewell's prompts (they gave none). Now
left: a two-character name at a sentence's start before only 已经/明天/
他 (张伟已经到了。), and an unlisted word after a person's verb at a
clause's end (发给文创。). Birthdays: the report names no birthday that
was masked wrongly, so they are unchanged.
2026-10-28 15:15:31 +08:00
yetone 58fb3a7786 redact: 关键发现, 易触发 and 和边界 are words, not Chinese names
xuanwo on X: with the model on, a report's words were masked as names,
关键 in "### 关键发现", 易触 in "`gh pr view` 易触发" and 边界 in
"判断和边界,". Each starts with a surname (关, 易, 边), and zhName took
a cue around it that was too weak alone:

- 发 and 打 after it counted as the verb a person does. They now count
  only when no Han character follows, or one of 了个给过一 (发了个消息,
  打给他); 发现, 打开 begin a word.
- 和 and 与 before it counted as "a person comes next". They join like
  to like, so they now count only when a pronoun or what may be a name
  (a surname and 1-3 characters, no zhWords word) is before them:
  吴敏和郑浩, 我和张伟, not 判断和边界.
- A sentence started after any space or symbol. A space after a word or
  code is inside a sentence, so the start is now after punctuation (with
  spaces after it or none) or at the text's start; a backtick no longer
  counts.

The fixtures are the reporter's literal lines, beside names around the
same cues that still mask (### 张伟发了个消息, 我和张伟,, 这件事。 李娜说过).

Run (mote, mote-run): go test ./internal/redact (TestChineseNames,
TestMaskEval and the rest) ok; gofmt clean. Broken by hand, each red on
its own case: the 和/与 rule off (边界), wordAfter off (关键发现),
sentenceStart always true (易触发).
Running as this is pushed: vet (darwin, windows, linux) of
internal/redact and go test of redact, masking, pii, otlp, sessions,
settings, gui and gateway.
Not tried: the real model on the reporter's whole session; a name that
starts after a space following a Chinese word (这件事 李娜说过) is now
left, as one inside a sentence.
2026-10-28 14:27:17 +08:00
yetone bad05e1b79 redact: sk- and a UUID in lower case is a key again
3e96197da left an sk- value unmasked when it had no capital and no run
of 16 between hyphens, so an SK hynix article's address is not a key.
A key that is sk- and a UUID in lower case (groups of 8, 4, 4, 4 and 12
hex digits) met both and went to the vendor as written. A value that is
hex digits alone after sk- is masked again; no slug of words is.

Run on mote at this tree: go test ./internal/redact ok. TestSlugIsNoKey
with the UUID case is red on 3e96197da's rule ("0 masked"). The SK hynix
addresses stay unmasked.
Not run: the full suite.
2026-10-28 11:23:46 +08:00
yetone 3e96197da3 redact: an address's words joined by hyphens are no sk- key (sk-hynix-…)
innerpeacebuild on X: search results naming articles about SK hynix,
cnbc.com/…/sk-hynix-third-quarter-profit.html and the like, went to the
model with each slug as {{API_KEY_…}}. The sk- rule took any 20
characters of letters, digits, - and _.

A key's characters are random, so it now needs a capital or a run of 16
or more with no hyphen. DeepSeek's sk- and 32 hex digits and
OpenRouter's sk-or-v1- and 64 are lower case and still masked.

Run on mote at this tree: go test ./internal/redact ok;
TestSlugIsNoKey (the reporter's four addresses beside four keys) is red
on the old rule (each slug masked) and green on the new. go vet for
darwin, linux and windows ok, gofmt clean. Not run: the full suite;
only internal/redact changed.
2026-10-28 11:11:45 +08:00
yetone df8e9de3f1 redact: a masked word that is a date matches that date however it is written
JackyCcao on X turned birthday masking off (old dates in logs and tasks
after a birthday's word were still taken) and put their own birthday in
Masked words instead. A word matched only as typed, so 1990-05-12 let
1990/5/12, 1990.05.12, 1990年5月12日 and 19900512 go as written.

A masked word that is all of a date (dateword.go: year-month-day with
- / . 、 or a space, 年月日 or 년월일, a month's English name, or
day/month/year where only one reading is a date) now matches that
calendar date in each of those forms, with or without leading zeros,
as eight digits, and day-first or month-first only where the day is
over 12 or equals the month: for 1990-05-12 neither 05/12/1990 nor
12/05/1990, which reads as December 5th too. A word like 05/12/1990
is no date and matches only as written. Eight digits alone are not
taken for a date word (as likely an id) and match as before. A date
match never has a digit, or a dot and a digit, beside it, whatever
Whole words only says, so 1990.5.12.1, 3.1990.5.12 and 11990-05-12
are no match; this is a change for a date word without Whole words,
which matched inside such numbers before.

The birthday rule is not changed. It takes a date only right after a
birthday's word (生日, DOB, born...), so a log line's, a file name's
or a task's own date is never one, however old. What is left (生日:
2019-03-02 in a task log about a party) has the same shape as a real
date of birth, and a time beside the date doesn't tell them apart: a
date of birth stored as a time (1990-05-11T16:00:00.000Z, midnight in
UTC+8, as JavaScript writes it) is the commonest way one reaches an
agent in JSON. TestBirthdayLogDates pins both sides; #3878 tracks
fixed-shape false alarms.

Tests: TestDateWordEveryForm (22 forms x 5 words x 6 contexts, each
restored as written), TestDateWordDayMonthOrder, TestDateWordNotAnotherDate
(another date, 1990.5.12.1, longer numbers), TestDateWordOnlyADate.
Broken by hand: with the dateSpans hook in mask turned off, EveryForm,
DayMonthOrder and NotAnotherDate fail; OnlyADate and BirthdayLogDates
pin behaviour that was already right and pass on both.

Docs: gateway-routing.md, masking.html en/zh/ja.

Run on origin/main 94c2aaecb, sandbox HOME and GOCACHE, then rebased
onto 841bcf8da (its changes are in usage and gateway/history.go, none
in redact) and the vet and the four packages run again there; on e056779a6
(a GUI change, nothing in redact) redact, masking and settings again:
- gofmt -l clean; go vet clean on macOS, GOOS=linux -tags nogui and
  GOOS=windows (internal/redact).
- go test -count=1 ./internal/redact/... ./internal/masking/...
  ./internal/pii/... ./internal/settings/...: ok. The date tests also
  with TZ=UTC and TZ=Pacific/Kiritimati: ok.
- go test -count=1 -timeout 100m ./internal/gateway (at 94c2aaecb):
  every test ok
  but TestPluginToldWhereTheAgentWorks, which failed only because the
  run's TMPDIR was inside this git worktree (its "not in a repo"
  folder was in one, git "yes"). Run alone with TMPDIR outside the
  repo it is ok; with TMPDIR inside it fails at this head too.
Not run: the full ./... suite (another session's full suite holds the
machine, load ~100-140). No GUI asset changed, so no GUI run.
2026-10-27 22:44:52 +08:00
yetone e7ba8a3892 redact: an email that ends a sentence is masked
The EMAIL rule's bound characters held "." on both sides, so an
address followed by a full stop was no match: "The user's email
address is jo@quill.dev." (Claude Code's own userEmail line) and
"write to me at li.wei@qq.com." went to the vendor as written with
the rules on. Found measuring the local model's threshold for
Yayoi_no_yume on X: in 2000 segments of real Codex and Claude Code
traffic, two real addresses were masked only because a model found
them, at 0.70 and 0.95.

emailAt now judges a dot beside the match: one before it still turns
it away, and one after it only when a letter, digit, - or _ follows
(a@b.io.12 stays unmasked, as before). The rest of the bound
(letters, digits, _ % + -) is unchanged.

TestEmailBeforeAFullStop: its five sentence-end cases fail on the old
rule (5 of 5 unmasked), pass now; its two longer-name cases are
unmasked on both.
2026-10-27 17:10:20 +08:00
JoeyWu-tech 1cbdda25be redact: cua-driver's element tokens go as written (#3782)
Hu9956 (#3782): with masking on, DeepSeek Harness's computer use
(cua-driver: a window's state, then a click on one of its elements) went
to the vendor with element_token values as {{SECRET_...}}, found by the
rules. cua-driver hands the model a token for each element of a window:
s, the snapshot's counter in 8 hex digits, a colon and the element's
index (s0000002a:14). The model clicks by it. The SECRET rule takes a
value of 8 or more letters and digits after a field whose name holds
"token", and element_token is one, so each token in a window's state, in
a click's arguments and in a shell command's JSON went as a placeholder
and its index ({{SECRET_...}}:74). Two of the report's places show the
token with no index ("element_token": "s00000001"), so that is taken as
it is written too.

noIDs, which lets a backend's id (a UUID, 32 hex digits or more) go as
written unless its field is named for a credential, now takes an element
token for one too (elementToken): s and 8 lowercase hex digits, then a
colon and the index, with no letter, digit or _ on either side. Without
the index, s and 8 hex digits is one only as the value of a field named
for an element: alone in a text it may be a student's number
(s12345678), which the local model may call an account. A field named
for an element is no credential's, as one named for a page, a cursor or
a request isn't (credentialField, whose field name reading is now
fieldWords). So element_token's value goes as written, while the same
value after password=, token:, "refresh_token": or "api_key": is
masked, and so is a value of any other shape in element_token. A token
the local model takes for a secret, or anything else, goes as written,
as a UUID does. The user's own words still mask one.
docs/subsystems/gateway-routing.md says so.

A UUID in a field named for an element (element_token) goes as written
now too, as one in next_page_token does.

What was run (tree bb52fa4d, on origin/main 5215108e, go1.26.8,
linux/amd64):
- TestElementTokensGoAsWritten, new. Five tokens (s00000001,
  s00000003:74, s0000002a:14, s00007a3f:42, s00010001:3) in seven
  places, as the report has them (JSON laid out and compact, a space
  after the colon, a shell command's JSON, element_token=, inside a JSON
  string, elementToken), go as written. MaskJSON of a window's state and
  a click, DB_PASSWORD=hunter2abc9 beside them, masks the password
  alone. The local model's every label goes as written on s0000002a:14
  in a text and on s00000001 in element_token. s12345678, in a sentence
  or under student_no, labelled an account number or a secret by the
  model, is masked. s00000001 and s00000003:74 after password=, token:,
  "refresh_token": and "api_key" are masked, and so is element_token
  holding abc123def456, s0000000g1, S0000002A, s000000012, s00000001x or
  s00000001:x9. The user's own word masks one.
- It and TestIDsGoAsWritten -count=50: ok. internal/redact,
  internal/maskrec, internal/gwmw, internal/masking and plugins/redact:
  ok.
- Broken by hand, each red in TestElementTokensGoAsWritten:
  - idAround not taking an element token: every kept place, the
    MaskJSON body, the model's every label on s00000001 in
    element_token (the rule masks it there), and its address and secret
    labels on s0000002a:14.
  - "element" not among credentialField's words: every kept place, the
    MaskJSON body and the model's every label on s00000001 in
    element_token (the rule, again).
  - the model's secret kept on a token: its secret label on both.
  - s and 8 hex digits a token anywhere: s12345678's four cases.
  - a token only with its index: s00000001 in its seven places and the
    model's labels on it.
- A real run: magpie built at 5215108e and at this tree (go build -tags
  nogui -buildvcs=false), in a sandbox HOME with masking on
  (settings.json "redact": true), a local server standing in for the
  vendor that keeps each body it is sent. One request on
  /v1/chat/completions with the report's three places: a window's state
  as compact JSON with "element_token": "s00000003:74", one laid out
  with "element_token": "s00000001", a shell command's cua-driver click
  with "element_token": "s0000002a", a click by s00000003:74, and a user
  message with DB_PASSWORD=hunter2abc9. 5215108e: the vendor got each
  token as a {{SECRET_...}} placeholder (s00000003's with its :74), four
  places. This tree: each as written, the password still a placeholder.
- gofmt -l; go vet -tags nogui and go build -tags nogui for linux,
  windows and darwin, and go vet and go build for windows without the
  tag: exit 0 each. go vet and go build without the tag on linux: exit
  1 (this box has no GTK or WebKitGTK dev packages).
- go test -tags nogui -count=1 -timeout 45m ./..., Bun 1.4.2 on PATH:
  68 ok, and 7 red, none in what this changes: agent
  TestCodexDriftReached and TestCodexBehindReverseProxy (#3398);
  TestHowInstalled, TestCursorFolderFromTheEditorIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (#3640);
  gateway TestPluginToldWhereTheAgentWorks (#3675); gui
  TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie
  (#3649); proc TestProbeTimeoutEndsWhatItStarted (#3848, passes 40 of
  40 alone); provider's "close of synctest channel from outside bubble"
  from TestUnreadLoginsWriteErrorsKeepCredentials (#3632), so the
  package's tests after it didn't run: go test ./internal/provider
  -skip '^TestUnreadLoginsWriteErrorsKeepCredentials$', Bun 1.4.2 on
  PATH: ok.

Not tried: DeepSeek Harness and cua-driver themselves (no macOS here);
the request was written by hand from the report's places.

Review, applied on origin/main 8e2ba36de (git am, sha256 of the patch
matches the issue's 1db65568…), with two changes to the patch:
- The patch made any field with "element" among its name's words no
  credential's (credentialField) and the field an index-less token may
  sit in. That widened a key-name exemption: a UUID in element_api_key or
  elementSecret went as written. Now only cua-driver's own name,
  element_token (elementToken, element-token), is that field
  (elementField); any other name is a credential's as before.
- A token known from before (ByKnown) was still masked as a credential.
  One the local model labelled in prose ("I will click s00000001 now")
  was then masked in every element_token after it, a click on nothing.
  An element token is no longer masked by a value known from before;
  the user's own words and rules, and the password, API key and token
  rules, still mask one.
Not scoped to tool calls and results by place: the exemption is held to
the token's shape (s, 8 hex digits, :index; index-less only as
element_token's value), so a value of any other shape under that key is
masked, and every route masks through redact.mask (masking.Masker's
MaskJSON and Text), so each route gets it.

What was run in review (darwin/arm64, go1.26.8, sandbox HOME):
- TestElementTokensGoAsWritten red with origin/main's ids.go (the
  report's laid-out "element_token": "s00000001" went as
  {{SECRET_…}}), green with this.
- Broken by hand: elementField back to "any word element": red, a UUID
  and s00000001 in element_api_key and elementSecret went out; ByKnown
  masking a token again: red, the click's element_token masked after
  the prose turn.
- go test -tags nogui ./internal/redact/... ./internal/masking/...
  ./internal/maskrec/... ./internal/gwmw/... ./plugins/redact/... and
  internal/gateway -run 'Redact|Mask|Masked': ok. gofmt -l: nothing;
  GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  internal/redact: ok.
- Real run: magpie built at 8e2ba36de and at this tree, `magpie serve`
  in a sandbox HOME with "redact": true, a local fake vendor recording
  bodies; one /v1/chat/completions request with the report's three
  places (a laid-out window state with s00000001, a compact one with
  s00000003:74, a Bash call's cua-driver click with s0000002a) and
  DB_PASSWORD=hunter2abc9. Base: all three tokens went as {{SECRET_…}}
  (the second with its :74). This: all three as written, the password
  still a placeholder.
Not run: the full suite (one suite per machine; other sessions' runs
are on this box). Not tried: DeepSeek Harness and cua-driver
themselves.
2026-10-27 15:42:08 +08:00
yetone 7aeae59670 privacy: masked words can match as whole words only, by a switch under Masked words (acmilan_)
Settings › Privacy's masked words (脱敏词) were found anywhere: ABC masked
the ABC inside XABCD, and 123456 the middle of 91234567 or 0.123456. A
new row under "Masked words in any case", "Whole words only" (仅完整单词
匹配), makes each word match only where no letter, digit or _ is beside
it, and for a number no "." and digit either, so a decimal counts as one
value: ABC masks "ABC IS xxx" and name='ABC' but not XABCD or ABCDEF;
123456 masks a 123456 of its own but not 91234567, 0.123456 or 123456.78
("the code is 123456." still is). Chinese and Japanese letters count as
no letter there, since those scripts put no spaces between words: 张三
is still found in 我的同事张三今天来了, and ABC in 用ABC做. It is
independent of any case and works with it (xabc then Abc! masks only
Abc). A match inside a longer word is passed over one letter at a time,
so a whole one after it is still found. Off by default and for every
existing user: settings.json without redactWordsWhole reads false, and a
page from before it that saves without the field keeps what was set
(api.go, as redactWordsAnyCase). Each match goes as {{TERM_…}} and comes
back as written. Translated in zh, zh-TW, ja, de.

redact.Options.WordsWhole (wholeWord, wordRune); settings.RedactWordsWhole
(redactWordsWhole) reaches it through internal/masking; prefsKeep sends it
on every Settings save. docs/subsystems/gateway-routing.md has a bullet
for the user's own words, any case and whole words.

Tests, each red when its part is broken by hand:
- TestWordsWhole (internal/redact), the reporter's literal examples plus
  CJK and any case: with the whole-word check skipped, 10 cases FAIL
  "1 masked, want 0"; with the decimal check off, FAIL on 0.123456 and
  123456.78; with Han/kana counted as letters, FAIL on 张三, 用ABC做 and
  これはABCです. Every case round-trips through Restore.
- TestWordsWholeJSON: a request body and a tool call's escaped
  arguments; with the check skipped, FAIL "XABCD not kept as written".
- TestCountTokensRedacted/words_whole (internal/gateway): with
  masking.go not passing the setting, FAIL "redaction off changed
  content: …X{{TERM_…}}D…"; words_inside holds the default unchanged.
- TestSettingsRedactWordsWholeKept (internal/gui): with the not-sent
  guard removed, FAIL "…redactWordsAnyCase…: whole words false".
- redact-words-whole.test.cjs: 20 of 20 (Chromium and WebKit, en, zh,
  zh-TW, ja, de, 1100 and 640px); with prefsKeep's field removed,
  WebKit fails "a later save keeps it".

Run, in worktree magpie-wt/redact-wholeword at base 353519f55, sandbox HOME,
pinned caches, pipefail, tee'd:
- go test -tags nogui ./internal/redact ./internal/masking
  ./internal/settings ./internal/gui (TestCoreScriptBudget, i18n)
  ./internal/gateway ./plugins/redact: all ok.
- GUI: redact-words-whole, redact-words-any-case, i18n-keys 44/44;
  gui-zh-tw, gui-ja, gui-de 9/9.
- gofmt -l clean; go vet (darwin), GOOS=linux -tags nogui and
  GOOS=windows vet of the changed packages clean; go build,
  GOOS=linux go build -tags nogui, GOOS=windows go build ok.

Not run: the full go test ./... and the whole GUI suite (machine load
over 200 with other sessions' runs); the change reaches only the
packages above. Not tried: a real vendor request with the switch on;
the gateway test checks the body that goes out. A letter written as a
\u escape inside a tool call's arguments reads as no letter beside a
word (unescapedView), so it doesn't stop a match there.

Rebased onto origin/main 83368d994 (usage, signin, agent, gateway stream,
web page port, guard; app.js and gateway-routing.md touched elsewhere):
go test -tags nogui ./internal/redact ./internal/masking ./internal/gui
(budget, i18n) ok; redact-words-whole and i18n-keys 24/24.

Then onto 83368d994 (Codex thread descriptions; settings.go, app.js, i18n.js):
gofmt clean; go test ./internal/settings ./internal/masking ./internal/redact
and ./internal/gui -run 'Budget|I18n|Settings' ok.
2026-10-27 15:34:38 +08:00
yetone ea7c0067e0 privacy: each local model's confidence threshold is the user's to set
Yayoi_no_yume on X asked for the privacy model's threshold to be
adjustable: they read it as fixed at 0.5, and from their own use find
0.85-0.95 right for AstrLink. The 0.5 is Privacy Filter's (pf-serve's
argv default); AstrLink Guard already masked at its publisher's 0.8.

Both models now find at a floor of 0.5 (pii.Floor) and give each span
its score: Guard's least token probability (rounded through float32,
so a span read back from the cache file sits on the same side of a
threshold), pf-serve's own. masking.model keeps the spans at
pii.Threshold or over: settings.RedactModelScore[model] when it is in
[0.5, 1), else the model's MinScore (Privacy Filter 0.5, AstrLink
Guard 0.8). Settings -> Privacy shows a Confidence threshold row under
the model (app menu, 0.5 to 0.95 and Default), /api/privacy-model
takes do:"score". The setting is this computer's own, like the model.

The defaults stay. TestMaskEval's cases, rules + model + magpie's
checks, by threshold:

  Privacy Filter 0.5-0.8   masked 41/42  kept 112/113
  Privacy Filter 0.85-0.95 masked 40/42  (a Chinese name lost)
  AstrLink Guard 0.5-0.7   masked 42/42  kept 112/113
  AstrLink Guard 0.8-0.85  masked 41/42  (a phone in a tool result)
  AstrLink Guard 0.9       masked 40/42
  AstrLink Guard 0.95      masked 40/42  kept 113/113

The model alone does raise fewer false alarms higher up (Privacy
Filter's found-in-keep falls from 47 at 0.5 to 27 at 0.95, Guard's
from 8 to 2), but the checks after it drop most of those already, so
a higher threshold mostly costs values that should be masked.

Cache file: found-<model>.bin is now "pfound02" with a float32 score
per span. A "pfound01" file is still read, each span with score 1, so
texts cached before mask as they did and aren't asked again. For those
texts a higher threshold drops nothing and a lower one doesn't add a
Guard span scored 0.5-0.8 until the cache turns over (20000 answers).
merge() keeps the surer score of spans it joins. The eval recordings
(eval-model.json, eval-astrlink.json) were made again with scores,
from a scratch cache, the live found files untouched.

Run in the worktree at 11dcc743f + this change:
- go vet / gofmt -l on the touched packages: clean
- go test -count=1 -timeout 45m ./internal/pii/... ./internal/masking
  ./internal/redact ./internal/settings ./internal/gui ./internal/gateway: all ok (gateway 546s, rerun
  after an earlier run hit "no space left on device" on this machine;
  every failure in that run was a TempDir mkdir). This run caught
  TestSettingsSaveKeepsWhatItDoesNotSend wanting RedactModelScore set;
  it is now
- GUI: privacy-model.test.cjs 64/64 (chromium + webkit, 5 languages,
  1100 and 640px; the new threshold menu test among them),
  i18n-keys 4/4, redact-kinds, redact-rule-edit,
  redact-rule-row, redact-shape, redact-words-any-case all pass.
  masking-records 82/82, routing-masking 10/10, privacy-usage-stats 4/4,
  mask-actions 22/22. privacy-hides-accounts was 3/4 once (webkit en,
  page.goto's 5s at load ~290, the class of #3525, commented there),
  then 4/4 three times. Not run: the rest of the GUI suite.
Rebased on 508911e43 (which touched internal/pii fetch and mirror): at
that head, go build ./..., Linux and Windows go vet of pii, masking,
settings and redact, gofmt -l, and go test of pii/..., masking, redact,
settings and gui all ok; gateway not run again after the rebase.
Broken by hand: masking.model keeping every span (TestModelThreshold
  red); Threshold taking any value (TestModelThreshold red); the cache
  writing 1 for every score (TestRestartReadsWhatWasFound red); merge
  not keeping the surer score (TestMergeAcrossPieces red, after its
  joined span was made surer than the one it joins).
Not tried: the real app's window, Windows, Privacy Filter on a GPU
with the new score read (pf-serve itself is unchanged; it always sent
the score).
2026-10-27 14:10:33 +08:00
yetone 79c8667c92 gateway: Codex gives Claude its signed thinking back through encrypted_content
Codex calling a Claude model through magpie (mysterious_dove_96933 on
Discord): a reply's reasoning items carried only the summary, so Claude's
thinking signature and a redacted_thinking block's data were gone. On
the next request of a tool loop magpie sent Anthropic the turn as
[tool_use] alone, with thinking on, which Anthropic documents as a 400
("final assistant message must start with a thinking block"), and the
model lost its reasoning across calls either way.

Now the Anthropic decoders name a signature as Claude's (KSig with
sealAnthropic, Part.SignedBy). The Responses encoder and renderResponses
give each thinking block a reasoning item whose encrypted_content is
"magpie-claude1:" and the block's JSON in base64 (internal/claudeseal):
its summary beside it, an empty summary for a block signed with no
text, and redacted_thinking as an item of its own. parseResponses reads
it back into the block as Claude wrote it, in order, so anthropicBody
sends it as before for an Anthropic client. A Gemini thought's
signature isn't named and isn't sealed.

The envelope never reaches a Responses API: withoutClaudeSeals in
passthrough and forwardOnce (the item keeps its summary, one with none
goes), codexInputAs leaves such an item out for Codex's own models, and
codexUpstreamOn takes it out before the ChatGPT backend. OpenAI's own
encrypted_content is untouched. sessions.PortCodexRollouts writes such
an item as its summary, so a thread resumed against OpenAI itself isn't
refused. redact.MaskJSON already keeps a reasoning item's seal whole
(no change); TestMaskJSONKeepsClaudeBlocks holds that.

Run, at 5e3dd1d52 plus this change:
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/sessions/
  ./internal/redact/ ./internal/claudeseal/: sessions, redact,
  claudeseal ok; gateway ok but for TestResponsesStreamToolThenHiddenThinking
  (#1786), whose hidden cases wanted no reasoning item, the loss this
  fixes. They now want one item carrying the sealed block with an empty
  summary, and its guarantee (a whole stream, no panic) is unchanged;
  re-run green.
- gofmt -l clean; go vet (darwin) on the touched packages, GOOS=linux
  go vet -tags nogui ./internal/..., GOOS=windows go vet on the touched
  packages: clean.
- TestCodexToolLoopGivesClaudeItsThinkingBack (a fake Anthropic: signed
  thinking, redacted_thinking, a text-less signed block, tool_use; a
  Codex-shaped request with store false and the encrypted_content
  include; then the follow-up) fails on 5e3dd1d52: "stream=true:
  Anthropic was sent 1 assistant blocks, want 4". Passes now, streamed
  and not.
- Real: a sandbox HOME with only OpenRouter's key (Anthropic endpoint,
  anthropic/claude-opus-5.5, served by Claude Platform on AWS), magpie
  serve on its own port, a Codex-shaped two-turn tool loop at effort
  high, streamed and not: turn 1 gave a reasoning item with
  magpie-claude1: (3.1KB), turn 2 was 200 through /v1/responses →
  /v1/messages and answered from the tool output.

Broken by hand:
- withoutClaudeSeals a no-op: TestClaudeBlocksNeverGoToAResponsesAPI
  red, the relay sent magpie-claude1: items.
- codexInputAs not leaving them out: red, "ChatGPT backend would be
  sent …".
- sealing any signature (no sealAnthropic check):
  TestGeminiSignatureIsNotSealedAsClaudes red.
- portValue's reasoning branch off: TestPortLineDropsClaudeBlocks red.

Not tried: the 400 itself. Through OpenRouter, Opus 5.5 answered turn 2
with the envelope stripped too (the old shape), so this route shows
only the lost reasoning, not the refusal. Not tried on api.anthropic.com
directly, Bedrock or Vertex keys, or Claude's subscription (whose tool
loop stays inside Claude Code's run). Codex resuming a ported thread
against OpenAI with such items wasn't run.
2026-10-27 11:26:54 +08:00
yetone 89a9ded2cc redact: the masking eval scores each local model (#3578)
TestMaskEval runs once per model in pii.Models, each against its own
recording (testdata/eval-model.json for Privacy Filter, the new
eval-astrlink.json for AstrLink Guard, recorded through pii with the
publisher's files), and MAGPIE_EVAL_CACHE records every model found
there. A value known to come out wrong with AstrLink Guard says so in
GuardKnown: a token count taken for a secret (#3775) and a +81 phone
neither the rules nor it find (#3776).

Rules + model: Privacy Filter 41/42 masked, 1/113 wrongly; AstrLink
Guard 41/42, 1/113. Model alone: 40/42, 47/113 and 38/42, 3/113.

Run: go test ./internal/redact at the pushed head; removing either
GuardKnown makes it red.
2026-10-27 02:01:17 +08:00
yetone b3729b8d56 redact: a model's or a toolchain's name the local model takes for a secret goes as written
The owner's 脱敏 page showed groqAPIModel = "llama3-70b-8192" masked as
a secret by the local model. The real model, asked again, also takes
claude-3-5-sonnet-20241022 beside it for one. namesThing now holds
modelName: lower-case words joined by dashes with a size part (70b,
8x7b, 32k), an eight-digit date part (20241022) or a yyyy-mm-dd date
(nightly-2026-09-01). A diceware passphrase (correct-horse-battery-
staple) or maple-4-river-77 has neither and is still masked.

The page's other value, nightly-2026-09-01 as a name, was recorded by
the running v0.1.1370 (10-24). The model labels it private_person, and
main already drops it (a name with a digit, a word in lower case, since
611b9e173); the new rust-toolchain eval case holds that.

Run:
- MAGPIE_EVAL_CACHE=$HOME/.cache go test -run TestMaskEval ./internal/redact
  with the real model: re-recorded, both new cases ok in "both", the
  model's column WRONG for all three values.
- go test ./internal/redact ./internal/pii: ok. gofmt clean; go vet for
  darwin, linux and windows.
- Broken by hand: modelName taken out of namesThing → settings-model red
  (both values) and the four new TestModelMisreadsNotMasked cases. The
  digit check in personFits alone taken out stays green on
  rust-toolchain, since the lower-case-word check also drops it.

Not run: the packages that import redact (gateway and others) before
the push; the change only narrows what the model's secrets mask.
2026-10-26 22:16:02 +08:00
yetone 720e491d2b redact: the local model's ids, decimals, model names and products in agent sessions go as written
A reporter on X (tearicerice, 10-26) had Claude Code check what the
local model masked and found "大概95%以上都是误判". Run over the last
120 turns of 22 real Claude Code sessions, rules-only against
rules-plus-model, the model alone found 69 distinct values, ~55 of them
wrongly. modelFits and modelTakes now leave these as written:

- PHONE: a decimal (a metric's 104.21875033916251, 23 such values) and
  a value starting with a letter ("run 48213097715").
- SECRET: a value right after an id's name (Claude Code's "with ID:
  kq3m8zx2t", "(ID: …)", <task-id>…, "backgroundTaskId":"…"); a
  lower-case slug with a slash (qwen/qwen3-14b); a lower-case file name
  (make-icons.sh); a grep regexp with \| or \b; words with a time of day
  in them (release about 17:05Z); a hex or digit run whose key cue is
  further back than "key:" / "token is" (GH_TOKEN in "env -u GH_TOKEN
  gh run view 48213097716" made the run id a secret).
- SECRET spans that took in a JSON key (ledgerId":"gl_…) start after
  the key's `":"`.
- madeID takes ids with more words and a nanoid's - and _
  (req_gateway_<hex>, tb_Ra4K…-ZqT2…), except under sk/rk/pk/whsec/
  shpat/shpss/xoxb/xoxp, whose keys have that shape.
- ADDRESS: an ASCII value with no space and a slash (a transcript's
  path). A Chinese address has no spaces and is unchanged; "3/12 Smith
  Street, Sydney" still masks.
- EMAIL: a value with no @ (eu.stg.acme.io, a host).
- PERSON, one word: an acronym (CI), a camel-case product with a
  capital after 3+ lower-case letters (CodeRabbit; McDonald, MacKenzie
  still mask), and a word the same text has as a host's name (Greptile
  beside app.greptile.com; not an address's local part, matt.lee@…).

Measured again on the same 22 sessions: 20 distinct model-only values,
12 of them real (people's names, the user's emails, an AWS account). The
8 left wrong are single dictionary or product words (Alma, Greptile
where no host is in the same text, Harness, Reds, Todo, Zhipu), 查询,
and an org id seen bare in a grep. The sessions' values were read in a
scratch test that isn't committed, and its logs are deleted; every
value in the tests and here is made up in the sessions' shapes.

Tests: 19 TestModelMisreadsNotMasked cases and 6 TestModelFindsStillMasked
cases (a Stripe-shaped sk_test_ key, a hex after "token is", McDonald,
Rina beside rina.lee@…, +1 415.555.0132, an address with a slash). 9
evaluation cases (metric-decimals, run-ids, background-tasks,
model-names, ls-files, gateway-ids, transcript-path, pr-checks,
team-notes), recorded with the real model.

Broken by hand, one at a time (each red): the decimal and leading-letter
phone checks, the path address check, regexpLike, idAfter and its camel
and > forms, the clock check, secretCued (back to cued), the slug and
file name checks, the JSON key trim, EMAIL needing an @, the acronym,
camel and hostIn name checks, madeID's longer ids and its keyHeads.
A decimal check for ACCOUNT was green when broken (versionRe already
covers it) and was dropped.

Run: go test -count=1 ./internal/redact ./internal/pii (ok),
MAGPIE_EVAL_CACHE TestMaskEval (re-recorded, ok). gofmt -l clean; go vet
./internal/redact for linux, windows and darwin. The packages that
import redact (gateway, gui, masking, otlp, sessions, settings) were
still running at push, beside another session's gateway run; not a
record of a pass.

Not tried: the reporter's own sessions, the WorkBuddy AI group/flash
traffic in their screenshot (~160 values a request), or their version.
Not looked at in the GUI's Masking page; the change is in what is
found, not in how it is shown.
2026-10-26 16:11:11 +08:00
yetone 25341b4ca5 redact: an address needs a mail domain (xxx@Agents.md, x@pytest.fixture)
ydzh on Discord: masking took xxx@Agents.md and xxx@pytest.xxx for
email addresses. realEmail now also refuses a host that is a known
agent doc file (agents.md, claude.md, readme.md, ...) or whose last
label is not an ICANN TLD (publicsuffix) nor a local mail suffix
(local, internal, lan, corp, home, intranet, localdomain). So
decorator and module paths like pytest.fixture or
dataclasses.dataclass go as written, while me@notes.md, j@Gmail.COM,
admin@build.local and ops@mail.corp are still masked.

Run: go test ./internal/redact (all, evals included) ok;
go test ./internal/gateway -run 'Redact|Mask|Email|Privacy' ok;
gofmt -l clean; GOOS=linux and windows go vet ./internal/redact ok.
Broken by hand: with the new checks removed, TestEmailNeedsAMailDomain
fails 10 cases. Not tried: the real app; full suite (other sessions'
suites on the machine).
2026-10-26 15:32:09 +08:00
yetone dce7fe6096 redact: git@host, a git remote's SSH user, is not masked as an email (jumy on Discord)
jumy: "脱敏的邮箱, 会把git地址也算进去, 比如 git@xxxx". The EMAIL rule took
git@github.com out of git@github.com:o/r.git, so a remote reached the
model as {{EMAIL_…}}:o/r.git. git is the user every git host is reached
by over SSH (GitHub, GitLab, Gitee, a company's own), no one's mailbox.
realEmail, which the rule and the local model's EMAIL both ask, now says
no to a local part of git, any case. userhost already left git out
(notUsers). An address whose name only starts with git (gitte@,
git.lee@, github@) is still masked.

Run:
- TestGitRemoteIsNoEmail: 7 failures with the check pointed at another
  name by hand, green with it.
- go test ./internal/redact (whole package, ok), the gateway's
  Redact/Mask/Email/PII tests, gofmt -l.
2026-10-26 15:06:01 +08:00
yetone c2c88e85e9 redact: a date in the last year or ahead is not a birthday
JackyCcao on X: under Mask personal data the birthday rule took the day
the agent ran on, 2026-10-24, for a birthday in 122 requests. dateOK now
takes a date after 生日/DOB/born for a birthday only when it is over a
year before today (dateClock, held in the test). A date in the last year
or ahead is a run date, a deadline or a log's; a baby's birthday in a
prompt is far rarer than those. Older dates are masked as before.

Run: go test ./internal/redact (also TZ=UTC and TZ=Pacific/Kiritimati),
go vet for darwin, linux and windows, gofmt -l. TestBirthdayNotRecent
holds today at 2026-10-24 (today, yesterday, a year less a day, ahead,
each format) and then reads the real clock; with the year check taken
out by hand it is red ("生日:2026-10-27" masked). The GUI's
redact-kinds test only toggles the category and is unchanged.
Docs: gateway-routing.md and masking.html (en, zh, ja).
Not tried: the reporter's own request text (the screenshot shows only
the masked date), so which words were before it is not known.
2026-10-26 10:57:18 +08:00
yetone db6d1540ef redact: eval cases that reach more of modelTakes/modelFits
TestMaskEval's cases reached 5 of the 36 checks on model spans: breaking
any other one by hand left it green. This adds 21 cases (39 to 60), most
of them texts from modelfits_test.go and vendorchecks_test.go, the
places the model was seen misreading, and records the real model's spans
on them (testdata/eval-model.json).

Breaking each check by hand (breaks.py: one replacement in model.go,
TestMaskEval run, file restored) now turns 13 red (5 before):
secret-madeID, person-2runes, email-realEmail, person-zhTrim,
person-assistant, account-numberLike, account-cue, address-letter,
secret-wordstart, secret-uuid, secret-hexwords, secret-hexcue,
edge-delimiter.

Still green, because the real model gives no such span on any text tried
(24 more probed) or another check catches the same span first:
secret-namesThing, secret-len8, person-snakeWord, account-madeID,
cut-from-word, person-chars, person-filedot, person-pathpart,
person-colon, person-lowerword (person-chars keeps the same lower-case
word), account-hex, account-version, the four phone checks, secret-pattern,
secret-json, secret-link, secret-base64, email-wordstart, email-modcache,
email-userinfo. Their unit tests in modelfits_test.go still cover them
with recorded spans.

A new real miss: "hex40 ok? 1 <sha1>" is one secret span "1 <sha1>" to
the model, and the hex-words check only looks at the first field. Filed
as #3597 and marked Known.

Totals at this head (rules / model / both, masked and wrongly):
16/40 0/89, 38/40 28/89, 39/40 1/89.

Run: MAGPIE_EVAL_CACHE=$HOME/.cache go test -run TestMaskEval -v
./internal/redact (recorded, then replayed green); go test -count=1
./internal/redact ./internal/pii ok; go vet ./internal/redact for darwin,
linux and windows; gofmt -l clean; breaks.py over all 36 checks.
Not tried: the full suite (only test files changed in internal/redact).
2026-10-25 19:17:53 +08:00
yetone 552cdf8071 redact: a value the model spans from the delimiter before it is masked (#3591)
The model's span may start at the token before a value: the `":"` of
a JSON field, a CSV row's comma. A phone number in
{"phone":"+86 139 1234 5678"} came as `":"+86 139 1234 5678`, and in a
CSV row as `,+81 90-1234-5678`, which the PHONE check took for no
number, and it went as written. A name came as `"Wei Zhang"` and was
masked with its quotes, so the JSON lost them. modelSpans now trims
spaces and `"',;:` from both ends of a name's, a phone's, an
address's, an account's and an email's span; a secret's only spaces,
since a password may start or end with a quote.

Found by TestMaskEval: its 3 #3591 phones are no longer Known, and
"both" reads 33/34 masked, 0/40 wrongly (from 30/34).

Run: go test ./internal/redact and ./internal/pii ok; -run
'Mask|Redact|Privacy' ./internal/gui ./internal/gateway ok; go vet
darwin, linux, windows; gofmt -l clean.
Broken by hand: edge = isSpace for every kind: TestModelSpanLeavesDelimiters
red (both phones as written, the name's quotes gone) and TestMaskEval
red on the 3 phones.
Not tried: the full suite (internal/proc's #3567 is red on main), a
real request through the gateway with the model on.
2026-10-25 17:44:52 +08:00
yetone 033990e642 redact: the masking evaluation starts with nothing known
A value Mask masks is known from then on, and masked wherever it is
again (known.go), Preview's too. TestMaskEval ran after the tests that
masked hunter2pass, rina.k@fastmail.com and the like, so in the
package's full run what they masked was masked in its cases too, and
the rules' column was not the rules': with one test before it that
masked the eval's phones, rules read 19/34 for 16/34. Forget
(export_test.go) lets every value go before the cases.

180cfb565's body says 38 cases; there are 39.

Run: go test ./internal/redact (TestMaskEval in the full run and
alone: 16/34 rules either way) and ./internal/pii ok; go vet darwin,
linux, windows; gofmt -l clean.
Broken by hand: without Forget and with a test before it that masks
the eval's phones, rules read 19/34.
2026-10-25 17:44:52 +08:00
yetone 180cfb565e redact: an evaluation of the masking, with the rules, the model and both
TestMaskEval scores 38 made-up texts of the kinds agents send (prose,
code, logs, tool results, JSON, CSV, Chinese) with 34 values to mask
and 40 to keep. The cases start from what users reported masked
wrongly (#3144, #3143, #3029, #3538, #3577, d3db461bb, 611b9e173,
#1977) and add the values masking is for. It logs, by kind, how many
each way masked of those to mask and, wrongly, of those to keep:
the rules alone, the local model as it said it, and both with the
checks on what the model found, and lists every value one way got
wrong.

What the real model said is recorded in testdata/eval-model.json, so
the test replays "both" with no model and no network, and fails when
a value comes out wrong, or a Known one right. MAGPIE_EVAL_CACHE
points it at a downloaded model to record again.

Baseline (privacy-filter q8, M4 Pro):
  rules  16/34 masked, 0/40 wrongly
  model  32/34 masked, 8/40 wrongly
  both   30/34 masked, 0/40 wrongly
The checks take all 8 of the model's wrong ones off. Of the 4 misses,
3 are phones the model found with the delimiter before them
(`":"+86 …`, `,+81 …`), which the PHONE check turns down (#3591),
and 1 is 刘洋, which the model doesn't find (#3592). Both are Known.

Run: MAGPIE_EVAL_CACHE=$HOME/.cache go test -run TestMaskEval -v
./internal/redact against the installed model (recorded); go test
./internal/redact ./internal/pii ok; go vet for darwin, linux,
windows; gofmt -l clean. internal/proc's TestNoCommandBypassesProc is
red, on origin/main too: internal/tui/keep.go (#3567).
Broken by hand: modelFits off: 4 keeps masked and the 3 #3591 phones
reported right, red. A case's text changed: red, the recording is
stale. Taking snakeWord, epochNumber or madeID's SECRET check off
alone stays green: the model makes neither mistake on these texts,
or a second check catches it.
Not tried: the model on Linux or Windows, or on the CPU.
2026-10-25 17:41:10 +08:00
yetone e4809a150a redact: a key of digits only after 密钥为, token 是, apikey:… is masked; PIN码, 安全码, 授权码 join the names (CyberCaius on Discord)
"密钥为12231241" in Settings → Masking's 试一试 came back "这里没有需要脱敏的
内容". ee715c2e0's key rules (a CJK name for a key or token, or an English
one before 为/為/是/:) asked for letters in the value, so that
"RSA 密钥为 2048 位" stays; an all-digit key went as written. 密码/口令 took
digits already (714ab8e8b).

Now:
- After a key's name and 为, 為, 是, :, :, =, は or 는, a value of six digits
  or more is masked as SECRET, by the CJK names (密钥, 秘钥, 令牌, 金鑰, トークン,
  토큰…) and the English ones (token 为, apikey:, API Key 是, secret 為).
  Not when a unit follows it (位, 字节, 个, 次, 秒, 毫秒, 天, ms, byte…), with
  no 为/是/: between (密钥 12345678), or under six digits.
- New names: PIN码, PIN碼, PIN 码, 安全码, 安全碼, 暗証番号, 비번 for a password
  (any value of four or more, digits too, as 密码 has); 授权码, 授權碼 for a
  key; pin and pin code before 为/是/: in English (six digits or more, a
  word boundary first, so "spin 是 …" stays). The CJK names are matched in
  any case (pin码).

Left as they were (tested): RSA 密钥为 2048 位, 密钥为 12345, 令牌有效期是 86400,
令牌是 300000 毫秒, 密钥长度为 4096000 位, token 是 3600000 ms,
key 是 1048576 byte, 令牌桶容量为 100000, 密钥 55661237, pin 为 1934,
const token = 44102939;, {"token": 44102939}, maxTokens: 128000, and every
case of TestCJKPasswordMasked, TestCJKSecretNamesMasked and 511c4a765's
code tests (code_test.go).

Run at this head:
- go test ./internal/redact ./internal/pii ./internal/settings
  ./internal/otlp ./internal/sessions ./internal/gui -count=1: ok
- go test ./internal/gateway -run 'CJK|Mask|Redact|Privacy|PII|Secret': ok
- go test ./internal/redact -run 'CJK|Code' -count=3 -shuffle=on: ok
- gofmt -l, go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui
  ./internal/redact: clean
- Broken by hand: with the parent's redact.go, TestCJKDigitKeysMasked
  fails 19 of its 21 masked cases (密码为/口令: already masked).
- With Shape on, 密钥为12231241 goes as a made-up 8-hex key and comes back.

Not tried: the GUI try box in a running magpie (no GUI file changed), and
the full suite.
2026-10-25 16:55:06 +08:00
yetone faa79ea2f5 redact: a Unix time the local model takes for a phone is not masked (#3577)
id.null (v0.1.1483) saw a tool result's "timestamp": 1792903687 go as
"timestamp": {{PHONE_c2ukh7gk}}. The PHONE rule needs eleven digits, so
the local model found it; v0.1.1457's check leaves a bare number alone
unless a cue is before it, but cues match inside words, and a log's
"tool_call" (or "telemetry") is "call" (or "tel").

A ten-digit time, or a thirteen-digit one in milliseconds, starting with
1 and nothing else, is now never a phone, cued or not: a North American
area code starts with 2 to 9, and a Chinese mobile is eleven digits.
The loose cues themselves are #3585.

Run: go test ./internal/redact ok; go vet darwin, linux, windows; gofmt
clean. Broken by hand: without the epochNumber check
TestModelPhoneKeepsUnixTime is red with the reporter's line masked.
Not tried: the real model on the reporter's whole tool result (their
screenshot only has the one line); the full Go suite.
2026-10-25 16:48:07 +08:00
yetone fc91e58ba4 redact: a bare JSON number ("timestamp": 17929036837) is not masked as a phone (id.null on Discord)
The 脱敏 before/after view showed a tool result holding a session file's
JSONL line, and its "timestamp": 17929036837 went as {{PHONE_…}}. The
PHONE rule is 1[3-9]\d{9} bounded by digits, so any 11-digit number
starting 13-19 is a CN mobile wherever it sits. A phone, a card or an ID
number in JSON is a string; a bare number there is a count, an id or a
time.

Now a personal kind's value that is all of a bare JSON number is left,
judged by where it sits and its form, not by the key's name: digits only,
after "key": (an object's value) or inside an array of numbers, with only
, } ] or the text's end after it. It sits beside the decimal check
(noDecimals, now noNumbers), so it holds for what the rules, the model
and values known before find alike. A BANK_CARD (Luhn-valid snowflake)
and an ID_CARD's digits as JSON numbers are left the same way.

Still masked (tested): "phone": "13800138000", ["13800138000"],
phone:13800138000, "call 13800138000, thanks", 我的号码 13800138000,谢谢,
"numbers 13900139000, 13800138000]" (no [ before), a phone inside a JSON
string's text, "card": "4111111111111111", and every case of
TestStandaloneNumbersStillMasked. "phone": 13800138000 as a number is
left too; that is the cost of not going by the key's name.

Run at this head:
- go test ./internal/redact ./internal/pii ./internal/settings
  ./internal/masking ./internal/otlp ./internal/sessions ./internal/gui
  -count=1: ok
- go test ./internal/gateway -run 'CJK|Mask|Redact|Privacy|PII|Secret': ok
- gofmt -l, go vet, GOOS=windows go vet, GOOS=linux go vet -tags nogui
  ./internal/redact: clean
- Broken by hand: with origin/main's redact.go, TestBareJSONNumberNotMasked
  fails 7 cases (the reporter's line, {"n": 13800138000}, a spread-out
  object, two arrays, the card and the ID number). The 10- and 13-digit
  epochs were not masked before either; they are in the test to stay so.

Not tried: the GUI before/after view in a running magpie, and the full suite.
2026-10-25 16:47:29 +08:00
yetone 359da679db redact: 试一试 shows the made-up key when "keep key form" is on, short keys and named keys too
A user turned on 保留密钥格式 (v0.1.1497) and 试一试 still showed
{{SECRET_…}} for "用密钥 sk_abcdefg 部署可以吗". Three gaps:

- Preview wrote every value with tag, which never looked at Shape: a
  sibling v0.1.1497 missed. It now makes the same key shapeOf gives a
  real request, without storing it.
- shapeOf made up nothing under 16 characters, so sk_abcdefg stayed a
  placeholder even on a real request. Now 8 or more, with at least 6
  characters made up after the prefix.
- 密钥 OPENAI_API_KEY=sk_… is found with its name (the CJK key rule
  takes NAME=value as the value), and '=' isn't a key character, so it
  fell back to a placeholder. The name now stays as written and only
  the key after it is made up and remembered, so a reply naming the key
  alone is put back too.

Run: go test ./internal/redact ./internal/settings, -tags nogui
./internal/gui, ./internal/gateway -run 'Redact|Mask|Shape|Privacy' all
ok; go vet darwin, linux and windows (nogui); gofmt clean.
Broken by hand: Preview back to tag, minShape 16, the minRandom check
removed and splitName turned off each turn TestShapeShortAndPreview,
TestShapeKeepsAName or TestMaskingPreviewKeepsKeyForm red; storing the
whole NAME=value turns TestShapeKeepsAName's Restore red.
Not tried: the GUI suite (no front-end change) and a real model's reply
naming the made-up key; the full Go suite.
2026-10-25 16:16:27 +08:00
yetone bea9f905d0 redact: a key can go as a made-up key of its own form, not a placeholder (Charles Cao on X)
Charles Cao on X (2114238140835844575) asked for a format-preserving
swap: sk_w3axCByTQgK1PxqPhfKTrJOLBqz6sbZv sent as another sk_ key of the
same shape and put back on the way home. With Mask secrets on, a key went
as {{API_KEY_xxxxxxxx}}, which a tool's check of the key's form fails
and a model may remark on.

Settings › Privacy has "Keep a key's form" under Mask secrets (shown only
while secrets are masked; off by default, so nothing changes for anyone
who doesn't turn it on). settings.RedactShape → redact.Options.Shape;
api.go keeps it when a page from before doesn't send it.

How (internal/redact/shape.go):
- Only a secret's kind, 16+ characters, all of [A-Za-z0-9-_.]. Personal
  data, the user's words and anything else still go as placeholders. A
  made-up key needs no JSON escaping.
- Prefix kept (sk-proj-, sk-ant-api03-, github_pat_, AKIA/ASIA, or up to
  4 letters plus - or _), same length, separators in place, and each
  other character a random one of the same class. A hex key stays hex
  of its case. Random from HMAC(placeholder key, kind+value), so it is
  the same every turn and a vendor's prompt cache still matches.
- Kept in values like a placeholder (makeRoom shared with placeholder),
  so masking records, Value(), signed-thinking re-masking (the put
  closure) and known-value re-masking work unchanged; kindOf reads it.
- restore() puts made-up keys back first, then placeholders.
  RestoreJSON no longer returns early when one is in the body;
  hasShapes copies nothing while none was made.
- A stream holds an event's end that may start a made-up key
  (partialTail → shapeTail), but never one inside a key that has come
  whole: a key ending in "s" is also the start of every sk_ key, and
  without that its end was held and the key went out unrestored (found
  as 1 in ~40 fresh processes; 0 of 150 after).
- apply() leaves a made-up key that came back unrestored alone
  (outsideShapes), as it does a placeholder.

Tests: shape_test.go — form kept (the reporter's key, hex, ghp_,
sk-proj-), same fake twice, Restore; off is placeholders; email/short/
odd values not shaped; MaskJSON then RestoreJSON with escaped tool
args; signed thinking re-masked to the same fake; no re-mask of a fake;
a stream split mid-key, after one character, and a key ending as one
starts. GUI: redact-shape.test.cjs (both engines, 5 languages, 1100 and
640px; row under Mask secrets, Off by default, one save with the rest
kept, no scroll, a later save keeps it; no row while secrets are off).
redact-words-any-case now finds Mask personal data by place after the
new row, not by index.

Broken by hand, each red: no restoreShapes (KeepsForm, JSON, Stream),
no shapeTail (Stream), no outsideShapes (JSON), no hasShapes (JSON),
put ignoring Shape (all three), shapeTail without the whole-key bound
(Stream).

Budgets: app.js 1,321,994 → 1,322,289 and the core 1,529,542 →
1,529,837, the row's 295 bytes, Settings' own row, no room added.

Doc: docs/subsystems/gateway-routing.md, a bullet beside the other
masking options.

Run at 4dfd88206 + this change (worktree key-shape):
- GUI (node --test, playwright 1.62.0, both engines): redact-shape
  22/22, redact-words-any-case 20/20, i18n-keys 4/4, privacy-model
  24/24, redact-kinds 22/22, mask-actions 20/20, masking-records
  52/52, provider-proxy 8/8, click-scroll 22/22.
- go test -tags nogui ./internal/gui ./internal/redact
  ./internal/settings: ok (internal/masking has no tests).
- TestShapeStream in 150 fresh processes: 0 red.
- Rebased on 04439c859: budget tests, internal/redact,
  internal/settings ok; gofmt clean; vet -tags nogui on darwin, linux
  and windows ok; i18n-keys 4/4.
- Earlier, at load ~40: account-discovery 22 red, red the same on
  origin/main defbb1a15, #3497 (ggbdpq has it); redact-rule-edit
  webkit zh-TW 420px red once, 3/3 alone, #3407.
- The full suite was not run before this push: it is queued behind
  other sessions' suites (one per machine).
Not tried: a real vendor turn with the setting on.
2026-10-25 15:35:52 +08:00
yetone ee715c2e0e redact: a key or token after 密钥, 令牌, 金鑰…, or apikey/token before 为/是/:, is masked (CyberCaius on Discord)
714ab8e8b masked a password after 密码/密碼/口令/パスワード/비밀번호. The reporter
came back with the rest of how a secret is sent in a Chinese chat: "密钥为 xxx",
"apikey 为 xxx", 密钥是, 秘钥, 私钥, 令牌, "token 是 xxx", "API Key 为 xxx". These
went to the vendor as written.

Now:
- A value after a CJK name for a key, secret or token is masked as SECRET:
  密钥, 密鑰, 秘钥, 秘鑰, 私钥, 私鑰, 金钥, 金鑰, 令牌, 权杖, 權杖, 秘密鍵, トークン,
  シークレット, APIキー, アクセスキー, 토큰, 비밀키, API 키. The value has letters and
  digits both, or is 16+ characters with a letter, so "RSA 密钥为 2048 位" stays.
- An English name (password, passwd, pwd, secret, token, api key, access key,
  private key, credential, key; DB_PASSWORD and access_token too) right before
  为, 為, 是 or a full-width colon is masked the same way. "token: x" with an
  ASCII colon stays the config rule's, as before.
- 为 and 為 join :, :, =, 是, は, 는 after any CJK name, so "密码为 hunter22" is
  masked too; 암호 (Korean) joins the password names.

Left as they were (tested): 请输入密钥, 请输入密钥:, 密钥管理, 忘记密钥了怎么办,
令牌桶算法, 私钥文件放在哪, 密钥:${API_KEY}, 密钥:****, token 是 ****,
apikey 为 ${OPENAI_API_KEY}, RSA 密钥为 2048 位, token 是 expired, 这个 key 是 value,
token 是 abc, key 是什么, API Key 为空, and every case of TestCJKPasswordMasked.

Cost: the English rule is run only near 为/為/是/: (fold, 24 bytes back,
260 ahead), and the CJK rules only near their names. Doing that showed that
matches() looked back for the line's start from every fold marker through
the whole text, which is quadratic on a one-line request body: with the
English rule folded on key/token, Mask over 1.5MB of dense text took 10.4s
(0.12s before). The line's start is now looked for no further back than
`back`, which is what the window used anyway. Benchmarked Mask on 156KB of
dense Chinese, of dense code+JSON, and on redact.go itself, against
origin/main: within noise of it on a box at load ~200 (zh 31-36ms vs 13-37ms,
code 72-84ms vs 55-72ms, src 12-14ms vs 24-36ms); benchmark not committed.

Run at this head:
- go test ./internal/redact ./internal/masking ./internal/otlp ./internal/pii
  ./internal/settings ./internal/sessions -count=1: ok
- go test ./internal/gateway -run 'CJK|Mask|Redact|Privacy' -count=1: ok
- gofmt -l, go vet ./internal/redact, GOOS=windows go vet ./internal/redact: clean
- Broken by hand: with origin/main's redact.go, TestCJKSecretNamesMasked fails
  16 of 19 masked cases and the JSON body case (账号密码 admin123 and 口令是 …
  were already masked). With the CJK rules' window back set to 0,
  "WiFi密码:20261025" and "admin密钥是k9j8h7g6f5" go unmasked (fixed with back 64).

Not tried: the GUI try box in a running magpie, and the full suite.
2026-10-25 15:27:39 +08:00
yetone 714ab8e8bf redact: a password after 密码, 密碼, 口令, パスワード or 비밀번호 is masked (CyberCaius on Discord)
"密码:786kih" in Settings → Masking's try box came back "nothing to mask", and so
went to the vendor as written. The password rules only knew English field names
(password = …, as configs have them) and asked for 8+ characters of letters and
digits both, since code calls many things a password. Nothing in code is called
密码, so after a CJK name for a password any value of 4 or more is taken, digits
only too, after :, :, =, 是, は or 는, quoted or not. A sentence's closing stop
stays outside the value.

Left as they were: "请输入密码:", 密码:${DB_PASS}, 密码:****, 忘记密码了怎么办,
修改密码功能, and a value of 3 (密码:abc). English "password: abc12" with a short
value is unchanged; issue filed for it.

Run at this head:
- go test ./internal/redact ./internal/masking ./internal/otlp ./internal/pii
  ./internal/settings ./internal/sessions -count=1: ok (every package that
  imports redact but gateway and gui)
- go test ./internal/gateway -run 'CJK|Mask|Redact|Privacy': ok
- gofmt -l, go vet ./internal/redact: clean
- Broken by hand: with origin/main's redact.go, TestCJKPasswordMasked fails 7
  of 7 masked cases; green with the rule.

Not tried: the GUI try box in a running magpie, and the full suite.
2026-10-25 14:50:13 +08:00
yetone 641b1217f2 redact: a URL's user:password@host is a PASSWORD and a host, not one EMAIL (#3538)
With Mask personal data on, postgres://app:hunter2pass@db.acme-corp.cn:5432/x
went as app:{{EMAIL_…}}:5432/x: the EMAIL rule took hunter2pass@db.acme-corp.cn,
which starts where the PASSWORD rule's value does and is longer, so it won
the overlap. The kind was wrong and the host the model may need was hidden.

Now an EMAIL match whose start is inside a URL's authority (after
scheme:// with no /, ?, #, space, quote or @ between) is turned away
(notUserinfo, the rule's `at`), and the local model's EMAIL the same way
(modelFits). The password is the PASSWORD rule's and the host goes as
written. An address in a URL's path or query, in mailto: and in prose is
an EMAIL still.

Sibling found on the way: the PASSWORD rule asked for a user before the
colon, so redis://:pass@host (Redis has a password and no user) was not
masked with Mask secrets alone, and was only covered by the EMAIL accident
with personal data on. The user part may now be empty; without that the
email fix would have sent a Redis password as written.

Behaviour change to note: a userinfo with no password
(https://yetone@github.com/..., ssh://git@gitlab...) was an EMAIL and now
goes as written; it is a user name in a URL, not an address. With Mask
personal data on and Mask secrets off, a URL's password now goes as
written, as Mask secrets off says (it went as an EMAIL by accident).

#3029's file names (…@2x.jpg) are untouched: realEmail is unchanged and
TestFileNameIsNoEmail/TestMoreFileNamesAreNoEmail pass. #3365 (rule SECRETs
and known values) is a different rule; this changes nothing it reports.

Test: TestURLUserinfoIsNoEmail (internal/redact/userinfo_test.go) with the
report's literal string, mysql://, amqp://, mongodb+srv://, https://user:pass@,
redis://:pass@, a user with no password, ssh://git@, and emails in prose,
mailto:, a URL path, a query, and a query after a userinfo; a request via
MaskJSON; and the local model's EMAIL.

Broken by hand:
- redact.go and model.go reverted: red, 9 table cases plus the request and
  model checks (the literal went as postgres://app:{{EMAIL_…}}:5432/x).
- model.go alone reverted: red on the model check only.
- the PASSWORD regex's user back to +: red on both Redis cases (with
  personal on it went fully unmasked).

Run at this head (rebased on origin/main d153f0259):
- go test -count=1 ./internal/redact/... ./internal/masking/... ./plugins/redact/...: ok
- go test -count=1 ./internal/gateway/ -run 'Mask|Redact|Privacy|Masked': ok
- gofmt -l internal/redact internal/masking plugins/redact: empty
- GOOS=linux, windows, darwin go vet on the three packages: ok
Not run: the full suite (no suite lock on this machine; owner: don't hold
the push for it). Not tried in the GUI's Try it preview by hand; it calls
the same redact.Preview path the tests exercise.
2026-10-25 09:57:21 +08:00
yetone 611b9e1731 redact: what the local model misreads in agent requests is not masked
With "Use a local model" on, the model masked far more than the rules
did. Over 3 MB of real Claude Code requests (19,258 texts, the fields
MaskJSON leaves as sent skipped) the model alone masked about 1,800
pieces before this change, almost all wrong; the rules masked 17. It
took the turn's <total_tokens> count, run ids, commit hashes and
versions for accounts; Claude, Opus and other model names, a user name
inside a path and skill names for people; pieces of toolu_/srvtoolu_
ids, of base64 images, bare hashes, grep alternations, session file
names, links and Go module-cache names for secrets.

modelFits now judges each span the model reports against the text
around it: a span cut out of a longer word is no finding; a person's
name has no digits, path signs or lowercase words (bar van, de, bin and
the like) and no assistant's name; an account or phone number is
number-like and not a hash, version or size, and a bare run of digits
needs a cue before it ("account", "卡号", "phone", "手机"); a secret
starts with a letter or digit, is not a link, a UUID, a pattern of
words or a piece of a base64 run, and a bare hex run needs "key",
"token", "password" or 密钥/密码/令牌 before it. madeID takes prefixes
up to 8 letters (srvtoolu_).

After: the model masks 32 pieces on the same texts, 13 of them real
email addresses; what's left wrong is mostly a lone capitalised word
(Rerun, Relay, Xferd, Alma). On the synthetic set rules+model miss 1 of
20 secrets (rules alone 4) and flag 0 of 15 clean texts. The default
stays off.

Run at this head (rebased on 5d2260d3e):
- go test ./internal/redact: ok. TestModelMisreadsNotMasked holds the
  real bytes of 23 misreads, TestModelFindsStillMasked 9 real finds
  (an account with its cue, Rina Kowalczyk, Ludwig van Beethoven, a
  mobile and a London number, an address, a secret, a cued hex key,
  an email). With modelFits taken out of modelSpans by hand, 17 of the
  first 18 misreads went red.
- The corpus and synthetic measurement with the real privacy-filter
  q8 model (a scratch test, not committed; the corpus stays local).
- go vet (darwin, linux, windows) and gofmt on internal/redact: clean.
- Full suite (-timeout 45m, behind other sessions' runs): queued, not
  finished at push.

Not tried: the GUI, since nothing in it changed; a request through a
running gateway with the model on.
2026-10-25 06:05:06 +08:00
yetone 511c4a765e redact: code naming a secret (secretKey: Uint8Array, toBase64Url(…)) is not masked as one
Kieran Zhang on X (10-25) showed TypeScript masked as secrets:
`secretKey: Uint8Array;`, `details.2`, `toBase64Url(...)`. The SECRET
rules took any letters-and-digits value after a secret's name, and an
identifier like Uint8Array or a call like toBase64Url has both.

Both SECRET rules (the named-secret one and the bare "key" one) now ask
notCode: a value that is an identifier path (a.b.c) is code, not a
secret, when a "(" follows it (a call), or when it sits unquoted after a
":" and code punctuation (; , ) } ] | ? & < >) or the end follows (a
type or an object member). A quoted value, an `=` assignment, or a YAML
style `password: Passw0rd123` line is masked as before.

Run at this head:
- internal/redact TestCodeIsNoSecret: the reporter's four literal lines,
  a union type, an object member and a spaced call go as written; seven
  real secrets (quoted, escaped JSON, env, YAML, query-like) still mask.
  Red on the old code (6 of them masked), green after.
- go test -timeout 45m ./internal/gateway ./internal/gui ./internal/otlp
  ./internal/pii ./internal/redact ./internal/sessions ./internal/settings:
  all ok except internal/gui TestMainWindowCorners, an AppKit window
  killed at its 40s deadline at load ~146; it is red alone too, filed as
  #1936 and #2645, and this change doesn't reach it.
- go vet on darwin, linux and windows; gofmt -l clean.

Not tried: the reporter's own file in a live session; an unquoted
`apiKey: SomeIdent,` in YAML now goes as written, which reads as code.
2026-10-25 03:53:35 +08:00
yetone 2dfaf75539 redact: a masked body is held at its size, not in a buffer grown by doubling (#3383)
With masking on, the masked body is what a request holds while it
streams (MaskJSON, 285 MB live in the report's heap). walk built it in a
bytes.Buffer grown by doubling, up to twice the body. It now makes room
for the body and a sixteenth at the first value it masks, and copies the
result to its size when placeholders grew it past an eighth spare.

Run:
- the heap probe, 8 requests of 9.7 MB held mid-stream with Privacy
  masking on: 138 MB before, 86 MB after (Anthropic to Anthropic);
  translated to Chat 235 MB before, 183 MB after.
- TestMaskedBodyHeldAtItsSize: green; red with both changes off
  ("the masked body of 4356589 bytes is held in 7077888").
- go test ./internal/redact/ ./internal/masking/ ok; gateway -run
  'Mask|Redact|…' ok (see the commit before).
2026-10-24 21:00:05 +08:00
yetone 9b57261b62 masking: a record keeps its request as sent, how long masking took and what the answer put back
For the 观测 › 脱敏 page's request view. In memory only: the masked body
of the latest 100 requests (each up to 4MB, 64MB in all), and by
placeholder how many places of the answer had the value put back
(redact.Writer.Put, counted once per place even when a stream splits
the placeholder). Took (µs) is written to disk too; it holds nothing of
the request.

GET /api/masking/sent?key= gives the body, POST /api/masking/values the
values the masker still remembers, both no-store.

Run: go test ./internal/maskrec ./internal/redact ./internal/gui
-run TestMaskingRecordsAPI and ./internal/gateway -run TestMasked; ok.
Broken by hand: without toldBack, TestMaskedRecordKeepsSentAndBack is red.
2026-10-24 19:41:02 +08:00
yetone 50f52b540b redact: a text masked for a vendor before is masked as it was then, so a cached prompt stays cached
With Privacy masking on, a value masked once is "known" and masked
wherever a later request has it (redact/known.go). When a rule first
finds a value in a later turn (a tool printing DB_PASSWORD=...), that
value was masked from then on in the system prompt and the turns already
sent with it as written. The prefix the vendor had cached changed, so
the whole prompt was written to the cache again and none of it was read.

Reported by audie on Discord: DeepSeek Harness on a routing group served
by a custom Anthropic-compatible provider. Adjacent turns 10s apart had
cache_read 0 and cache_write 412K to 427K.

Fix: Mask and MaskJSON (the vendor-bound paths, via masking.Masker) now
use sentKnownSpans. A text masked before gets the known values it had
the first time, keyed by a sha256 of the text and the options. Only
hashes and spans are kept, never a value, in two generations of 65536.
New text still gets every known value masked. Scrub (archives, sessions,
OTel; local only) keeps the latest known set.

Unchanged: if magpie restarts, or a text falls out of both generations,
the text is masked under the current known set once, as before.

What was run:
- internal/redact TestSentTextKeepsItsMasking and internal/gateway
  TestMaskedConversationKeepsItsCachedPrefix. The gateway test sends a
  dsh-shaped Chat Completions conversation to a group with an Anthropic
  member, and a Claude Code-shaped /v1/messages one. It checks that each
  turn's system, tools and earlier messages reach the fake upstream byte
  for byte. Both tests are red with sentKnownSpans forced back to
  knownSpans: the system prompt became "{{SECRET_...}}" on turn 3. Both
  are green with the fix.
- With masking off, a probe of the same dsh shape had the system, tools
  and earlier turns byte-identical on every turn.
- gofmt -l: clean. go vet: darwin, GOOS=linux -tags nogui ./...,
  GOOS=windows ./...: clean.
- Full suite at 8187919d7 (this tree, on origin/main bf2e067ef):
  set -o pipefail; go test -tags nogui -timeout 45m ./..., through the
  suite lock. 69 packages ok, none red (gateway 519s, agent 393s).

Not tried: audie's real setup. Their Privacy setting isn't known; with
masking off this is not the cause, and every breakpoint reading 0
(even the unchanged system block) points at the provider's own cache or
pool. Not tried against a real Anthropic or relay account. GUI not
touched, so the GUI suite was not run. Windows tests not run.
2026-10-23 20:53:53 +08:00
yetoneandggbdpq 243594410d redact: a tool call's arguments stay JSON when a value follows an escape (#3022)
A history tool call's function.arguments is JSON text inside a string.
MaskJSON masked it as plain text, so the n of a \n started a match:
"\n@mcp.tool()" became "\{{EMAIL_…}}()", the arguments were no longer
JSON, and Ollama Cloud refused every turn that replayed the call with
400 "invalid tool call arguments". Reported by xiaobaifly7 and reproduced
independently by Shane-Meng (\n\n\n@pytest.mark…).

Where a string holds JSON text (asJSON), mask now reads it the way the
vendor reads it once it is unescaped:
- unescapedView: a same-length view in which \n, \r, \t, \b and \f read
  as control characters and a \u escape reads as line breaks, so no word
  starts or ends on an escape's letter. \" \\ \/ stay as written, so the
  SECRET rule's \"-aware quote and Windows paths read as before.
- outsideEscapes: any span (rule, word, model, known) that starts or
  ends inside an escape is cut back to the escape's edges, so the JSON
  holds and what the span held is still masked. A span left empty is
  dropped.
- unescapedPut: the value kept for Restore is the unescaped one, so
  Restore (which escapes it again in arguments) gives the agent exactly
  what it wrote. Before this, a private key's \n came back as \\n.

Ported from ggbdpq's hunt53-f-redact-json-escape. Their test
TestMaskJSONKeepsArgumentsJSON is kept verbatim. Their guard alone let
"\njo@quill.dev" through unmasked, so this port also adds the view, the
trimming and the restore.

Run at base 673651e8d (origin/main) plus this change:
- gofmt -l: clean
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok
- go test -tags nogui -race -count=3 ./internal/redact: ok
- go test -tags nogui -count=1 -timeout 45m ./internal/redact/...
  ./internal/gateway/...: ok (redact 3.7s, gateway 423s; internal/masking has no tests)
- Full suite NOT run: another session's `go test -timeout 45m ./...`
  was already running on this machine (one suite per machine).

Broken by hand (each run against the new tests in escape_test.go):
- old code (origin/main's redact.go, json.go and scrub.go, with a no-op
  outsideEscapes shim): all 4 tests red. TestMaskJSONKeepsArgumentsJSON
  "2 masked, want 1"; Escapes "invalid character '{' in string escape
  code" with \{{EMAIL_…}}; Restore gets \\n back; CutShort red.
- unescapedView off: KeepsArgumentsJSON, Escapes and CutShort red.
- unescapedPut off: TestRestoreArgumentsFromArguments red.
- outsideEscapes call off: CutShort red (a user rule
  `REL-[a-z\\]+` ending on the backslash of \" breaks the JSON).
- trimming replaced by dropping: CutShort's unit check red.

Fixtures come from the reporters' bytes: xiaobaifly7's \n@mcp.tool() and
Shane-Meng's \n\n\n@pytest.mark…. They also cover an address after \n,
\t, \" or \r\n, after a Windows path, and after é/—; an npm key
after \n; a key-context password; and cut-short arguments. Each checks
that the arguments still parse, the values are gone and the decorators
are unchanged.

Not tried / not covered:
- No real Ollama Cloud round trip, and nothing end to end on Windows.
- A user rule that reads past the string's closing quote (e.g. \S+ over
  JSON text) can still break arguments. That was true before this change
  and is not an escape case.
- Allow-list matching and a Hit's hint use the escaped text as written.
  A value remembered earlier with real newlines is not found by
  knownSpans in arguments unless a rule finds it again.
- A personal value written as a JSON number in arguments is not masked
  (masking it would break the JSON).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-23 18:01:26 +08:00
yetone ec7e50b828 redact: a decimal's digits are not masked as a number of their own (willz, Discord)
willz on Discord: a tool's JSON with "height": 5.13393848347348 went to
the vendor with part of the number as a placeholder. A run of digits
right after the point of a decimal, or right before it, was judged on
its own: 0.13800138000 went as 0.{{PHONE_…}}, 6.4111111111111111e-3 as
6.{{BANK_CARD_…}}e-3, 1.110105194912310038 as 1.{{ID_CARD_…}}, and
13800138000.5 as {{PHONE_…}}.5. The rules' bound only kept digits off
either side, not a point with a digit beyond it.

mask now drops, after noIDs, any span of a personal-data kind (kindCats:
PHONE, BANK_CARD, ID_CARD, SSN, IP, the model's ACCOUNT and PHONE, …)
that starts with a digit after "<digit>." or ends with a digit before
".<digit>" (noDecimals, inDecimal). It is one choke point for every
finder: the rules, the local model's spans and values known from
before. Not changed: secrets (a key or password masked once is masked
wherever it is, a decimal's digits too), the user's words and rules,
and the signed-thinking path, which re-masks only secrets. A phone
number or card standing alone, in text, after a colon, in a JSON
string, or at a sentence's end ("13800138000.") is masked as before.
A number list written "1.13800138000" with no space now goes as
written; a comma decimal (5,13800138000) is not treated as one.

Reporter's literal: at 86254d404 the rules alone leave
5.13393848347348 as written (the 14 fractional digits are too long for
a phone or a card); it is masked when the local model labels the
fraction (TestDecimalDigitsNotMaskedByModel, 5.{{ACCOUNT_…}} on the old
code) or once its digits are a known value, which is how it leaked
into another test's body on the old code. Which finder masked it for
willz is not known; the fix covers all three.

Tests (decimal_test.go): TestDecimalDigitsNotMasked (the reporter's
bytes and siblings: negative, exponent, ID card, whole part, text, many
digits; through Mask and MaskJSON in a tool_result),
TestDecimalDigitsNotMaskedByModel, TestKnownNumberNotInDecimal (plain
and in a signed thinking block), TestStandaloneNumbersStillMasked,
TestKnownSecretInDecimalStillMasked.

Run at 28d191fbe (on origin/main 86254d404):
- old redact.go with the new tests: all four decimal tests FAIL as above
  (TestStandaloneNumbersStillMasked too, through the known ACCOUNT).
- broken by hand: without the fraction-side check 12 failing lines;
  without the whole-part-side check, {"total": 13800138000.5} and
  "13800138000.25" fail; without the personal-kind scope,
  TestKnownSecretInDecimalStillMasked fails.
- gofmt -l internal/redact: empty. go vet ./..., GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: ok.
- go test -timeout 45m ./... (one suite on the machine, checked with
  ps): 68 packages ok, no FAIL; internal/redact, internal/gateway and
  internal/agent ok. An earlier full run during the edit also passed.
- after rebasing on fresh origin/main: go test ./internal/redact/... ok.

Not tried: the real local model (internal/pii) on willz's text, a real
gateway request, Windows or Linux runs of the package. No docs page
describes the rules' boundaries, so none changed.
2026-10-22 17:49:49 +08:00