Commit Graph
21 Commits
Author SHA1 Message Date
yetoneandSunnyRx 7b883cc617 pii: a panic in the local model fails its request instead of ending magpie (#4553)
#4553's panic took the process down because it ran on a goroutine no
recovery covered. Every goroutine on the path now hands a panic back:

- pii's worker calls classify through classifySafely, which recovers,
  logs the stack, and returns "the local masking model failed reading
  this request (...)" as that request's error. It sets no retry
  hold-back, so the next request is tried as usual. Warm in
  astrlink.go and serve.go goes through it too.
- guard.Model.Find's per-window workers and bert.go's parallel carry a
  panic back to the caller (type carried), and give(procs) is deferred
  so a panicking window doesn't keep its cores.
- masking.find's goroutine recovers into the same error.

The gateway's mask calls already run in gwmw.Safely; the pf-serve model
runs in its own process.

Tests: TestGuardPanicFailsOnlyItsRequest (the error, the next request
masks its phone, Now().Failed stays empty), TestParallelCarriesAPanic,
TestFindCarriesAWindowsPanic (real model, a cut word table makes a
window worker panic; the caller sees it and no core is held),
TestModelPanicIsTheRequestsError (masking).

Broken by hand, each red: no classifySafely, the pii test binary
crashes; no recover in masking.find, the masking binary crashes; no
carry in parallel, TestParallelCarriesAPanic fails; no carry in Find,
the guard binary crashes (slice bounds [:5736192] capacity 384); give
not deferred, "3 cores still held after the panic".

Run: as in the stack's first commit (mote: gofmt, vet x3, the pii,
masking and gateway packages at -timeout 45m; Windows: pii, masking,
gateway Embeddings).

Not tried: a panic injected on the CoreML path (macOS, its own
binding); the full ./... suite.

Co-authored-by: SunnyRx <7306148+SunnyRx@users.noreply.github.com>
2026-10-31 18:22:49 +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 e61e10535d privacy: AstrLink Guard reads several requests at once, on 4 cores between them
yyhhyyyyyy (Discord, 10-28) saw an agent's parallel requests queue behind
Guard's one turn and asked for a concurrency setting (16). The turn now has
guard.Cores() places (half GOMAXPROCS, 4 at most). The cores are shared: a
process-wide pool of Cores() tokens, each window takes one before it reads
and more only while they are free (guard.take), so requests together never
use more cores than one did (the 4-core cap of 10-28, xinvxueyuan and
shensmart). The model loads once (guardLoading), the idle unload waits for
every place (guardIdle), and a text one request is reading another waits
for instead of reading it too (backend.reading). On CoreML windows are read
one at a time; only windows under coremlMin or after a failure take CPU
tokens.

No setting: measured, the bound is cores, not the request count.
Bench (zz bench, not committed): requests/s at 1/2/4/8 concurrent.
- Linux (WSL magpie-desktop, Ryzen AI Max+ 395, Cores()=4):
  512 B  shared 4.2/6.1/8.1/8.4 on 1.9-3.9 cores, rss ~150 MB
         one turn (before) 4.2 whatever came
         unshared 4.4/8.8/14.1/20.4, on 12 cores at 8
  4 KB   shared 0.6/0.5/0.6/0.7 (one 4 KB already reads 3 windows on 3.6 cores)
         unshared 0.6/1.1/1.7/2.2, 20 cores and 521 MB at 8
- Windows (xiaomi-gpu, same box, busy with other runs):
  512 B  shared 7.5/9.2/11.3/12.1 on <=3.8 cores; unshared 5.1/9.6/15.9/24.1 on 13 cores
  4 KB   shared 0.7/0.8/0.8/0.8; unshared 0.9/1.2/1.8/2.4, 18 cores, 519 MB
- mote (M5 Pro, load 25-45): CoreML 4 KB 23.0/19.6/25.1/24.9, a model a
  worker 15.7/25.6/25.5/23.4, rss ~190 MB flat: the GPU is the bound.
  CPU unshared 4 KB at 8: 953 MB.

Tests: turns_test.go (TestGuardReadsRequestsAtOnce, TestGuardIdleWaitsForEveryTurn,
TestOneTextReadOnceAtOnce), guard/cores_test.go (TestTakeHoldsOnlyWhatIsFree,
TestFindsAtOnceReadAsOneAtATime: concurrent finds equal serial ones).
Broken by hand, each red: one turn ("1 turns, 4 cores"), no load lock
("4 loads"), idle taking one place ("let go while a request read it"), no
in-flight check (TestOneTextReadOnceAtOnce), take waiting for more (10s
timeout fail).

Run:
- wsl-run: go test ./internal/pii/... ok; -race -count=3 ./internal/pii ok;
  -race guard TakeHolds/FindsAtOnce ok.
- mote-run: gofmt -l internal clean; GOOS=darwin/linux/windows go vet
  ./internal/pii/... ./internal/masking/ ok; MAGPIE_GUARD_DIR=real model
  go test ./internal/pii/... ./internal/masking/ ok (CoreML).
- win-run: go test ./internal/pii/... ./internal/masking/ with the real model ok.
- mote-run full go test -timeout 45m ./... of this and the commit before
  (at c3462d5fe): red only in TestClaudeAccountsSpentFallBackToCodex
  (#2858, #2859), TestGatewayHookWaitsForStartingHost (#2871), both ok
  alone after, and AppKit window tests in internal/gui (#2645, #4125), red
  the same alone at origin/main e15b2277c on mote.
Not tried: a real agent's parallel requests through the gateway.
2026-10-29 13:45:01 +08:00
yetone 174250b277 masking: comments no longer quote Routing's "masking…" (#4053)
i18n-keys' "a plugin's words are its own" was red on main: masking.go's
and masking_test.go's comments quoted the Requests page's word "masking…",
which plugins/routing/i18n.js owns, so the test took it for a shared word.
Both comments now say it unquoted, without the ellipsis.

Run (on mote): node --test i18n-keys.test.cjs: 4/4 (3/4 before, red with
masking.go's then masking_test.go's line); gofmt -l internal/masking: none.
Comments only.
2026-10-28 22:34:52 +08:00
yetone 6a074fc132 pii: the default's local model reads what a request adds first, a backlog 4 KB a request, on 4 cores at most
shensmart and xinvxueyuan on Discord (10-28): with the local model on by
default, a long history kept the CPU high; the model off, 5-15%.

What was heavy (measured, TestLiveHistoryCost below): not re-reading.
A text read once is kept by hash (cache, on disk too), and a warm turn
costs what the rules alone do. The heavy case is a history the model
hasn't read (a resumed session, or one from before the model was on),
on the CPU path (Linux, Windows, Docker). Each request's 2 s wait was
spent reading that history oldest first on every core (threads =
GOMAXPROCS-1, windows at once = GOMAXPROCS), the newest turn last, and
the 12 KB chunk in flight was finished past the wait. A 32-core Linux
box spent 33-60 CPU seconds a request, 13 cores busy for as long as
requests came, and the backlog was still unread after 30 requests.
Nothing ran on after the last request (1 ms CPU in the 20 s after).

Now:
- guard.Cores: AstrLink Guard reads on half of GOMAXPROCS, 4 at most.
- backend.missing reads a request's unread texts newest first (the last
  text, a long one's last piece, first).
- AstrLink Guard's chunk is 4 KB (backend.chunk), not 12 KB, so what a
  request leaves the model finishing past its wait is about a second.
- pii.Bounded (masking's default, not a model the user turned on):
  what a request went without reading is remembered by hash
  (backend.sent); a request after it reads what it adds first, and that
  backlog backlogCap (4 KB) at most, nothing found for the rest (the
  rules mask it, as past the 2 s wait). The answer past the wait with
  what was read is 874b86653's (pii.Partial), unchanged.
- A model the user turned on (strict) still reads everything, within
  874b86653's strictWait.
- Not done: OS priority (nice) for the model's threads; the core cap
  is the bound.

Measured, TestLiveHistoryCost (internal/masking, gated on
MAGPIE_GUARD_FILES, no network): a 2,041,658-byte Codex Responses
body (2,032,267 bytes at the rebased tree), 200 turns (repo files as tool output, doc paragraphs as answers,
Chinese names and an email every 10 turns), 30 requests 3 s apart, a
turn more each, model never having read it, then 20 s idle.

WSL2 Ubuntu 24.04 on xiaomi-gpu (32 cores, CPU path):
  before: 33-60 CPU-s a request (44.0, 38.3, 50.4, 42.8, 54.3 ...),
          session 23m16.8s CPU over 1m48s (1293% of a core),
          wall median 2.759s, max 3.07s; 20 s after: 1 ms
  after:  6.3-9.2 CPU-s a request, session 4m1.5s over 1m30s (268%),
          wall median 2.389s, max 2.438s; 20 s after: 1 ms
  warm turn after a full read: 876ms wall / 5.284s CPU before; after
          the rebase the "full read" is strict and stops at 874b86653's
          15 s, so that line is not a warm turn (2.41s / 7.9s); before
          the rebase, at a full read, 1.28s / 3.04s (4 cores, not 31)
  rules alone: 394 / 384 ms CPU
mote (M5 Pro, CoreML):
  before: requests 1-3 2.2 CPU-s each, then ~0.45; session 18.7s CPU
          over 1m30s (21%); warm 396ms / 380ms
  after:  request 1 2.12 CPU-s, then 0.44-0.62; session 17.2s CPU
          (19%); wall median 562ms; warm 476ms / 465ms

On the CPU path a turn adds about 15 KB here, more than 4 cores read
in 2 s, so each request still spends its wait (now on 4 cores, newest
text first) and the backlog isn't reached until turns get shorter;
on CoreML the backlog is gone after the first request.

Tests, each red with its part of the change undone by hand:
- TestNewestTextReadFirst (pii): red on the old code as it stands
  ("read first: a a a ..."); red again with the last piece not first.
- TestBoundedReadsTheBacklogALittleARequest: backlog cap removed, the
  second request read 75169 bytes.
- TestGuardReadsShortChunks: red with guard's chunk unset (12288).
- TestReadsOnFewCores (guard): Cores at 32 and 1 procs.
- TestDefaultModelIsBounded (masking): red with the default's ctx not
  Bounded ("on by default, the model wasn't asked Bounded").
- TestJoinSplitsAtChunkSize now expects the newest-first order.

Rebased onto 874b86653 (strictWait, pii.Partial), which made the
same partial-answer change; mine was dropped for its. Everything below
was run again at the rebased tree.

Run at this tree: gofmt -l clean; go vet darwin, GOOS=linux and
GOOS=windows -tags nogui on internal/pii/..., internal/masking,
internal/redact; go test -count=1 -timeout 45m of those on mote,
wsl-run (magpie-desktop) and win-run (xiaomi-gpu), all ok; internal/gwmw ok;
-race -count=5 of the pii/masking turn, wait, partial and bounded tests
on mote ok; internal/gateway, internal/gui -run
'Mask|Redact|Privacy|PII' ok; TestLiveHistoryCost on mote and WSL. Not run: the full ./... suite.
Not tried: a real Codex session through a live gateway.
2026-10-28 19:53:35 +08:00
yetone 874b86653d masking: the model the user turned on is waited 15s at most, and what it read is kept (xRayySummers on X)
xRayySummers on X (0.1.1877, Linux, AstrLink Guard turned on in
Settings -> Privacy): in one minute masking took 1.2s to 290s, and each
request whose wait ended was "gateway: masking failed, so nothing was
sent".

Cause: the model reads on the CPU one chunk at a time on one turn,
about 6 KB a second on 8 Linux cores. A burst of requests with text it
hadn't read (new tool results, subagents at once) queued behind each
other, and the turn goes round between chunks, so all of them finished
near the end of the burst. Turned on by the user, the wait had no
bound, and when anything ended it (the client, a deadline) masking.model
panicked: the request was held back whole, and even the finds already
cached for its history were thrown away (backend.find returned nil).
Not a reload (60-90ms) and not a lock in redact.

Now:
- pii.FindContext, when the wait ends, answers with what was known of
  the texts (its cache: earlier turns' history, chunks read meanwhile)
  and a *pii.Partial saying how many it hadn't read.
- masking.model waits at most strictWait (15s) for the user's model,
  defaultWait (2s) for the default's as before. Past it, the model's
  finds mask what it read and the rules mask the rest alone; the request
  goes. Nothing the rules mask goes as written. Logged once a minute.
- A model that fails (not on disk, didn't load, held back after a
  failure) still holds the user's requests back, as before: broken, not
  busy.
- masking.find gives a model that doesn't stop for ctx 100ms (handBack)
  to hand back what it knew, so a partial answer racing ctx.Done isn't
  dropped.
- docs/subsystems/gateway-routing.md says so, with the numbers below.

Run:
- Reproduced with the real AstrLink Guard (guard-7216b6a3) on Linux
  (wsl-run, magpie-desktop, GOMAXPROCS=8), a throwaway test not
  committed: load 63-87ms, reload on a request 57ms, a 125 KB history
  20.8s first read and 66us cached; six requests at once with 67-145 KB
  of new text each took 62, 91, 92, 108, 108 and 110s on the old code.
  With this change each went at 15.0s with the history's 14 finds and
  the model's finds for 1 to 4 of its 9 texts.
- mote-run at df9376592 plus this change: gofmt -l clean; go vet of
  internal/pii, masking, gateway for darwin, GOOS=linux and
  GOOS=windows ok; go test -timeout 45m ./internal/pii/...
  ./internal/masking/... ./internal/redact/... ./internal/gwmw/...
  ./internal/gateway/ all ok (gateway 459s).
- wsl-run and win-run: go test ./internal/pii/... ./internal/masking/...
  ok.
- After the rebase onto origin/main (no overlap in these files): the
  same pii and masking tests again through mote-run, ok.

Broken by hand, each red:
- backend.partial back to `return nil, waitErr(ctx)`:
  TestStoppedRequestKeepsWhatWasRead fails (no Partial).
- strict mode waiting with no deadline:
  TestStrictModelStalledIsTheRulesForWhatItDidntRead fails at its bound
  ("held the request with no bound").
- strict mode panicking on a Partial as the old code did: the same test
  fails ("held back").

Not tried: the reporter's machine, and a real Claude Code burst through
the gateway with the model on; the reproduction called the model's
backend directly.
2026-10-28 19:17:41 +08:00
yetone e296211b8b masking: the default's local model is waited for 2s at most, then the rules mask alone
shensmart on Discord (10-28, magpie in Docker on Linux, web UI remote):
Codex's requests sat "masking…" on the Requests page from about ten
minutes into use. ae0327945 (v0.1.1858) turned the local model on by
default: once its download finished it was recorded (RedactModelAuto)
and warmed, and every request then waited for it. Under the default
model() passed the request's own ctx to m.Find, so the wait (for the
one-at-a-time turn, the load, and a whole uncached history read 12 KB a
chunk on the CPU) lasted as long as the client did, and the unrouted
watch doesn't count masking time. AstrLink Guard is pure Go on the CPU,
so it runs in a container, slowly; a slow model was the hold, not one
that failed (that one already fell back to the rules).

- masking.model: not turned on by the user (strict false), the model
  is waited for defaultWait (2s) from the request's masking start, and
  given up even where Find doesn't stop for ctx (a goroutine and a
  select); then it finds nothing and the rules mask alone. Turned on by
  the user, unchanged: the request waits, and is held back on failure.
- pii backend.find: a caller that stopped waiting leaves the chunks
  after the one under way, instead of a select on a free turn and an
  ended ctx taking either, so a stopped read doesn't hold the turn every
  later request's 2s needs. The chunk under way is still finished and
  kept, so the next request finds it.

Run (mote, Go 1.26.8):
- gofmt -l clean; go vet of internal/masking and internal/pii, and
  GOOS=linux and GOOS=windows vet of both.
- go test -count=1 ./internal/masking ./internal/pii ./internal/redact: ok.
- At the rebased head (on 0b99b8fbe): go build -tags nogui ./..., vet
  as above, go test -count=1 of masking, pii, pii/guard, redact: ok.
- go test -count=5 for the new and nearby tests (TestDefaultModel*,
  TestNoModelYet*, TestModel*, TestStoppedRequestLeaves*): ok.
- go test -count=30 -run TestStoppedRequestLeavesTheRestOfItsChunks
  ./internal/pii: 30 of 30 ok.

Broken by hand: both new tests were run on the old masking.go and
find.go, with only a defaultWait var added so the tests compile.
TestDefaultModelHangingIsTheRules was red 20 of 20 ("on by default, a
model that never answers held the request", at its 10s bar).
TestStoppedRequestLeavesTheRestOfItsChunks was red 19 of 30: 2 or 3
chunks were read for a request that stopped after the first.

Not tried: a real Docker container with the downloaded AstrLink Guard
and a real Codex history; the reporter's machine. The masking page's
原文/对照 buttons are disabled with no word why when the original body
isn't held (a restart, over 4 MB, out of the last 100): not changed
here, filed as #4045.
2026-10-28 17:52:53 +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 a47596ea61 privacy: AstrLink Guard is the default local model; its menu stands apart from the switch
Settings > Privacy's "Find with a local model" row put the model menu 2px
from the Off/On switch (.prefs .val's gap): two bordered boxes touching.
The row's .val now has an 8px gap.

With no model picked, pii.Choose is AstrLink Guard. Before, it was Privacy
Filter whenever the model was on or Privacy Filter was on disk. Now
Privacy Filter is chosen only while the model is on, Privacy Filter is
downloaded and AstrLink Guard isn't, so a request isn't held back. In
that case masking.picked starts AstrLink Guard's 38 MB download
(toGuard, tried again an hour after a failure). Once it is on disk,
AstrLink Guard is saved as the pick, unless the user picked a model in
between, and Privacy Filter is let go.

Existing users:
- Privacy Filter on with no pick: moved to AstrLink Guard after the
  download. Privacy Filter stays on disk and can be picked again.
- Privacy Filter explicitly picked: unchanged.
- Model off: the menu now shows AstrLink Guard.

Run at this tree, on origin/main:
- go test ./internal/pii ./internal/masking: ok. TestChoose is updated,
  with Privacy Filter on disk both off (Guard) and on (PF).
- go test ./internal/gui -run 'Budget|I18n': ok.
- privacy-model.test.cjs, chromium + webkit, every language, 1100/640:
  64/64. The new gap check fails with the CSS line removed (gap 2).
- gofmt, vet (darwin, linux nogui, windows), linux and windows builds:
  ok.

Not tried: toGuard's real download and switch-over. It needs the
network, and no test covers it.
2026-10-27 23:18:24 +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 a019f4ffc0 masking, settings, gui: the local model the user picks (#3578)
settings.RedactModelName holds the pick ("" for none, read by
pii.Choose), this computer's own like RedactModel, kept by KeepOwn and
by the GUI's settings save. /api/privacy-model returns the chosen
model's status and every model's, and takes {do: pick, model}: picked
while off it is saved for the next On; picked while on it is
downloaded, and once on disk it is saved and the other model stopped.
Remove deletes both. masking runs the picked model.

TestPrivacyModelPick and TestMaskingUsesThePickedModel fail on the old
code (no pick; Privacy Filter always).

Run: go test ./internal/settings ./internal/gui ./internal/masking
./internal/gateway -run 'Mask|Redact|Privacy|PII|Unmasked'
./internal/gwmw at the pushed head.
2026-10-27 02:01:16 +08:00
yetone e5dd86965b pii: the masking model's requests take turns without holding the status, Stop or a restart (#3682)
After a restart, with Settings → Privacy's local model on, every request
queued for minutes on srv.mu in classify. That lock was held across
start() (up to 3m loading) and the model's answer (30s and more), and
Now(), Stop() and the idle timer took it too. The user saw a 504
"held this request for 2m0s without routing it to any provider".

Now:
- pf-serve's requests take turns through a one-slot channel (`turn`),
  so writes on its one pipe never interleave. srv.mu only guards state.
  Now() never waits: it reports Loading and how many are Waiting. Stop()
  never waits either: it kills a pf-serve that is loading or answering,
  and the request on it fails with errStopped (no retry). Fetch's
  upgrade stops pf-serve only once its turn is free (stopWhenFree).
- A request waits for its turn under its own context (FindContext). The
  gateway passes the request's context through a new gwmw.ContextTeller,
  so a client that went away, or a request the gateway answered 504,
  leaves the queue. A turn already begun still finishes and caches.
- What Find learned is kept on disk (found-<model sha>.bin, beside the
  model): a text's sha256 and its spans' offsets and labels, never the
  text. Written via temp-and-rename. A bad, cut-short or over-long file
  is read as empty, and a cached span that doesn't fit its text is
  asked again. A restart no longer asks about every history again.
- A request waiting for its turn reads the cache again when it gets it,
  so requests queued with the same history ask the model once.
- The guarantee stays: a request the model can't mask is held back, never
  sent masked by the rules alone. A wait that ends panics inside
  gwmw.Safely, as a failed model did, and the request fails closed.
- The 504 for a request held while masking says it waited for the local
  masking model, what the model was doing (loading, or masking another
  request with N waiting), that what it read is kept, and that the model
  can be turned off in Settings → Privacy (unroutedMsg).

Tests (each red on the fix broken by hand, in the sandbox HOME):
- TestStatusAndStopDontWaitForARequest / ...ForALoad: red with Now()
  taking the turn (Now waited), and the suite hung with Stop() taking it.
- TestWaiterLeavesWhenItsContextEnds: red with the waiter ignoring ctx.
- TestQueuedRequestReadsWhatTheOneAheadLearned: red without the re-read.
- TestRestartReadsWhatWasFound: red with loadCache a no-op. It also
  checks the file never holds the text.
- TestBadCacheFileIsReadAsEmpty: red with a cut-short file's entries kept.
- TestCachedSpanOutsideItsTextIsAskedAgain: red without the fits check.
- gateway TestHeldForTheMaskingModelSaysSo: red with the masker handed
  context.Background() (the wait never let go), without noteMasking, and
  with the old message. TestUnroutedMsgNamesTheModelOnlyWhenItIsOn: red
  with the old message.
- TestMaskingOnAndOff's panicky fixture embeds masking.Masker, which now
  has the Context methods. It panics on those too, and still refuses.

Run at this head (base origin/main 098ac9696, fetched before the commit),
in a sandbox HOME, load ~25:
- go test -timeout 45m -count=1 on internal/pii, internal/redact,
  internal/gwmw, internal/gateway, internal/gui and plugins/redact/...:
  all ok, apart from TestMaskingOnAndOff (the fixture above). After its
  fix, internal/gateway and internal/pii were run again whole: ok.
  internal/masking has no tests.
- go test -race -count=1 ./internal/pii/: ok.
- gofmt -l clean; go vet ./... (darwin); GOOS=linux and GOOS=windows
  go vet -tags nogui on the changed packages and internal/gui, and
  go build -tags nogui ./...: ok.

Not tried:
- A real pf-serve and model: everything above ran against the test's
  stand-in pf-serve. A real cold restart with the model on was not timed,
  and neither was Windows CPU.
- pf-serve is not warmed when magpie starts, so the first request after
  an update to the model still waits for its load. That wait now says so
  and can be left.
- The GUI does not show Loading/Waiting yet; GET /api/privacy-model carries
  them (status.loading, status.waiting).
2026-10-26 14:15:53 +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 dd7915243b privacy: masked words can match in any case, by a switch under Masked words (ZoeCats)
Settings › Privacy's masked words (脱敏词) were matched as written:
Nightjar masked "Nightjar" and let NIGHTJAR and nightjar go to the
vendor. A new row under them, "Masked words in any case", makes each word
match in any capitals (Unicode simple folding, so МОСКВА matches Москва
too), with no rule to write. It is off by default and for every existing
user: settings.json without redactWordsAnyCase reads false, and a page
from before it that saves without the field keeps what was set
(api.go, as noAutoDownload). Each match goes as {{TERM_…}} and comes
back as it was written in the request. Translated in zh, zh-TW, ja, de.

redact.Options.WordsAnyCase; settings.RedactWordsAnyCase
(redactWordsAnyCase) reaches it through internal/masking; prefsKeep
sends it on every Settings save.

Tests, each red when its part is broken by hand:
- TestWordsAnyCase (internal/redact): with the any-case branch skipped,
  FAIL "any case: \"NIGHTJAR\" still in …" and NIGHTJAR left in a request.
- TestCountTokensRedacted/words_any_case (internal/gateway): with
  masking.go not passing the setting, FAIL "system, message and tool
  description must be masked: …NIGHTJAR…"; words_as_written holds that
  the default leaves NIGHTJAR alone.
- TestSettingsRedactWordsAnyCaseKept (internal/gui): with the
  not-sent guard removed, FAIL "after {…no field…}: any case false".
- redact-words-any-case.test.cjs: 20 of 20 (Chromium and WebKit, en,
  zh, zh-TW, ja, de, 1100 and 640px). With the old app.js it times out
  waiting for #redactWordsAnyCaseRow; with only prefsKeep's field
  removed, WebKit fails "a later save keeps it".

Not tried: a real vendor request with the switch on; the gateway test checks the body that goes out.

Rebased over b00c82acf (#1977's Warn/Block and Never mask list):
masking.go and settings.go keep its Actions and Allow beside
WordsAnyCase; redact, settings and provider ran ok after it.

Run for this batch of seven commits (devin, routing zh, qoder, masked words
any case, Long conversations, Claude subagents, user-select), in a worktree,
sandbox HOME, never against live configs:
- At e352cc823 (tree ea497c9f5, on origin/main 7dd965ed2): go test
  -timeout 45m ./... with pipefail, tee'd: 68 packages ok, exit 0, no
  ENOSPC. gofmt -l clean; go vet ./... for darwin, GOOS=linux -tags nogui
  and GOOS=windows: clean.
- The whole GUI suite at e352cc823 (node --test --test-concurrency=3
  internal/gui/tests/*.test.cjs, Chromium and WebKit, every language):
  11725 tests, 11679 pass, 46 fail, none ENOSPC. Each red file run alone at
  both 7dd965ed2 and e352cc823 gives the same counts on both, so none is
  from this batch: usage-agents-hide 5/16 (#2276), usage-ledger 28/34
  (#3104), usage-fold, quota-count-wrap, quota-name-translated (#2399),
  usage-checkin 26/28 (#2549), plugin-github 14/18 (#3218), s3-sync 3/4
  (#2448), modal-morph (#3179), fonts (filed as #3227, 1 in 9 alone on
  main). tray-usages (#2453), plugin-card-update (#3079) and
  proto-menu-overflow (filed as #3229) were red only under the full run
  and pass alone on both.
- Rebased onto origin/main 4a87c4476 (only Zed's mover min changed), tree
  8944b5dbb: go test ./internal/provider ./internal/gui (TestCoreScriptBudget
  and the app.js budget) ./internal/redact ./internal/settings
  ./internal/agent: all five ok; gofmt -l clean.
2026-10-22 10:52:04 +08:00
yetone b00c82acfa masking: each kind is masked, sent with a warning or held back; a Never mask list and Try it (#1977)
Settings › Privacy gets two sections under What to mask:

- When a value is found: Mask, Warn or Block per kind (redactActions;
  a kind left out is masked). Warn sends the value as written and records
  it with a placeholder nobody remembers, not counted as masked. Block
  masks it as before and the gateway answers 400 naming the kind and the
  value's hint, never the value, with nothing sent (maskBlocked); the
  record is kept as Blocked. The secret kinds come first, the personal
  ones behind Show all kinds. A Never mask list (redactAllow) lets a whole
  value go as written in any case; a longer value it is part of is masked.
- Try it: POST /api/masking/preview masks a text as a request would
  (redact.Preview) and remembers nothing: no placeholder stands for it
  afterwards and its values aren't masked later as seen before. The page
  shows the vendor's text, what was found and what would be done, and
  keeps the text in no storage.

The masking card counts requests held back and values sent as written; a
call whose values only went as written gets an amber badge on Recent calls
and the Routing log. zh, zh-TW, ja and de throughout. Docs: gateway-routing
and gui-shell.

Broken by hand: the new GUI badge assertion fails on the old maskedBadge
(no .warn badge drawn); TestSettingsSaveKeepsWhatItDoesNotSend went red
until the two settings were in its fixture; "{n} held back" turned
i18n-keys red against the routing plugin's "{n} held" and was renamed.

Run at this tree (base origin/main 9b0f48612):
- gofmt clean; go vet on macOS, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 -timeout 45m redact, maskrec, settings, gwmw, gui,
  gateway: ok.
- GUI, both engines: every Privacy file, mask-actions, masking-records,
  routing-bodies, i18n-keys, old-webkit: 263/263.
- Whole GUI suite earlier at 083b1c8e7's base, beside 7 other runs:
  53 red; alone, the ones left red fail the same on origin/main
  6fc532198 and are filed (#3179, #2228, #2448, #2276, #2549, #2163,
  #2399), except privacy-usage-stats and account-discovery, which this
  change's taller page moved off screen; both fixed here.

Not tried: a real vendor request held back by Block from a real agent.
2026-10-22 04:07:55 +08:00
yetone 9329c89c95 settings: an unchanged settings.json is parsed once, and a gateway request reads the shared settings
settings.parse ran json.Unmarshal on every Load, and one gateway request
called Load six or seven times (Provider.Efforts, ImageOverride,
masking.options, withWires, redactionWanted, recordConversation,
namesMember). parse now keeps the last parsed value keyed by the file's
bytes, and hands Load a deep clone (internal/settings/clone.go), so every
caller still owns what it gets. settings.Shared() returns one read-only
value for the request path, its slices held at len==cap so an append
reallocates instead of reaching the shared array; the seven callers above
moved to it after checking none writes what it reads. A file that doesn't
parse is not memoized: it falls back as before (lastgood), and Shared
then returns that result, never the last good parse, so a failed read
can't keep a looser list. LoadChecked callers (allow list, image fetch
guard, disabled) stay on Load.

Measured with a 200-request probe through the gateway (5 providers, a
~9.9KB settings.json), before (origin/main 2201b6628) -> after:
  chat       7.1 parses/request, 570-571 KB/request -> 0.0, 216-242 KB
  messages   6.1-6.2 parses,      537-556 KB         -> 0.0, 255-261 KB
  responses  6.2-6.3 parses,      569-574 KB         -> 0.0, 268-277 KB

Tests: TestRequestsParseUnchangedSettingsOnce (gateway, 30 requests must
parse fewer than 30 times), TestUnchangedSettingsParsedOnce,
TestLoadIsTheCallersOwn, TestSharedAppendReallocates,
TestUnreadableSettingsNotTheLastParsed, TestCloneSharesNothing. Broken by
hand, each went red:
  - old code: "settings.json parsed 226 times for 30 requests with the
    file unchanged"
  - memo hit off: "an unchanged settings.json was parsed 200 more times
    in 300 reads"
  - shallow clone: TestLoadIsTheCallersOwn, TestSharedAppendReallocates,
    TestCloneSharesNothing ("Settings.RedactKinds is shared", ...)
  - Shared keeping the last parse on a bad file: "Shared kept the last
    file's list: [10.0.0.1]"
  - no len==cap clone: "appends reached the shared list"

Run at this commit's tree (go1.26.8 darwin/arm64, sandbox HOME):
  gofmt -l .: nothing
  GOOS=linux go vet -tags nogui ./...: ok
  GOOS=windows go vet -tags nogui ./...: ok
  go test -tags nogui -race -timeout 45m ./internal/settings
    ./internal/masking ./internal/provider ./internal/gateway: ok
    (settings 388s, provider 836s, gateway 2081s)
  set -o pipefail; go test -tags nogui -timeout 45m ./...: ok, every
    package (66 ok, 20 with no test files)
2026-10-21 07:32:11 +08:00
yetone f21dd99f5a privacy: every masking is recorded, and Settings › Privacy shows it
What was masked is now kept, so the user can see it. Settings › Privacy
opens on a summary card: how many values were kept from vendors over 1,
7 or 30 days, by kind, by finder (rules, your words, the local model,
known values) and by where they went, with a day strip. The page is
grouped into What to mask, How it's found (rules and the local model are
layers, not a toggle: the model adds names and addresses rules can't
see) and Sharing. A records view lists each masked request: its kinds,
finders, placeholders and, while magpie runs, the line around each
value. Gateway › Recent calls and the Routing log carry a masked-N badge
that opens the record.

Originals never go to disk. internal/maskrec writes day files under
~/.config/magpie/masking (0600, 30 days, 100MB at most) holding kinds,
finders, placeholders, a first character or key prefix and a length.
The lines around values are kept in memory for the last 400 records
only, and /api/masking/value answers only while the masker remembers a
placeholder. Nothing is written under MAGPIE_TEST_SANDBOX.

A masker says what it masked through gwmw.Teller (JSONHits, TextHits,
Value); a plugin masker that doesn't is counted only, so older redact
plugins keep working. Every route that masks notes it: chat, Responses,
Codex backend and search, embeddings, images, video, transcription,
decide and the search MCP query. Masking still fails closed: a masker
that panics on any path refuses the request (TestMaskingOnAndOff's fake
now panics on JSONHits and TextHits too, since the gateway asks a Teller
through those).

app.js grows to 1,314,432 bytes, so its budget rises to 1,335,000 and
the core's to 1,528,800 (+1.5%): Settings is the core's own page.

Run at this head (rebased on origin/main a3ebed202):
- go vet clean on macOS, GOOS=linux -tags nogui and GOOS=windows;
  go test ./internal/gateway ok (561s).
- On origin/main c922225f1 (one commit back, the packages either side
  touches): agent, gateway, gui, gwmw, maskrec, provider, redact ok.
- On origin/main 592899467: go test ./... -timeout 45m, 65 packages ok;
  agent and gateway hit the 45m timeout under load ~26 (each mid-way
  through a short test, not a hang) and pass alone with -timeout 100m
  (1133s, 890s).
- GUI, on 592899467, the 42 files this change or main's new commits reach (privacy-*,
  redact-*, masking-records, settings-*, gateway-*, routing-bodies,
  routing-request-metrics, routing-log-icons, account-discovery,
  click-scroll, i18n-keys, old-webkit), both engines, every language:
  475 tests, 475 pass. routing-bodies is green here since 2543fb2c1.

Run on the previous base, origin/main c84864ffc (the whole suites):
- go test ./... -timeout 45m: every package ok (66), exit 0. An earlier
  run found TestMaskingOnAndOff/panics (its fake, above) and
  TestCoreScriptBudget (the budget, above); both fixed.
- gofmt -l clean; go vet on macOS, GOOS=linux -tags nogui and
  GOOS=windows clean; node --check on the changed scripts.
- GUI suite, both engines, every language, --test-concurrency=6:
  11533 tests, 11483 pass, 50 fail. Each failing file rerun alone here
  and on origin/main:
  - red the same on main, filed: codex-predictions (#2624),
    usage-checkin (#2549), usage-agents-hide (#2276), usage-fold
    (#2163), s3-sync (#2448), quota-count-wrap and
    quota-name-translated (#2228), routing-request-metrics (#2571),
    routing-bodies (#2559: red at its "second request pressed" step;
    this change's badge checks before and after it pass),
    routing-rule-remove (#3096, filed now: 0 2 1 alone here, 0 0 2 on
    c84864ffc).
  - load, pass alone: group-member-weight (#2387), routing-model-rest,
    context-tune (Chromium didn't launch in 180s at load average ~45;
    0 0 0 alone on both). An earlier whole run's library-chip-fan red is
    #3072 (filed), plugin-card-update #3079, lightweight #2638,
    segs-glide #2683.
  - mine, fixed: old-webkit, three ":hover, :focus-visible" lists
    Safari before 15.4 drops; split, 6/6.
- Broken by hand, each went red: masked values kept on disk
  (TestNoValueOnDisk), a snip that runs past an escaped quote
  (TestSnipStaysInItsString), the shared-line dedup in the records view
  (masking-records, 10 of 12).
- Real app in a sandbox HOME with the local model on: the summary card,
  flow, chips and records view in light and dark; persons and
  addresses, Chinese names among them, recorded by=model; a grep of the
  masking folder and the sandbox config for the masked values found
  none.
2026-10-21 06:12:37 +08:00
yetone c0dad80da1 redact, pii: a local model finds what the masking rules can't (#1977)
WIP on pf/serve, recovered after the scratchpad holding it was wiped.
internal/pii downloads OpenAI's Privacy Filter (q8 GGUF, sha256 pinned)
and pf-serve, runs it on the GPU first, and answers redact's Model;
settings.RedactModel turns it on, per computer. Off by default.

Run: go vet and go test -race on internal/redact, pii, source,
settings (all ok). Not yet released: pf-serve's serveSHA is empty
until pf-v1 is tagged.
2026-10-18 23:12:41 +08:00
yetone 4ac4d9ba99 plugins: the gateway's middleware point; JS middleware and privacy masking are built-in plugins, masking fails closed (P3)
P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:

- Agent: a middleware on an agent's request in its own API and on its reply.
  serveAgent runs each registered one. The JS gateway middleware is the one
  there (middleware.Chain), registered by the new built-in plugin
  `middleware`. Its place, API, limits and fail-open are unchanged. InUse is
  middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
  back. The new built-in plugin `redact` serves masking.Masker (in
  internal/masking, since settings imports redact). InUse is masking.Wanted.
  It fails closed: masking asked for with no masker serving, or a masker that
  panics, is a 503 "nothing was sent" at every call site that masked before
  (serve, count_tokens, embeddings and audio, transcriptions, images, video,
  search stand-ins and their queries, the Codex backend).

With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.

Run (on origin/main 95e7c6bcc + this change, with the next commit's two
test waits):
- go test -count=1 -timeout 60m ./...: all ok (gateway 682s, agent 617s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, Chromium and WebKit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw. builtins reaches the Usage row by wheel now, since the
  page puts back a scroll that isn't the reader's.

Broken by hand, each went red:
- masking fails open with no masker (TestMaskingOnAndOff)
- a panic isn't recovered (TestSafelyTurnsAPanicIntoAnError, TestMaskingOnAndOff)
- no refresh asked (TestServedRefreshesOnce, TestMaskingOnAndOff)
- the plugins don't register (plugins/redact, plugins/middleware
  TestOnServesOffDoesNot)
- InUse misses redactWords (plugins/redact TestInUse)
- maskedQuery fails open (TestMaskedQueryFailsClosed)
- middleware runs with the plugin off (TestMiddlewareOnAndOff/off)
- no refresh on a middleware miss (TestMiddlewareOnAndOff), want ignored
  (TestAgentsWantedRefreshesWhenWanted)

Real use, sandbox HOME, magpie serve and a fake vendor that echoes:
- redact off with nothing asked: sent as written
- redactWords written, request at once: the vendor got {{TERM_…}} and the
  agent got the word back; `plugin builtin off redact` refused while in use
- `magpie plugin add ./alias.middleware.js`: the next request is rewritten
  (200, was 404). Removed: 404 again.
  The first build left that request at 404 until a restart, since plugins.json
  wasn't watched. That's fixed here.

Not tried: a real vendor account; the Windows box.
2026-10-15 13:40:20 +08:00