Commit Graph
5 Commits
Author SHA1 Message Date
yetone 59d9f5c7d9 gateway, redact: compile their 275 package-level regexps on first use, not at every start
magpie is one binary, so every package's init runs on every launch,
including `magpie statusline`, which Claude Code runs on every message.
internal/gateway and internal/redact compiled 275 patterns at init:
3.7 MB + 2.3 MB and ~38k allocations per launch, most of them for
vendors and rules that launch never reaches.

New internal/lazyre: RE holds the source and compiles it through a
sync.Once on first use, with the *regexp.Regexp methods magpie calls
delegating to it (Of wraps one already compiled, for the user's own
privacy rules). A one-off Go AST rewrite turned every regexp.MustCompile
in a package-level var (outside func literals) into lazyre.New; the
struct fields, map and parameter that hold them took the new type. A
bad pattern now panics on first use instead of at start, so
TestAllCompile in gateway and redact compiles every registered one.

Measured on mote (M5 Pro), sandbox HOME with a copy of real accounts,
v0.1.3515 (273b9f5a9) vs this change:
- GODEBUG=inittrace=1: all init 13.0 MB / 106k allocs -> 7.4 MB / 70k;
  gateway 3.68 MB -> 70 KB, redact 2.31 MB -> 261 KB.
- `echo {} | magpie statusline`, /usr/bin/time -l, 3 runs each:
  instructions retired 260-265M -> 212-215M (-18%), peak footprint
  22.1-22.3 MB -> 18.6-19.2 MB.

Run: go vet ./... (mote); GOOS=linux and GOOS=windows go vet of
gateway, redact, lazyre; go test -race ./internal/lazyre (incl. a
bad-pattern test that MustAll panics); go test ./internal/redact (all);
go test ./internal/gateway -run 'TestAllCompile|OtherOff|WorkDir|
WorkPlace|RunNoise': ok. Broken by hand: TestBadPatternPanicsInMustAll
registers `(` and fails if MustAll does not panic.
Not run before the push: the whole internal/gateway package and the
full suite (a full suite of 273b9f5a9 was running on mote).
2026-11-10 12:34:14 +08:00
ggbdpq db9d6a6107 gateway: a working-directory line a turn quotes is no caller's word, and a --bare run's CWD: is read (#4940)
What changed: workPlace reads the folder in two layers, as
clientNamedWorkPlace does. The caller's own layer - its instructions and
its {role: "system"} messages - is read whole: Claude Code's
" - Primary working directory:", a --bare run's "CWD: /x", pi 1.1's
"Current working directory:", Codex's and pi's <cwd>, OpenCode's <env>.
A turn of the conversation is read only for the forms a caller states in
one - <cwd>, <env>, and Claude Code's <system-reminder>, which says a
folder it moved to; a line a user message quotes ("Primary working
directory: /x" alone on its line, WardLu's P3) no longer names the
folder for a group's rule by folder, nor goes to a plugin's provider as
its WorkDirHeader. The last said still goes, wherever it sits: an agent
that moved says so after. The forms are workdir.go's own, wrapper-scoped
as the routing face pinned them; the bridge's clientNamedWorkPlace is
untouched.

Run:
- go test ./internal/gateway -run 'TestWorkDirTurnQuote|TestWorkDirBareCWD|TestWorkDirMoveReminder|TestTellWorkPlaceTurnQuote' -count=1
  RED before (the quoted line named the folder; CWD: named none), green after.
- TestWorkDirOfEachAgent, TestWorkDirOpenCode, TestWorkDirLastSaidAndOnlyByTheAgent,
  TestRuleByFolder unchanged and green - the agents' own shapes and the
  move reminder keep working.
- gofmt, go vet -tags nogui (darwin/linux/windows), go build -tags nogui
  (darwin/linux/windows), the new tests with -race: clean.

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported: not superseded by b9a45f59e, which fixed the
bridge's clientNamedWorkPlace and named workDirIn as the sibling left.
On mote, with workdir.go and the docs at the parent: TestWorkDirTurnQuote
IsNotTheCallerWord FAIL ("a quoted line in a turn overrode the caller's
own: /Users/me/quoted"), TestWorkDirBareCWD FAIL ("a --bare run's CWD:
is not read"), TestTellWorkPlaceTurnQuote FAIL (the plugin is told
%2FUsers%2Fme%2Fquoted); green with the patch. go test -timeout 45m
./internal/gateway ok, GOOS=linux/windows/darwin go vet -tags nogui ok.
Fixed: workdir.go was not gofmt-clean (the piDir alignment); gofmt -w
applied. Not tried: a real agent's request through a group's rule by
folder.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-05 18:31:17 +08:00
yetone 41147956d2 gateway: a conversation's turn count and folder come from one parse of it, not one each (yg6888 on X: ~1 GB)
turnOf (affinity), dirOf (the trace's folder) and tellWorkPlace (a
plugin's work-place headers) each parsed the whole conversation for a
number and a folder. A parse decodes every message and tool output into
strings of its own, so a long conversation was decoded twice over on
every request for them. In the 60-min soak before (dee5c9d75, 4746
requests), parse was 26.4 GB of 106.7 GB allocated: turnOf 11.5 GB and
dirOf 11.4 GB.

factsOf parses once for the turn count, the folder, and whether the
text says it is a git repository (bodyFacts). For a body being served
(holdBody), it keeps those facts, a few words, while the body is held.
The pause-by-folder check reads the same facts.

It keeps the facts, not the parse. A first version kept the *Request
weakly. In the served benchmark the weak pointer was already collected
between turnOf and dirOf on 1 read in 6, and under real load the
collector runs more often. Keeping the parse strongly would keep a copy
of the conversation for the whole request. The facts are kept only
while their body is listed whole; the entry goes when the body is
released, so a body's memory given to another never reads as this one.
A body not held, or read in another protocol, is parsed for its own.

BenchmarkLargeRequest, ~2 MB conversation, B/op before → after:
  anthropic        53.81 → 45.84 MB
  anthropic-group  65.26 → 57.30 MB
  chat             43.27 → 36.61 MB
  responses        53.81 → 46.04 MB
6.7 to 8.0 MB less per request, about 3.5× the body.

Tests (parse_memo_test.go):
- TestReadersOfAHeldBodyParseItOnce: what the three readers say equals
  a parse of their own. Together they allocate at most 1.5× one parse,
  and readers after the first allocate almost nothing. A Chat read of
  the same bytes is its own, and a copy not held is parsed again.
- TestHeldFactsGoWithTheirBody: the entry goes when the request ends,
  a released body is not listed again, and a prefix of a held body is
  not the body.
Broken by hand:
- factsOf always parsing: red, "turnOf, dirOf and tellWorkPlace
  allocate 446064 bytes on a held body, a parse 135096", and "a held
  body's facts were not kept".
- The delete at release removed: red, "a body's facts are still listed
  after its request ended".
TestPauseByFolder, TestRuleByFolder, the WorkDir and WorkPlace tests and
the affinity and turn tests pass, with -race too.
Under -race the readers' byte bound is skipped (raceOn, as
request_zstd_pool_test does): sync.Pool drops a quarter of what is put
in it there, and workDirIn's regexps take their ~37 KB matchers from
one. Five tries read 1.3x to 2.1x a parse, while the parse stayed at
135304 bytes; -race -count=3 went red at 1.57x before the skip.

Run (darwin arm64, go1.26.8, sandbox HOME, load 40 to 90 from other
sessions' suites):
- go test ./... -count=1 -timeout 45m on the series' final tree at
  ba319a758: exit 0, all 68 packages ok (gateway 1498s, agent 1633s).
- After the rebase onto b855cfee9 (two redact commits): go test
  ./internal/redact ./internal/gateway -count=1 -timeout 45m, both ok
  (gateway 917s).
- go test -race -count=3 on the Held, ReadersOfAHeldBody, RecentRing,
  RequestBody, CaptureRequest, folder, WorkPlace, WorkDir and Turn
  tests: ok, after
  TestReadersOfAHeldBodyParseItOnce's byte bound was skipped under
  -race (the third commit says why); that test and
  TestHeldFactsGoWithTheirBody then passed -count=30 with and without
  -race.
- Each commit alone: go vet ./internal/gateway and gofmt -l clean.
- Final tree: gofmt -l clean; go vet ./... for darwin, GOOS=windows and
  GOOS=linux -tags nogui, all exit 0.
Not tried: a second 60-minute soak after the series (the one before is
the "before" here; the "after" numbers are the benchmark's), the GUI
suite (nothing in it changed), Windows and Linux test runs (vet only).
2026-10-21 19:17:09 +08:00
yetone 1075991f90 gateway: a plugin's fetch is told the folder the agent works in and whether it is a git repository, never seeing magpie's own (plugins #86, Hipple)
A plugin runs in magpie's plugin host, so its process.cwd() is magpie's
folder. The ZCode plugin's Start Plan request said that folder
(C:\Users\<user>\.config\magpie) as the agent's "Primary working
directory", with "Is a git repository: no", and the model looked there.

forwardOnce now calls tellWorkPlace on every request to a plugin's
provider. It reads the request as sent to the plugin with workPlace (the
same reading rules by folder use) and sets two headers on the plugin's
fetch:
- x-magpie-work-dir (provider.WorkDirHeader): the folder, percent-encoded
  (url.PathEscape; decodeURIComponent reads it);
- x-magpie-work-git (provider.WorkGitHeader): yes/no. The agent's own word
  beside the folder (Claude Code's "Is a git repository: true/false",
  OpenCode's "Is directory a git repo: yes/no") wins. Otherwise it is a
  .git in the folder or above it, when the folder is on this computer
  (provider.GitSaid, provider.GitOnDisk in the new workplace.go).
Each is left off when unknown; a folder that isn't on this computer and
that the agent didn't call a repository has no git value, never "no".
host.js's fetch (unsaid) takes both headers off every request a plugin
sends, so a plugin that forwards the headers it was given sends them to
no vendor. Documented in docs/subsystems/provider-plugins.md.

Run: TestPluginToldWhereTheAgentWorks (new) sends the captured Claude Code
and Codex requests, and Pi-style ones from a temp repo subfolder and a
plain folder, through the fake plugin to fake-claude and fake-1. It checks
what the plugin read and that the vendor got neither header. Broken by
hand: without the tellWorkPlace call every case fails; without unsaid in
host.js it fails with "the vendor got X-Magpie-Work-Dir". go test
internal/gateway (-timeout 40m), internal/provider, internal/plugin;
gofmt -l; go vet on darwin, GOOS=linux and GOOS=windows for the three
packages.
2026-10-11 21:51:34 +08:00
yetone ae70d8eac8 routing: a group's rule can hold by the folder the agent works in (Cario0x on X)
Cario0x on X asked to route by the project being worked on. A group's rule now has a
"folders" condition: it matches when the request's working folder is one of the listed
folders or inside one. It combines (AND) with the existing conditions: tokens, images,
intent, time, agents and quota.

- gateway/workdir.go reads the folder each agent states in its own request:
  - Claude Code: "Primary working directory", including "(was …)" after a move.
  - Codex: <environment_context><cwd>.
  - Pi: <cwd>.
  - OpenCode: <env> "Working directory".
  The last one stated wins. Assistant text and tool results are ignored. A request
  that states no folder matches no folder rule: unknown, never empty.
- provider/rulefolder.go matches a folder only at a path boundary.
  - ~ is the home folder.
  - C:\x is the same folder as /mnt/c/x, and \\wsl$\Distro\x as /x.
  - Case is ignored on macOS and Windows, and always for a drive.
  - A rule's folder must be a whole path. Pause rules can't have folders.
- The trace's RuleHit.Folder makes the Routing page say "The agent works in …".
- GUI: an "in folder" condition in the group editor, hidden on pause rules. Strings in
  zh, zh-TW, ja and de.
- CLI: `magpie group rule add … folders=~/oss,"~/My Project"`. The TUI shows the
  condition.
- Docs: docs/subsystems/gateway-routing.md and site start.html (en, zh, ja).

Fixtures are real requests from Claude Code 2.1.296, Codex 0.162.0 and Pi 1.1.0, run in
a sandbox from a folder named "a&b <c> 中文" or "My Proj", with the sandbox path
replaced.

Run at this head:
- go test ./... green.
- gofmt -l clean.
- go vet green for darwin, GOOS=linux -tags nogui and GOOS=windows.
- GUI routing-folder.test.cjs: chromium and webkit, en, zh, zh-TW, ja and de, 1100px
  and 390px (no horizontal scroll). It fails on the old routing.js.
- Related routing, group and i18n GUI tests: 85/85.
- Full GUI suite: 5611/5631 under --test-concurrency=6. Rerun alone, every failure
  passes except:
  - skill-install-agents-all (chromium, 420px), which is red on origin/main too: #1554.
  - The menu-scroll track flake, which flakes on main as well: #1550.
- e2e: a sandbox HOME, a dev build and fake upstreams, with real Claude Code 2.1.296
  (`claude -p --model group/fd`).
  - From proj/acme/web, rule 1 matched and the request went to kb.
  - From proj/acme-old, no rule matched and the request went to ka. The trace and UI
    showed the folder.
2026-10-11 10:17:16 +08:00