Skip to content

Feat: agentop export writes the archive's record export to a file - #1831

Merged
mrsabath merged 9 commits into
session-export-walkfrom
session-export
Nov 16, 2026
Merged

mrsabath merged 9 commits into
session-export-walkfrom
session-export

Conversation

@mrsabath

Copy link
Copy Markdown
Member

Summary

Third piece of #1810: the endpoint from the previous PR, as a command. agentop export
streams GET /v1/export to stdout or --out, with --session and --since as the
endpoint's parameters and a summary line on stderr (2400 records, 766.7kB → cli-export.ndjson)
— stdout may be the export itself, so nothing human goes there.

  • apiclient.Export is a thin query builder over getBody, which already maps the
    endpoint's whole error contract.
  • runExport copies runCost's shape: own FlagSet, usage heredoc, exit codes returned
    not os.Exit'd, endpoint defaulting to the local install.
  • --out refuses an existing file without --force (the cortex-session-dump
    precedent); --session is repeatable and comma-splittable.

Validation lives where the archive is

The plan called for a client-side pre-check of --session ids via ListSessionsArchived.
Studying getBody showed it redundant and subtly wrong: the server already refuses an
unknown session before its first byte, and getBody surfaces that 400 with the
server's own words (the archived ids). A client-side check against the archived list
would also accept resident sessions the archive has not flushed yet — ids the endpoint
would rightly refuse. So the command opens its output file only after the proxy
answered: a typo costs nothing, and the ids named are the archive's own answer.

The budget this command owns

exportTimeout (ten minutes) rather than getBody's 60s deadline-less default: the walk
reads every segment single-threaded (~10s for a 30-day archive), and HeaderTimeout
remains the liveness backstop for a proxy that never starts answering. Same shape as
costFetchTimeout.

Testing

ok  cmd/agentop           (runExport: stdout pipe, --out refusal and --force,
                            query flags reach the wire, 400 and 404 paths)
ok  cmd/agentop/apiclient (unchanged; Export is exercised through the command tests)

End-to-end against a served archive: agentop export --out wrote 2,400 records matching
curl's line count, --session e2e-session-3 to stdout wrote its 300, and an unknown id
exited 1 with the proxy's own words naming every archived session.

Stacked on #1830; merge that first.

Refs #1810

Assisted-By: Claude (Anthropic AI) [email protected]

The endpoint from the previous commit, as a command: agentop export
streams GET /v1/export to stdout or --out, with --session and --since as
the endpoint's parameters and a summary line on stderr — stdout may be
the export itself, so nothing human goes there.

apiclient.Export is a thin query builder over getBody, which already maps
the endpoint's whole error contract: an unknown session or a bad since is
a 400 the server answers before its first byte, carrying its own words
(the archived ids, the accepted forms), and a proxy without an archive is
a 404. That made the planned client-side pre-check via ListSessionsArchived
redundant and subtly wrong — the archived list also names resident
sessions the archive has not flushed yet, which the endpoint would rightly
refuse — so validation stays where the archive is, and the command opens
its output file only after the proxy answered: a typo costs nothing.

The command owns its own budget (exportTimeout, ten minutes) rather than
inheriting getBody's 60s deadline-less default: the walk reads every
segment single-threaded (~10s for a 30-day archive), and HeaderTimeout
remains the liveness backstop for a proxy that never starts answering.

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
@mrsabath
mrsabath requested a review from a team as a code owner November 12, 2026 16:17
@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ec8e2f58-b97d-4c12-803e-a5f4ebff9362

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cześć @mrsabath! Ładnie to wygląda — runCost's shape copied so faithfully I almost checked for a plagiarism notice, opening the file only after the proxy answers is a genuinely nice touch, and the O_EXCL / --force dance is exactly right. Niestety, the headline claim of the PR — "an unknown id exited 1 with the proxy's own words naming every archived session" — only holds while the archive has fewer sessions than fit in 512 bytes. Your e2e had 8 sessions; real laptops have a lot more. Details inline, one must-fix, the rest is small stuff.

Must-fix (1)

  • The "proxy's own words" path goes silent past ~11 archived sessions. getBody reads at most 512 bytes of a 400 body; the server's UnknownSessionsError lists every archived id. Once the JSON no longer fits, json.Unmarshal fails, badRequestDetail returns "", and the user gets a bare apiclient: bad request with no names and (because the ErrBadRequest branch deliberately adds nothing) no hint either. Probed against the real sessionapi handler + archive through runExport:

    archived sessions (UUID ids) stderr
    3 ...bad request: sessionexport: no archived session nope (archived: 00000000-..., ...)
    10 full list, ~470 bytes
    12 agentop export: /v1/export?session=nope: apiclient: bad request
    50 agentop export: /v1/export?session=nope: apiclient: bad request

    So the PR's own justification for dropping the client-side pre-check ("getBody surfaces that 400 with the server's own words") doesn't work in the normal case of a real archive, and the help text + docs/session-export.md promise output the user won't see. Not a regression, but it's the stated fix not working in its target case, so blocking. Suggested fixes inline.

Suggestions (4)

  • --session "" / --session "$(ids)" with an empty expansion silently widens to the whole archive.
  • Stray positional args (agentop export out.ndjson) are ignored and the export goes to stdout; every sibling command rejects fs.NArg() > 0.
  • The 404 hint asserts "no session archive" but a pre-#1830 proxy also 404s /v1/export (unregistered route).
  • A walk that fails mid-stream ends the body cleanly, so the command reports success with a short count.

Checks

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop, apiclient), Docs; cross-checked against #1830's core/sessionapi/export.go and core/sessionexport/walk.go
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, signed-off: yes
CI status: DCO + title pass; no Go CI ran (stacked on session-export-walk, not main). Locally: go build, go vet, gofmt clean; go test ./cmd/agentop/apiclient ./core/sessionapi ./core/sessionexport ok; all TestRunExport_* pass. TestReportSessionInterruption/names_the_cost_when_connections_are_attached fails in my sandbox, but it fails identically on the base branch — unrelated.

No to co, poprawisz i lecimy — I'll be back to approve faster than you can say Szczebrzeszyn.

Comment thread cmd/agentop/cmd_export.go
// A reachable proxy with no archive — a cluster sidecar, or an install with
// session.archive off. Different problem from a down proxy, different fix.
fmt.Fprintln(stderr, " this proxy has no session archive — exports read the archive, which a cluster sidecar does not run")
case errors.Is(err, apiclient.ErrBadRequest):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix — this branch trusts that err already carries the archived ids, but getBody caps the 400 body at 512 bytes and the server's UnknownSessionsError lists every archived id. With UUID ids that's ~11 sessions before the JSON is cut, badRequestDetail can't parse it, and the user sees only:

agentop export: /v1/export?session=nope: apiclient: bad request

(Probed with the real sessionapi handler + archive from #1830: n=10 prints the list, n=12 and n=50 print the line above.) So the typo costs nothing — but it also tells you nothing, and this branch then adds nothing on top. Pół biedy przy 8 sesjach w e2e; a month of Claude Code sessions is a lot more than 11.

Options, in my order of preference:

  1. Bound it server-side in Feat: Walk the archive into content-free records over GET /v1/export #1830: UnknownSessionsError.Error() names the requested ids plus the first N known (most recent first, which Summaries() already gives you) and … and K more, sized to stay well under 512. The server owns the words, and every client gets a parseable answer.
  2. Or: on ErrBadRequest with len(sessions) > 0 and no detail, fall back to ListSessionsArchived here and print a capped list — the pre-check you dropped, but as a fallback after the server already refused, so the resident-vs-flushed objection doesn't apply.
  3. At minimum, a hint in this branch when the detail is missing (agentop observe / curl .../v1/sessions?archived=...) and soften the help/doc wording.

Whichever you pick, please add a test that drives a >512-byte refusal through the real handler, not the canned 3-id body in exportServer (which is short enough to always fit).

Comment thread cmd/agentop/apiclient/client.go Outdated
// A STREAM, NOT A DOCUMENT: the body is the whole export — a month of traffic, ~12MB — and
// the caller reads and closes it. getBody's status mapping is the whole error contract
// here: an unknown session or a malformed since is a 400 the server answers BEFORE its
// first byte, carrying its own words (the archived session ids, the accepted since forms),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix (same root cause as the cmd_export.go:117 comment) — "carrying its own words (the archived session ids…)" is true only while the server's message fits in getBody's 512-byte read; past that badRequestDetail returns "" and the detail is gone. Whatever fix you choose, this comment (and the --help paragraph at L70 and docs/session-export.md "with the proxy's own words naming the sessions it does hold") should match what actually happens.

Comment thread cmd/agentop/cmd_export.go

func (s *sessionIDs) Set(v string) error {
for _, id := range strings.Split(v, ",") {
if id = strings.TrimSpace(id); id != "" {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — an all-empty --session (e.g. --session "$(ids)" where ids printed nothing — the exact scripting case the doc comment above advertises) leaves s.ids empty, and Export then omits the parameter, so the command silently exports the whole archive. Probed: --session "" → exit 0, query "", 3 records. For a filter flag, "empty means everything" is the dangerous direction. Suggest returning an error from Set when the value yields no ids (--session needs at least one id).

nit on the doc comment: "ids are UUIDs and the literal default — neither contains a comma" isn't guaranteed — header-derived ids pass validHeaderSessionID, which only refuses control runes and >MaxSessionIDLen, so a custom id_headers client can send a,b. Edge-casey, but the comment states it as a fact; maybe "in practice" plus a note that such an id can still be exported with the raw endpoint.

Comment thread cmd/agentop/cmd_export.go
`)
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — no fs.NArg() > 0 check, so agentop export out.ndjson (very natural thing to type) ignores the filename and dumps 12MB of NDJSON into the terminal, exit 0 (probed). doctor, setup, update, pipeline, experimental… all reject stray positionals with exit 2; worth matching here — or accept a single positional as --out, but rejecting is simpler.

Comment thread cmd/agentop/cmd_export.go Outdated
case errors.Is(err, apiclient.ErrNotFound):
// A reachable proxy with no archive — a cluster sidecar, or an install with
// session.archive off. Different problem from a down proxy, different fix.
fmt.Fprintln(stderr, " this proxy has no session archive — exports read the archive, which a cluster sidecar does not run")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — this hint asserts the proxy has no session archive, but a 404 here is also exactly what a proxy older than #1830 answers (/v1/export simply isn't routed — the mux's own NotFound). Mixed-version is real during an agentop update window. Cheap fix: "this proxy has no session archive, or predates /v1/export (agentop update)". Bonus: the handler's 404 body is {"error":"session archive not enabled"}, so you could tell the two apart if getBody surfaced it — not required.

Comment thread cmd/agentop/cmd_export.go
// one thing this command says on success, and it must agree with what was written
// even when the output is a pipe nobody could seek back on.
counted := &lineCounter{w: dest}
if _, err := io.Copy(counted, body); err != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — this error branch only fires on a transport-level break. When the server's walk fails past its first record, handleExport logs at Debug and returns normally, so the chunked body ends cleanly, io.Copy returns nil, and the user gets N records, … → file with exit 0 — a truncated export indistinguishable from a complete one. The design choice is documented in #1830, fair enough, but from the CLI's side "summary line on success" now means "probably complete". An HTTP trailer (X-Export-Records / X-Export-Error, set after the walk) would let this command exit 1 on a short walk without changing the NDJSON. Fine as a follow-up issue if you'd rather not widen #1830.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken, via the abort rather than the trailer — and the trailer is worth keeping on the table.

Your read of this branch was right: it only fired on a transport-level break, and a walk that died past its first record returned normally, so the body ended cleanly and the command printed N records, … → file with exit 0. @huang195 reported the same thing on this line and escalated it to must-fix, so rather than leave it as a follow-up I widened #1830: handleExport now panics with http.ErrAbortHandler after its Warn (9c2d752), and this branch fires as written. CLI-side test in 27198c2.

Why the abort and not the trailer. The abort is already this repo's answer to exactly this bug class — the forward proxy does it in three places for #1543, and classifyBrokenStream's doc makes your argument almost verbatim ("a normal return … hands the client a COMPLETE response off a stream the upstream cut off"). Reusing it meant no new wire surface, and it made the handler's old comment honest; "the best a stream can do" was just untrue given the proxy does better one package over.

But the trailer would buy something the abort doesn't, and I don't want to pretend otherwise:

  • a client could distinguish complete from truncated without a connection reset, which is friendlier to anything that treats a reset as a transport fault worth retrying;
  • X-Export-Records would give a consumer an expected count to check its own line count against, which the abort cannot express;
  • and it degrades better through intermediaries that may mask or synthesise a clean close.

The abort's cost is that "truncated" and "the network broke" look alike to the client. For agentop export that's fine — both are "don't trust this file" — but for a long-running consumer it's a real distinction.

So: shall I file that as a follow-up issue? I'd rather it be a tracked decision than a thing we silently didn't do. Happy to write it up with the above as the motivation if you agree it's worth having.

One thing the abort did settle in the meantime: that branch had zero test coverage before this, which is how it survived two rounds. It now has a part-way-failure test through the real handler and archive, plus a clean-walk control so an abort can't start firing on healthy exports.

A merge rather than a rebase: the push path moves branches
fast-forward only, so the stack keeps its original CLI commit and
takes the walker fixes from session-export-walk as a merge. The
tree is exactly the rebased stack's tree.

Signed-off-by: Mariusz Sabath <[email protected]>
The #1831 review's must-fix — the 400 path going silent past ~11 archived
sessions because getBody reads 512 bytes of the body while the server listed
every archived id — is fixed server-side in the commit below: the error now
names the first few ids and a count of the rest, so the answer always
arrives whole. This commit carries the client half: the help text, the
ErrBadRequest comment and apiclient's Export doc now say what actually
happens instead of promising the uncapped list.

And the two silent widenings a filter flag must not have:

- A --session that yields no ids is a usage error, not an absence. Empty
  is the dangerous direction for a filter: `--session "$(ids)"` with an
  empty expansion used to export the whole archive, exit 0.
- A stray positional is a usage error too. `agentop export out.ndjson`
  used to ignore the filename and dump the archive to stdout, exit 0;
  every sibling command already rejected positionals.

The 404 hint now names the other proxy that answers it — one predating
/v1/export, the mixed-version window during an update — rather than
asserting the archive is off.

Refs #1810
Assisted-By: Claude (Anthropic AI) <[email protected]>

Signed-off-by: Mariusz Sabath <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No i jak, @mrsabath, szybko poszło! Three of my four suggestions are in, and they're done well. An empty --session is now a usage error, with a test covering "", " " and ",". Stray positionals are refused, and the message even points at --out. The 404 hint now covers a proxy that predates /v1/export. The comma-in-id comment is honest now too.

The must-fix, though, only got half fixed, and the half that's missing is the one the commit message says is done. The cap in #1830 counts ids, not bytes. Five requested ids plus eight archived ones, each up to MaxSessionIDLen (256), don't fit in 512 bytes. So the 400 still goes silent in ordinary cases, and the new help text, comments and docs now promise "the answer always arrives whole". Sorry, kolego, it's the same must-fix as before, just at a different threshold. Details inline.

Must-fix (1)

  • The capped refusal still overflows getBody's 512-byte read. I ran the real sessionapi handler with a real archive through runExport at head (72aa684), using UUID-length ids:

    archived unknown --session ids 400 body stderr
    50 1 ~411 B names 8 ids and 42 more ✅
    50 3 ~487 B names 8 ids and 42 more ✅
    50 4 ~525 B agentop export: /v1/export?session=…: apiclient: bad request ❌
    50 9 ~574 B apiclient: bad request ❌
    20 (ids ~70 chars, e.g. custom id_headers) 1 ~667 B apiclient: bad request ❌

    Four mistyped ids, a pasted list or a "$(ids)" from a script is a perfectly normal thing to send, and it gets back no names and no hint. CodeRabbit raised the same thing on #1830 (walk.go:67, "bound by bytes, not only by ID count"). The real fix lives there, but this PR is the one claiming the answer arrives whole, so the block is here. See the inline comment for the fix and the test that would have caught it.

Still open, not blocking

  • From last round: a walk that fails past its first record still ends the body cleanly, so agentop export prints N records → file, exit 0. #1830 now at least logs it at Warn. A trailer or a follow-up issue is fine, your call.

Checks

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop export command + tests, apiclient.Export, main.go dispatch), Docs. Cross-checked against #1830's core/sessionexport/walk.go cappedList and core/sessionapi/export.go at 6b33781.
Agent/IDE config (.claude/.vscode): none
JSON decoders: none new. The PR only builds query params, and badRequestDetail is unchanged.
Commits: 3 (incl. merge of the #1830 fixes), all signed-off: yes
CI status: DCO and title pass. No Go CI ran, since the base is session-export-walk, not main. Locally at head, go build, go vet ./cmd/agentop and gofmt are clean. All 7 TestRunExport_* pass, as do ./cmd/agentop/apiclient and ./core/sessionexport. Three failures (TestServiceInstall_RefusesABrokenConfig, TestReportSessionInterruption/names_the_cost…, TestHandleExport_BrokenSegmentIs500) happen identically on the base branch in my root sandbox. They're unrelated.

One byte budget and one honest test, and the next approval is yours. Nie ma co się wstydzić, 512 bajtów to mniej niż się wydaje 😄

Comment thread cmd/agentop/cmd_export.go
// the same 404 from an unregistered route. Different problem from a down
// proxy, different fix.
fmt.Fprintln(stderr, " this proxy has no session archive, or predates /v1/export (`agentop update`); a cluster sidecar never runs one")
case errors.Is(err, apiclient.ErrBadRequest):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix: this branch still adds nothing on the assumption that err carries the server's words. The comment above says "capped server-side so the answer always arrives whole", but #1830's cappedList caps the count (5 requested + 8 known), not the bytes. Run against the real handler and archive:

archived=50, --session with 4 UUIDs  -> 400 body ~525 B -> "agentop export: /v1/export?session=…: apiclient: bad request"
archived=20, ids ~70 chars, 1 typo   -> 400 body ~667 B -> "… apiclient: bad request"

At 4 requested UUIDs the JSON gets cut at 512, badRequestDetail returns "", and the user is back to no names and no hint. Ids are only bounded by MaxSessionIDLen = 256, so even a single unknown id against a few long-named sessions gets there. Count-capping makes it rarer, ale nie znika.

The fix, both halves preferably:

  1. Feat: Walk the archive into content-free records over GET /v1/export #1830, UnknownSessionsError.Error(): render under a byte budget, not an id count. For example, add known ids while the message stays under ~400 bytes, then and K more. Do the same for the requested list, truncating an individual id past some length, since one 256-char id can blow the budget alone. Then extend TestWalk_UnknownSessionErrorIsCapped with 5 requested UUIDs, a few 256-char ids, and len(json body) < 512.
  2. Here: a fallback for when the detail still doesn't make it (an older or different proxy, a future message). On ErrBadRequest with len(sessions.ids) > 0 and no : detail after the sentinel, print a hint like list the archived sessions: curl -s <endpoint>/v1/sessions?archived=1 (or whichever agentop command shows them). Then the typo case is never a dead end.

Also add a test that drives a refusal >512 bytes before the fix through the real sessionapi handler and archive, not exportServer's canned (archived: old, s1) body (cmd_export_test.go:31). That body always fits, so this path can never go red. I asked for this last round, so this is a friendly przypominajka 😉

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both halves done, as you preferred.

Half 1, in #1830 (4fc99dc): UnknownSessionsError.Error() now renders under a byte budget rather than an id count — 400 bytes, half to the requested ids and the rest to the known ones, with any single id past 64 bytes truncated so one 256-char id can't eat the budget alone. Your two rows (4 UUIDs against 50 archived; 20 long ids with one typo) now come in at 448 and 441 bytes wrapped. There's a test through the real sessionapi handler and archive, and I confirmed it goes red at 568 bytes with the count cap restored.

Half 2, here (52d14fb): the fallback. On ErrBadRequest with len(sessions.ids) > 0 and no : no archived session in the error, the command now prints:

  the proxy did not name the sessions it holds; list them with:
    curl -s 'http://127.0.0.1:47601/v1/sessions?archived=true'

So even against an older proxy that caps by count, or a future message longer than the budget, the typo isn't a dead end. I used ?archived=true rather than =1 — that's the form docs/session-api.md and ListSessionsArchived use.

The test, through a >512-byte refusal. TestRunExport_RefusalTooLongToParseStillPointsSomewhere builds the 538-byte body a count-capping proxy answers for 5 unknown UUIDs against 8 archived ones — deliberately not exportServer's canned 72-byte (archived: old, s1), which as you say always fits. It asserts the premise (the detail really didn't survive) and then the fallback. Verified red before the change, printing exactly the bare line you quoted:

agentop export: /v1/export?session=nope-3f2504e0-...: apiclient: bad request

And the prose that outran the code is fixed in all three places you listed — the --help paragraph, Export's doc comment, and docs/session-export.md — plus #1830's own ?session= table row. None of them claim "always arrives whole" any more; they describe the byte budget and say what happens when an older proxy overruns it.

Comment thread docs/session-export.md Outdated

A refused query — an unknown `--session`, a malformed `--since` — fails before the
output file is created, with the proxy's own words: the first few sessions it does hold
and a count of the rest, the list capped server-side so the answer always reaches the

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix (same root cause as cmd_export.go:127): "the list capped server-side so the answer always reaches the client whole" isn't true yet. Four unknown UUIDs, or one against long ids, still overflow the 512-byte read. The same promise is in docs/session-export.md:78, the --help paragraph (cmd_export.go:71) and the Export doc comment (apiclient/client.go:193). Once the byte budget lands, these become true. Until then, please don't put it in writing, bo potem ktoś to przeczyta i uwierzy.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair, and the line is out. 52d14fb here, with the budget itself in #1830's 4fc99dc.

Every place that promised it:

  • docs/session-export.md:99-102 (this comment) — now says "as many of the sessions it does hold as fit the refusal's byte budget, then a count of the rest", followed by a sentence saying the command reads 512 bytes, that a count-based cap would overrun on long ids, that an older proxy still can, and that the command then prints the curl instead.
  • docs/session-export.md:78 (the ?session= row, in Feat: Walk the archive into content-free records over GET /v1/export #1830) — "bounded in bytes, not in ids, so the answer stays inside what a client reads of a 400 body however long the ids are".
  • cmd/agentop/cmd_export.go --help — "as many of the sessions it does hold as the refusal has room for, then a count of the rest".
  • cmd/agentop/apiclient/client.go Export doc — now states both cases: a current proxy's refusal fits the 512 bytes getBody reads, an older one caps by count and can overrun, in which case badRequestDetail finds nothing and the caller gets a bare ErrBadRequest.

Masz rację — lepiej nie pisać, niż obiecać coś, czego kod nie robi. The byte budget is in now, so the strong version is true for a current proxy; the docs just no longer claim it for every proxy.

#1830's UnknownSessionsError now renders under a byte budget rather than an id
count, which is the server half of this PR's "the proxy's own words" claim.

Assisted-By: Claude (Anthropic AI) <[email protected]>
The review's point, and it was right: this command's only answer to a refused
--session was the proxy's own words, and those words only arrive if they fit the
512 bytes getBody reads of a 400 body. Past that the JSON is cut mid-string,
badRequestDetail returns "", and the user gets:

  agentop export: /v1/export?session=nope: apiclient: bad request

No names, no hint, and this branch added nothing on top.

#1830 fixes the cause — the refusal is now rendered under a byte budget rather
than an id count, so a current proxy's words fit, and that commit is merged in
below. This one handles what the budget cannot reach: an older proxy, which caps
by count and still overruns on long ids. When the detail did not survive, the
command now prints the curl that lists the archived sessions, so a typo is never
a dead end.

THE PROSE THAT OUTRAN THE CODE, in all three places the review named: the --help
paragraph, Export's doc comment and docs/session-export.md said the list was
"capped server-side so the answer always arrives whole". That was a count cap and
it did not guarantee that. They now describe the byte budget, and say plainly that
an older proxy can still overrun it and what happens when it does.

TestRunExport_RefusalTooLongToParseStillPointsSomewhere drives a 538-byte refusal
— what a count-capping proxy answers for 5 unknown UUIDs against 8 archived ones
— rather than exportServer's canned 72-byte body, which always fits and so could
never go red. Verified red before this change (printing exactly the bare
"apiclient: bad request" above) and green after.

ok  cmd/agentop            (1034 tests in 8 shards; the 3 failures are
                            pre-existing sandbox-environment artifacts —
                            xcode-select, polkit/systemd, a foreign PID —
                            and fail identically on the base)
ok  cmd/agentop/apiclient

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No i proszę, @mrsabath — do trzech razy sztuka! 🎉 Both halves landed. The ids are now capped by bytes instead of by count in #1830 (4fc99dcf). The curl fallback here covers older proxies, and the >512-byte fixture test actually has teeth: it asserts its own premise before it checks the fallback. That's the detail I've been nagging about for two rounds. The prose is honest everywhere I'd flagged it: --help, the Export doc comment and docs/session-export.md no longer promise "always arrives whole". So the stated fix holds. A current proxy names the sessions, and an older one leaves you a curl to run. Nie jest to już ślepa uliczka.

I'm approving. Two small suggestions on the fallback itself are inline. Neither blocks.

Suggestions (2)

  • cmd_export.go:140: the fallback also fires when the 400 is about --since, and then it says something untrue. I probed --session s1 --since bogus: stderr shows the proxy's since must be a duration… detail and then "the proxy did not name the sessions it holds". The detail did survive, it's just not about sessions.
  • cmd_export.go:141: the hint prints the raw --endpoint, but the client trims a trailing slash and the hint doesn't. With --endpoint http://host:47601/, the export itself works, while the suggested curl hits //v1/sessions, gets a 307 from ServeMux path-cleaning, and curl -s without -L prints <a href=…>Temporary Redirect</a>. So the fallback breaks right where you need it.

Still open, not blocking (carried over)

  • A walk that fails past its first record still ends the body cleanly, so the summary line plus exit 0 means "probably complete". It's fine as a follow-up.
  • An FYI for #1830, outside this diff: errorMsgBudget measures the raw message, but the handler then json.Marshals it, which HTML-escapes <, > and & to \u003c and friends (6×). Five requested ids of 60 < each come out at 317 raw bytes but a 1230-byte body. Only id_headers ids can contain those characters, and this PR's fallback now catches exactly that case. So it's working as designed, but the comment saying the budget "keeps a current proxy inside the read" is about 99% true rather than 100%. If you care, an json.Encoder with SetEscapeHTML(false) fixes it for free.

Checks

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop export command and tests, apiclient.Export, main.go dispatch), Docs. Only this PR's own diff against session-export-walk. I cross-checked #1830's cappedList/UnknownSessionsError and handleExport at 4fc99dcf.
Agent/IDE config (.claude/.vscode): none
JSON decoders: none new. badRequestDetail is unchanged.
Commits: 5, every non-merge commit is signed off. Merge 71b9fde has no trailer, and DCO passes.
CI status: DCO and title pass. No Go CI ran (stacked base). Locally at 52d14fb, go build, go vet and gofmt are clean. All 8 TestRunExport_* pass, as do ./cmd/agentop/apiclient, ./core/sessionexport and ./core/sessionapi.

Merge #1830 first and then this one, lecimy dalej. Szczebrzeszyn wymówiony, approval dostarczony 😄

Comment thread cmd/agentop/cmd_export.go Outdated
// detail did not survive, the error above is a bare "bad request" and a typo
// would otherwise be a dead end, so point at where the ids can be read
// directly rather than leaving the user with nothing.
if len(sessions.ids) > 0 && !strings.Contains(err.Error(), ": no archived session") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: this condition is "a session was asked for and the words don't mention sessions", not "the words didn't arrive". So a --since refusal whose detail arrived fine also trips it whenever --session is set. I probed --session s1 --since bogus against a 400 {"error":"since must be a duration or Nd, e.g. 168h or 7d"}:

agentop export: /v1/export?session=s1&since=bogus: apiclient: bad request: since must be a duration or Nd, e.g. 168h or 7d
  the proxy did not name the sessions it holds; list them with:
    curl -s 'http://127.0.0.1:43637/v1/sessions?archived=true'

The second line isn't true, since the proxy named the real problem. The thing you actually want to detect is "no detail at all", and getBody's two shapes give you that directly. For example:

if len(sessions.ids) > 0 && !strings.Contains(err.Error(), apiclient.ErrBadRequest.Error()+":") {

or have getBody wrap a tiny exported sentinel/flag for the bare case. One extra row in the test (--session x --since bogus → no curl line) pins it. Drobiazg, ale skoro już mówimy prawdę na stderr, to do końca 😉

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 58f851e. You and @huang195 reported the same bug on this line, and @clawgenti made the same point again on the later round — so three times, which is fair, because the condition really was "a session was asked for and the words don't mention sessions" rather than "no detail arrived".

The fix is the typed marker rather than either string match. getBody already knows which case it's in — it either wraps the server's words or doesn't — so that fact is now carried as an exported sentinel:

if len(sessions.ids) > 0 && errors.Is(err, apiclient.ErrNoDetail) {

ErrNoDetail is wrapped alongside ErrBadRequest, never instead of it, so every existing errors.Is(err, ErrBadRequest) caller is unaffected (the assertions in client_test.go pass unchanged).

One wrinkle worth flagging, since it's a deviation from the literal suggestion. I first wrapped it the obvious way, fmt.Errorf("%s: %w: %w", path, ErrBadRequest, ErrNoDetail), and the user-facing message became:

agentop export: /v1/export?session=nope: apiclient: bad request: apiclient: no detail

That's worse than the bare refusal it replaces. So the sentinel goes on through a small noDetail wrapper that adds nothing to the text — Is reports it, Error() doesn't mention it. The message is byte-identical to before; only the chain is richer. I also preferred this over strings.HasSuffix(err.Error(), ErrBadRequest.Error()), which works but couples the command to the exact fmt.Errorf layout inside getBody.

Your probe now gives what you'd expect — the detail, and no hint:

agentop export: /v1/export?session=s1&since=bogus: apiclient: bad request: since must be a duration or Nd, e.g. 168h or 7d

Tests. TestRunExport_RefusalThatNamedTheProblemGetsNoSessionHint is the row you asked for (--session x --since bogus → no curl line); it goes red against the old condition, printing the three-line output you quoted. And TestGetBody_ErrNoDetailMarksARefusalThatExplainedNothing pins the sentinel across all three 400 shapes in apiclient: the documented shape (detail arrives), a non-JSON body, and a body longer than the 512 bytes getBody reads — that last one being the export refusal's actual failure mode. It also asserts the sentinel's words never reach the message.

TestRunExport_RefusalTooLongToParseStillPointsSomewhere keeps passing untouched: that fixture overruns the read, so there's no detail either way and the new condition fires exactly where the old one did.

On the two-places-one-string observation — that's gone too. Neither the command nor its test matches "no archived session" any more.

Comment thread cmd/agentop/cmd_export.go Outdated
// would otherwise be a dead end, so point at where the ids can be read
// directly rather than leaving the user with nothing.
if len(sessions.ids) > 0 && !strings.Contains(err.Error(), ": no archived session") {
fmt.Fprintf(stderr, " the proxy did not name the sessions it holds; list them with:\n curl -s '%s/v1/sessions?archived=true'\n", target)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: target is the raw --endpoint. apiclient.New runs it through trimSlash, so the export itself works with --endpoint http://host:47601/, but this hint doesn't trim and prints curl -s 'http://host:47601//v1/sessions?archived=true'. ServeMux cleans //v1/sessions with a redirect (I checked: 307 <a href="/v1/sessions?archived=true">Temporary Redirect</a>.), and curl -s without -L prints exactly that HTML. So the one fallback meant to rescue a dead end leads into another one 🙃

Cheap fix: build the client once and use its trimmed endpoint, which already exists:

client := apiclient.New(target)
body, err := client.Export(ctx, sessions.ids, *since)
...
fmt.Fprintf(stderr, "...curl -s '%s/v1/sessions?archived=true'\n", client.Endpoint())

(Adding -L to the curl would work too, but the trimmed endpoint is the honest fix.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 58f851e — the honest fix, as you put it, not -L.

The client is now kept rather than constructed inline, and the hint prints its trimmed endpoint:

client := apiclient.New(target)
body, err := client.Export(ctx, sessions.ids, *since)
...
fmt.Fprintf(stderr, "... curl -s '%s/v1/sessions?archived=true'\n", client.Endpoint())

New already runs the endpoint through trimSlash, and Endpoint() was already exported for the TUI, so this needed no new API — just using what the request itself uses.

Good catch on where it led. I confirmed the 307-into-raw-HTML path you described, and it's a particularly bad failure for this line specifically: it's the fallback that exists to rescue a dead end, so sending the reader into a second one defeats the whole point of the branch above it.

TestRunExport_HintTrimsTheEndpoint pins it — a --endpoint with a trailing slash must yield host/v1/sessions and no doubled slash. It goes red before the change, printing host:PORT//v1/sessions?archived=true.

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One must-fix and one suggestion. I proved both with a run against the PR head (52d14fb), through runExport and an httptest server.

  1. must-fix: when the walk fails after its first record, agentop export exits 0 and prints a normal summary. The export is short, and nothing tells the user.
  2. suggestion: --session X --since bogus prints the "list the sessions" hint, but the problem is --since.

The 8 TestRunExport_* tests pass. go vet ./... and gofmt -l are clean in cmd/agentop. This PR is based on session-export-walk, so CI ran only DCO and the title check, not the Go jobs.

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop, apiclient), docs
Agent/IDE config (.claude/.vscode): none
Commits: 5. The merge commit 71b9fde has no sign-off, but the DCO check passes.
CI status: passing (DCO and title only)

Comment thread cmd/agentop/cmd_export.go
// one thing this command says on success, and it must agree with what was written
// even when the output is a pipe nobody could seek back on.
counted := &lineCounter{w: dest}
if _, err := io.Copy(counted, body); err != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix: a truncated export exits 0.

This branch runs only when the connection breaks. It does not run when the walk fails. In #1830, handleExport logs export truncated and returns normally. net/http then sends the last chunk, so the client reads a clean EOF. io.Copy returns nil, and the command prints the success summary.

I ran runExport against a server that writes 2 lines and then returns, as handleExport does:

return-path: code=0 stderr="  2 records, 20B → (stdout)\n"

The same server with panic(http.ErrAbortHandler) in place of the return:

abort-path: code=1 stderr="agentop export: unexpected EOF\n  the walk failed part-way; (stdout) holds every complete record before it\n"

The user and any script get exit 0 and a short file. The only record of the failure is a Warn line in the proxy log. For an export that feeds analysis, a short file that looks complete is the worst result.

Suggested fix, in #1830: after the slog.Warn in handleExport, add panic(http.ErrAbortHandler). net/http then closes the connection without the last chunk, and it does not log a stack. This branch then runs as written. Also change the Export doc comment in apiclient/client.go (line 198, "simply ends the body"), so that it says the client sees an error. A test here can use the abort server above and expect exit 1.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9c2d752 (in #1830, since the change is server-side as you said).

handleExport now panics with http.ErrAbortHandler after the slog.Warn, so net/http closes the connection without the terminating chunk and the client's read breaks instead of returning a clean EOF.

The Warn stays. You suggested adding the panic after it, and that ordering matters here: the handler's own doc calls that log line "the only trace a truncated export leaves", so the Warn is the server's record and the panic is only what tells the client. Dropping it would have traded one blind spot for another.

I checked the thing that would have made this not work: there is no recover() anywhere in core/sessionapi, and the only wrapper between the mux and this handler is httpx.LoopbackOnly (an IP/Origin check, no recover) — and in tests not even that, since the fixtures build the bare mux. So the panic reaches net/http, which special-cases ErrAbortHandler and logs no stack trace. Confirmed in the test run: the Warn appears, no panic trace.

On the precedent — you're right that this is the established shape rather than a new idea. classifyBrokenStream's doc (core/listener/forwardproxy/stream.go:114-121) already spells out the argument almost word for word, and the forward proxy panics the same way in three places for #1543. The handler's old comment, "the best a stream can do", wasn't true: the proxy does better one package over.

The test. That branch had zero coverage, which is why this survived review twice. TestHandleExport_TruncatedWalkReachesClientAsError breaks the older of two segment files — Page reads newest-segment-first, so the newer one's records are written before the walk dies, which is the part-way failure rather than the before-first-record one BrokenSegmentIs500 already covers. Two things I had to get right for the fixture to be honest:

  • Segments roll on size and idle, never on an event's timestamp, so events spaced an hour apart still land in one file. Two archive.Open → append → Close cycles produce two segments (createSegment is O_EXCL and never reopens).
  • The fault has to be a self-referential symlink. os.Remove alone is skipped as fs.ErrNotExist by read.go:64-66 and tolerated; a directory opens and then reads as merely truncated, which is swallowed.

It goes red without the panic, printing exactly what you reported:

--- FAIL: TestHandleExport_TruncatedWalkReachesClientAsError
    a truncated export reached the client as a clean end of body; got 414 bytes:
    {"schema":1,"sessionId":"s1","seq":6,...}
    {"schema":1,"sessionId":"s1","seq":5,...}
    {"schema":1,"sessionId":"s1","seq":4,...}

It also asserts the bytes that did arrive still parse as whole records — truncation, not corruption — and there's a clean-walk control so an abort can't start firing on healthy exports. I needed a new helper for the assertion: getBody, getPath and exportRecords all t.Fatalf on the body-read error, so none of them can observe the very thing this is about.

CLI side, in #1831 (27198c2): TestRunExport_TruncatedWalkExitsNonZero drives your abort server and asserts exit 1 with no success summary. The Export doc comment you flagged (the "simply ends the body" sentence) is corrected, and docs/session-export.md / docs/session-api.md no longer describe the old behaviour.

Comment thread cmd/agentop/cmd_export.go Outdated
// detail did not survive, the error above is a bare "bad request" and a typo
// would otherwise be a dead end, so point at where the ids can be read
// directly rather than leaving the user with nothing.
if len(sessions.ids) > 0 && !strings.Contains(err.Error(), ": no archived session") {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: this hint is wrong for a --since refusal.

The condition is true for every 400 whose detail is not an unknown-session message. The server checks since before the walk. So --session s1 --since bogus gets a full, readable detail, and then also this hint:

agentop export: /v1/export?session=s1&since=bogus: apiclient: bad request: since must be a duration or Nd, e.g. 168h or 7d
  the proxy did not name the sessions it holds; list them with:
    curl -s 'http://127.0.0.1:58684/v1/sessions?archived=true'

The user then looks at the sessions, but the problem is --since. The hint is for the case where the detail did not survive the 512-byte read. Check for that case instead: getBody then returns the error with no text after ErrBadRequest, for example strings.HasSuffix(err.Error(), apiclient.ErrBadRequest.Error()). This also removes the match on the server's ": no archived session" text.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 58f851e — same root cause as @clawgenti's comment on this line, so one change closes both; full detail is in my reply there.

Short version: the condition is now errors.Is(err, apiclient.ErrNoDetail), a sentinel getBody wraps alongside ErrBadRequest when the detail didn't survive — so it tests "no detail arrived at all", which is what you identified as the actual question, and it drops the match on the server's ": no archived session" text as you suggested.

I went with the sentinel rather than strings.HasSuffix(err.Error(), apiclient.ErrBadRequest.Error()). Your version works and is a smaller diff; I preferred not to couple the command to the exact fmt.Errorf layout inside getBody, and the package already uses flat sentinels everywhere (ErrNoSearch, ErrSessionGone, …). It's wrapped so the user-facing message is unchanged — bad request: apiclient: no detail would have read worse than the bare refusal.

Your probe output is now just the detail, with no session hint under it. Pinned by TestRunExport_RefusalThatNamedTheProblemGetsNoSessionHint, which goes red against the old condition.

@mrsabath mrsabath added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 16, 2026

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cześć Grzegorz! 🇵🇱 Another chapter of the export saga with a PR body so thorough I half expected a table of contents — kurczę, you even documented the byte budget of a 400 response. Thank you.

What the design gets right: opening the output file only after the proxy answered is the quietly excellent part — a typo'd --session costs nothing, and the server validating before its first byte is what makes that guarantee real. The refusal-too-long-to-parse test (538-byte fixture that must exceed the 512-byte read) is exactly the kind of adversarial thinking this PR series has been built on.

I have no must-fixes. The rest are suggestions/nits — the kind of thing you'd probably have caught in the next PR anyway. Do widzenia, and tell babcia the export is safe to pipe. 🇵🇱


Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop, apiclient), docs, tests
Agent/IDE config (.claude/.vscode): none
Commits: 5, all signed off: yes (71b9fde is a merge commit, which DCO exempts)
CI status: passing (DCO, pr-title-check; CodeRabbit skipping)

Verified by: (on head 52d14fb)

  • go test ./cmd/agentop/... — all TestRunExport_* pass; one failure in TestReportSessionInterruption/names_the_cost_when_connections_are_attached reproduces on main too (pre-existing, unrelated to this PR)
  • go vet ./cmd/agentop/... — clean
  • gofmt -l cmd/agentop/ — no output
  • Read core/sessionapi/export.go:84 + core/sessionexport/ndjson.go: the endpoint writes through json.Encoder, which always appends \n per record — so the lineCounter's newline-based count is sound against the real endpoint, not just the fixtures
  • Confirmed trimZero/plainCount already exist in cmd_cost.go (reuse, not re-definition)
  • Confirmed 71b9fde is a merge commit (two parents), so its missing Signed-off-by is DCO-exempt — CI agrees

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

Comment thread cmd/agentop/cmd_export.go Outdated
// detail did not survive, the error above is a bare "bad request" and a typo
// would otherwise be a dead end, so point at where the ids can be read
// directly rather than leaving the user with nothing.
if len(sessions.ids) > 0 && !strings.Contains(err.Error(), ": no archived session") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — This fallback hint is gated on !strings.Contains(err.Error(), ": no archived session"), which couples the client to the exact wording of the server's error message. If the server-side phrasing ever drifts (e.g. #1830 renames sessionexport: or rewords the refusal), the client would print the curl hint even when the ids did survive the read — harmless (a redundant hint), but it would also silently stop matching the test's premise string.

Evidence: the test at cmd_export_test.go (TestRunExport_RefusalTooLongToParseStillPointsSomewhere) asserts on the same "no archived session" substring, so the string now lives in two places across two modules.

Suggested fix: have badRequestDetail/Export mark whether the detail parsed (e.g. a typed error or a detailOK wrapper), and branch on that instead of the message text. Not worth blocking on — it's a stderr hint, not a correctness path — but it's the one string-matching seam in an otherwise contract-driven design.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already fixed, in 58f851e — and you'd independently arrived at the same fix I'd landed, which is a good sign the string match was the wrong seam rather than just an unlucky one.

badRequestDetail's outcome is now carried as a typed marker exactly as you suggested: getBody wraps an exported ErrNoDetail alongside ErrBadRequest when the detail didn't parse, and the command branches on errors.Is(err, apiclient.ErrNoDetail). No wording match anywhere.

Your "silently stop matching the test's premise string" worry is resolved too — that string lived in two places across two modules, and now it lives in neither. The test asserts on the sentinel and on the absence of a hint, not on the server's phrasing, so a rewording in #1830 can't quietly make this path untestable.

The wrapper adds nothing to the message text, so the user-facing output is byte-identical to before; only the error chain is richer. Details in the reply on the original thread.

Comment thread cmd/agentop/cmd_export.go

// byteSize renders a byte count the way a summary line has room for: 12.5MB, not
// 12582912.
func byteSize(n int64) string {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — byteSize divides by 1000 (1e6/1e3) while labelling the result MB/kB. That's a deliberate decimal choice and it's internally consistent (the PR body quotes 766.7kB, docs quote ~12 MB for 30 days), so no change needed — just noting it so nobody 'fixes' it to 1024 later and quietly breaks the doc numbers.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bookkeeping note: the review above covers this head; this comment exists only to carry the state marker so the scanner does not re-queue it.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

Three review findings on the ErrBadRequest branch, all on the same few lines.

The hint fired on a refusal that HAD explained itself. The condition was "a
session was asked for and the words do not mention sessions", so
`--session s1 --since bogus` printed "the proxy did not name the sessions it
holds" underneath the proxy's own perfectly clear complaint about since,
sending the reader to look at sessions when since was the problem.

What the branch wants to know is whether any detail arrived at all, and getBody
already knows: it either wraps the server's words or does not. Carry that as an
exported ErrNoDetail sentinel beside ErrBadRequest and check it with errors.Is,
rather than matching on either the server's wording or getBody's own formatting.
It is wrapped in a type that adds nothing to the message, because the text is
printed to a user and "bad request: apiclient: no detail" reads worse than the
bare refusal it would replace. errors.Is(err, ErrBadRequest) is unaffected.

The hint's curl was not runnable. It printed the raw --endpoint, so
`--endpoint http://host:47601/` produced `host:47601//v1/sessions`, which
ServeMux answers with a 307 whose HTML body is all `curl -s` shows -- the one
fallback meant to rescue a dead end leading into another. Keep the client and
print Endpoint(), the trimmed form the request itself uses.

And the Export doc comment claimed a failed walk "simply ends the body, which
NDJSON tolerates". It resets the connection as of #1830, so the caller sees an
error rather than a short success; the help text now says the command exits
non-zero and what the output holds.

Tests: a refusal that named a different problem gets no hint, a trailing-slash
endpoint produces no doubled slash, a truncated export exits 1, and ErrNoDetail
is pinned across all three 400 shapes -- parseable, undocumented, and cut by the
512-byte read. The first two go red against the old conditions.

Reported by clawgenti and huang195.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
The same two places #1830 corrects, carried here so this branch's own diff does
not describe the old behaviour: a walk that dies part-way resets the connection,
so a client reads an error and `agentop export` exits non-zero, rather than
ending the body cleanly and looking complete.

Identical text to #1830's, so merging that into this branch changes nothing.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
`git add -A` picked up the heredoc file the commit message itself was written
from, before the rm. Not meant to be tracked.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
@huang195 huang195 closed this Nov 16, 2026
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 16, 2026
@huang195 huang195 reopened this Nov 16, 2026
@huang195

Copy link
Copy Markdown
Member

why does only 3 CI run on this PR?

@huang195

Copy link
Copy Markdown
Member

oh this is a stacked PR on 1830, once that merged, the CIs should run properly

mrsabath added a commit that referenced this pull request Nov 16, 2026
A walk that failed past its first record logged a Warn and returned normally.
net/http then wrote the terminating chunk, so the client read a clean EOF off a
200: io.Copy returned nil, `agentop export` printed its success summary and
exited 0, and a short file was indistinguishable from a whole one. The only
trace was a line in the proxy log.

Panic with http.ErrAbortHandler after the Warn instead. The forward proxy's
stream relay already fixed this bug class the same way in three places (#1543),
and classifyBrokenStream's note spells out why a normal return is wrong: it
hands the client a COMPLETE response off a stream that was cut off. There is no
recover() between the mux and this handler, and the standard library suppresses
the stack trace for ErrAbortHandler specifically.

The Warn stays -- it is the server's trace, and the panic only tells the client.
Every complete NDJSON line already flushed stays valid, so a consumer keeps what
arrived and reads an error at the end rather than a clean end of body.

The branch had no test. The new one breaks the OLDER of two segment files, since
Page reads newest-segment-first, so records are written before the walk dies; it
goes red without the panic, printing the 3 whole records and clean EOF this
fixes. Two open/close cycles to get two segments -- rolling is by size and idle,
never by an event's timestamp -- and a self-referential symlink for the fault,
because os.Remove is skipped as fs.ErrNotExist and a directory reads as merely
truncated. A clean-walk control pins that healthy exports are not aborted, and
readKeepingError exists because getBody and getPath both t.Fatalf on the read
error this has to assert on.

Reported by huang195 in review of #1831.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cześć @mrsabath! Czwarta runda tej sagi i, kurczę, wreszcie nie mam się do czego przyczepić na serio. Ktoś tu chyba czyta recenzje szybciej, niż my je piszemy 😄

Everything that was open on 52d14fb is now closed, and I checked each one by running it, not by reading the commit messages:

  • huang195's must-fix (a truncated export exits 0) is fixed. The fix is in two places: #1830's 9c2d7525 makes the handler panic(http.ErrAbortHandler) past the first record, and this PR's io.Copy branch turns the broken read into exit 1. I merged session-export-walk into fe91ff8 (it merges cleanly) and ran runExport against the real sessionapi handler and archive. I broke the older of two segments with an ELOOP symlink, the same trick as your server test. Result: code=1, stderr agentop export: unexpected EOF / the walk failed part-way; … holds every complete record before it, and the 3 complete records from the good segment are on stdout. That holds for stdout, --out and --session s1. A healthy export still exits 0 (6 records, 828B). The docs also say curl > file gets a non-zero exit of its own. That's true: curl -s exits 18 (partial file).
  • The --since misfire (from both of us) is fixed. ErrNoDetail is the right tool, much better than guessing from the server's wording. Against the real handler, --session nope --since bogus now prints only the proxy's since must be…, with no session hint.
  • The doubled slash in the hint is fixed. client.Endpoint() is used, and the test also checks that //v1/sessions is absent. A healthy export with --endpoint …/ works too.
  • The unknown-id refusal after the byte budget is no longer a dead end. With 50 archived UUIDs × {1 typo, 5 typos, one 200-char &&&… id}, every case names ids and then says and N more. Nic się nie urwało w połowie.

Suggestion (1), inline

  • cmd_export.go:195: the io.Copy branch blames the walk for write errors too. With --out /dev/full you get the walk failed part-way; /dev/full holds every complete record before it. Neither half is true: the walk is fine, and a failed write can leave half a line. Easy to split, details inline. Not blocking.

Nits (not inline)

  • The PR body's Testing section still says cmd/agentop/apiclient (unchanged; …), but TestGetBody_ErrNoDetailMarksARefusalThatExplainedNothing is in there now. It's the PR body, so whoever merges can update it.
  • Merge commit 71b9fde has no Signed-off-by. The DCO check passes anyway (merge commits are exempt), so I'm only mentioning it.

Lessons-learned probes

  • New JSON-decoded fields from external input: none. Export streams the body raw, and the only decode is the existing badRequestDetail. The new noDetail wrapper doesn't change any message text, and errors.Is(err, ErrBadRequest) still holds for cmd_cost.
  • Does the stated fix work in its target case: yes, against the real handler (see the first bullet), not only against the httptest stub in TestRunExport_TruncatedWalkExitsNonZero.

No i git, approving. Babcia może spokojnie pipe'ować do jq. 🍺


Author: mrsabath (MEMBER, maintainer)
Areas reviewed: Go (cmd/agentop, apiclient), docs, tests. Only this PR's diff against session-export-walk (#1830), plus #1830's 9c2d7525 where the fix depends on it
Agent/IDE config (.claude/.vscode): none
Commits: 8. All are signed off except merge 71b9fde (DCO passes)
CI status: passing (DCO and title only; the Go jobs don't run on a stacked base)

Verified by (head fe91ff8, and head merged with session-export-walk@9c2d7525):

  • go test ./cmd/agentop/...: every TestRunExport_* and the apiclient tests pass. Two failures, TestReportSessionInterruption/names_the_cost… and TestServiceInstall_RefusesABrokenConfig, are sandbox-environmental (no systemd user bus). The first one reproduces on the base too.
  • go vet ./... and gofmt -l in cmd/agentop: clean
  • Throwaway probe tests driving runExport against sessionapi.New(...WithArchive): truncated walk, healthy walk, trailing-slash endpoint, unknown ids (3 and 50 archived), --since refusals, /dev/full, and curl exit on truncation

Comment thread cmd/agentop/cmd_export.go Outdated
counted := &lineCounter{w: dest}
if _, err := io.Copy(counted, body); err != nil {
fmt.Fprintf(stderr, "agentop export: %v\n", err)
fmt.Fprintf(stderr, " the walk failed part-way; %s holds every complete record before it\n", where)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: this branch catches both sides of io.Copy, but the message only describes the read side. I probed --out /dev/full --force against a healthy real handler:

agentop export: write /dev/full: no space left on device
  the walk failed part-way; /dev/full holds every complete record before it

The walk didn't fail. And after a short write, the file may end in half a line, so "every complete record" isn't guaranteed either. A full disk on an --out to a small partition is the realistic case. (A broken stdout pipe, like | head, doesn't get here: Go dies on SIGPIPE for fd 1.)

The fix is cheap. lineCounter already sees the write error, so record it there and branch on it:

func (l *lineCounter) Write(p []byte) (int, error) {
	n, err := l.w.Write(p)
	...
	l.err = err
	return n, err
}

// at the call site
if _, err := io.Copy(counted, body); err != nil {
	fmt.Fprintf(stderr, "agentop export: %v\n", err)
	if counted.err != nil {
		fmt.Fprintf(stderr, "  writing %s failed; it may end in a partial line\n", where)
	} else {
		fmt.Fprintf(stderr, "  the walk failed part-way; %s holds every complete record before it\n", where)
	}
	return 1
}

The exit code is already right, so this is only about the words. Nie blokuje, it's just that the sentence currently points the user the wrong way, i.e. "something in Cortex broke" when the disk is actually full. 😉

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 27198c2. Implemented as you suggested — lineCounter already saw the write error and threw it away, so it now keeps it and the call site branches on it.

You were right that it's wrong twice, and the second half is the part I'd have missed on my own: not just the wrong cause, but the wrong guarantee. A short write can stop mid-line, so "holds every complete record before it" isn't true there either — only a failed walk ends the stream at a record boundary, because the server flushes one record per write. So the two messages now differ in both respects:

agentop export: no space left on device
  writing /mnt/small/e.ndjson failed; it may end in a partial line

versus the walk case, which keeps the original wording.

One deviation on the test. I started with --out /dev/full as in your probe, and it does reproduce it — but /dev/full doesn't exist on macOS, so the test skipped on my machine and would only ever have run on Linux CI. A test that's green locally because it didn't run is close to no test, so it now passes a writer that always fails as stdout instead: the destination goes through the same lineCounter either way, and it runs everywhere. It goes red against the old message with precisely the line you quoted:

stderr = "agentop export: no space left on device\n  the walk failed part-way; (stdout) holds every complete record before it\n",
  want no accusation against the walk on a write failure

Also noted on the sibling comment about byteSize dividing by 1000 while labelling kB/MB — agreed it's deliberate and internally consistent with the docs' numbers, so I've left it alone rather than "fix" it to 1024. The byteSize(999_999) → "1000kB" rounding window I've also left: it's a one-value cosmetic on a summary line, and I'd rather not touch the rounding on a PR that's already this wide. Say the word if you'd like either as a follow-up.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cześć mrsabath! 🇵🇱 Kurczę, this PR body reads like Grzegorz Brzęczyszczykiewicz wrote his doctoral thesis on it — "Validation lives where the archive is" is a section heading I did not expect to enjoy.

Credit where due first: opening the output file only after the proxy answered, so a typo'd --session costs nothing, is exactly the right call, and the ErrNoDetail sentinel (matching on the condition rather than grepping the server's wording) cleanly fixes the --since bogus mis-hint without touching any existing ErrBadRequest caller.

No must-fixes. I held the PR against its own claims and could not break any of them:

  • The refusal-too-long path (512-byte read overrun) does what the doc comments promise, including the count-capping-older-proxy case the tests build by hand.
  • The truncated-walk path exits non-zero with the part-way message, matching session-export.md's new "resets the connection" contract.
  • --session "$(ids)" with an empty expansion is refused rather than widening to a full-archive export — the one silent widening the PR says it must not do.

The rest are suggestions/nits — do with them as you will, and thanks for the genuinely readable doc comments (babcia would say you write more carefully than the parish newsletter).

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop, apiclient), docs (session-api.md, session-export.md)
Agent/IDE config (.claude/.vscode): none
Commits: 8 commits, DCO check passing (71b9fde is a merge commit — exempt from DCO, noted only for completeness)
CI status: passing (CodeQL not run on this PR; verify-pr-title and DCO green)

Verified by:

  • go test ./cmd/agentop/ -run TestRunExport -v — all 11 tests PASS
  • go test ./cmd/agentop/apiclient/ -run ErrNoDetail -v — all 3 subtests PASS
  • go vet ./cmd/agentop/... and gofmt -l cmd/agentop/ — clean; go build ./cmd/agentop/ — clean
  • Throwaway probe on byteSize boundary values (positive control: 766700 → "766.7kB", matching the PR body's example); probe deleted afterwards
  • Full ./cmd/agentop/... suite: two failures (TestServiceInstall_RefusesABrokenConfig, TestReportSessionInterruption), both reproduced on origin/main in this environment (no systemd user bus) — pre-existing, not from this PR

Comment thread cmd/agentop/cmd_export.go
// 12582912.
func byteSize(n int64) string {
switch {
case n >= 1_000_000:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — byteSize(999_999) renders "1000kB" (probed on head: byteSize(999999) = "1000kB", while byteSize(1000000) = "1MB"). The 1e6 threshold is checked before the rounding, so a value just under 1MB rounds up to a thousand of the smaller unit.

Suggested fix: round first and re-test, e.g. in the n >= 1_000 branch compute mb := float64(n)/1e6; if mb >= 1 { return trimZero(mb) + "MB" } — or simply accept it; it is a summary-line cosmetic and only reachable in a 999,999–999,999.4-byte window.

Why it matters now: only polish — the PR body's own example (766.7kB) and every common size render fine.

io.Copy reports a failed read and a failed write as the same non-nil error, and
this branch described only the read side. An --out to a small partition printed
"the walk failed part-way" over an ENOSPC: wrong cause, pointing the user at
Cortex when the disk is full. It was wrong twice, because a short write can stop
mid-line, so "holds every complete record" is not true there either -- only a
failed walk ends the stream at a record boundary.

lineCounter already saw the write error and dropped it; keep it and branch on it.

The test uses a writer that always fails rather than /dev/full, which does not
exist on macOS: the destination goes through the same lineCounter either way, so
this runs everywhere instead of silently skipping outside CI. It goes red
against the old message, printing the same line the review quoted.

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cześć @mrsabath! Piąta runda, and this time the delta is one commit, 27198c2, and 49 lines. Ty to chyba śpisz z otwartą zakładką „Files changed” 😄

What changed since fe91ff8 (my last approval)

The one open suggestion was that the io.Copy branch blamed the walk for a failed write. That's fixed, and fixed properly. I checked it by running it, not by reading the commit message:

  • --out /dev/full --force against a healthy server: write /dev/full: no space left on device / writing /dev/full failed; it may end in a partial line, exit 1. The walk isn't accused any more, and the "every complete record" promise is gone in the one case where it was false.
  • stdout redirected to /dev/full: writing (stdout) failed; …, exit 1. Same branch.
  • Server aborting mid-stream (panic(http.ErrAbortHandler)): still unexpected EOF / the walk failed part-way; …, exit 1. The read side is unchanged.
  • The new test has teeth. I ran TestRunExport_FailedWriteDoesNotBlameTheWalk against the fe91ff8 version of cmd_export.go and it fails with exactly the old line. Using an errWriter instead of /dev/full so it runs on macOS is the right call: a test that only goes green because it skipped isn't a test.
  • One edge I poked at: a writer that returns n < len(p) with a nil error makes io.Copy return ErrShortWrite with counted.err == nil, so it would blame the walk. But that writer breaks the io.Writer contract, and *os.File never does it, so there's nothing to fix.

On your trailer question to me in the :193 thread: yes, please file it as a follow-up. Being able to tell truncated from network died, plus an X-Export-Records count to check against, would be worth having for long-running consumers. You laid out the trade-off well. It just doesn't belong in this PR.

@huang195: your CHANGES_REQUESTED at 52d14fb (truncated export exits 0) is addressed by #1830's 9c2d7525 plus TestRunExport_TruncatedWalkExitsNonZero here. I verified it against the real handler last round. When you have a moment, a re-review or a dismissal would clear the block.

Nit (1), inline

  • cmd_export.go:184: on the success path, f.Close()'s error is dropped. Not blocking, details inline.

No must-fixes. Approving. Dobra, wystarczy tych rund, czas to zmergować, zanim wymyślisz szóstą 🍺


Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop/cmd_export.go and its test), focused on the fe91ff8..27198c2 delta. I also re-checked the PR's other changes at head.
Agent/IDE config (.claude/.vscode): none
JSON decoders: none new. Export streams the body raw.
Commits: 9. All are signed off except merge 71b9fde (DCO passes).
CI status: DCO and title pass. The Go jobs don't run on a stacked base.

Verified by (head 27198c2, cmd/agentop module):

  • go build ./..., go vet . ./apiclient and gofmt -l .: clean
  • go test -run TestRunExport -v .: all 12 pass. go test ./...: every package passes except two tests in cmd/agentop, TestServiceInstall_RefusesABrokenConfig and TestReportSessionInterruption/names_the_cost…, which fail because this sandbox has no systemd user bus (the same as in earlier rounds and on base).
  • Red/green: the new test fails against the fe91ff8 cmd_export.go
  • A throwaway probe test driving runExport: /dev/full as --out and as stdout, a mid-stream ErrAbortHandler, and a short-writing writer

Comment thread cmd/agentop/cmd_export.go
fmt.Fprintf(stderr, "agentop export: %v\n", ferr)
return 1
}
defer f.Close()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this commit makes the command careful about which end broke, but one write failure can still get through. defer f.Close() drops the close error, so the success path prints N records, … → file and exits 0 even if the close itself fails. On a local ext4 that basically never happens. On NFS, or under a quota, a write-behind EDQUOT/ENOSPC often shows up only at close(2). That's the "short file that looks complete" outcome this PR has been working so hard to rule out.

It's cheap to close it explicitly before the summary when --out is set:

if f != nil {
	if err := f.Close(); err != nil {
		fmt.Fprintf(stderr, "agentop export: %v\n  writing %s failed; it may end in a partial line\n", err, where)
		return 1
	}
}

(Keep the defer for the error paths. A second Close just returns ErrClosed, and nobody reads it.) Nie blokuje. It could go in this PR or into the trailer follow-up, whichever you prefer 😉

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cześć! Kurczę, the PR body reads like a babcia's pantry inventory — everything labelled, everything accounted for, and a doc comment for every drawer. This is the third piece of #1830's walk and it slots in exactly as promised.

What the design gets right: opening the output file only after the proxy answers is the quietly excellent move here — it turns a typo'd --session into a cost of zero, and it falls out naturally from the server's validate-before-first-byte contract instead of a redundant client-side pre-check (dropping the planned ListSessionsArchived round-trip was the right call; accepting not-yet-flushed resident ids would have been a subtle wrong).

Must-fixes: none. I could not break it — the tests are genuinely adversarial (a >512-byte refusal fixture built byte-by-byte, an errWriter disk, a mid-walk panic(http.ErrAbortHandler)) and every claim I probed on head held.

The rest are suggestions/nits, nothing that blocks. Do dobrej roboty, Grzegorz by niezawodny jak zwykle 🇵🇱


Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (apiclient, command), tests, docs
Agent/IDE config (.claude/.vscode): none
Commits: 9 commits, all signed-off: yes (DCO check passing)
CI status: passing (pr-title-check, DCO)

Verified by:

  • go test ./cmd/agentop/ -run 'TestRunExport|TestGetBody_ErrNoDetail' -count=1 — all 13 pass on head 27198c2
  • gofmt -l cmd/agentop/ clean; go vet ./cmd/agentop/... clean
  • Full go test ./cmd/agentop/ has 2 failures (TestServiceInstall_RefusesABrokenConfig, TestReportSessionInterruption) — both also fail on the base branch session-export-walk in this sandbox (no systemd user bus), so pre-existing and not from this PR
  • Mutation probe with a positive control: inverted the counted.err != nil write-vs-walk blame condition in runExport → TestRunExport_FailedWriteDoesNotBlameTheWalk fails with exactly the expected message; reverted, green again. Probe deleted afterwards.

Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).

Comment thread cmd/agentop/cmd_export.go
}
}
if got == 0 {
return fmt.Errorf("--session needs at least one id")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — fmt.Errorf with a constant string; errors.New("--session needs at least one id") is the idiom (staticcheck S1039 flags this). Kurczę, even the error messages are thorough. Suggested fix: swap in errors.New and drop the fmt use if nothing else in the file needs it (it does, so just the one line).

Why it's only a nit: message and behaviour are identical; purely idiomatic.

Comment thread docs/session-export.md
Sessions the archive last touched before the floor are skipped without reading their
segments.

## `agentop export`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — the example says 3 records, 231B → (stdout), but the three-record canned export in the tests (exportLines) is 115 bytes on the wire, and three real ~30-scalar records would be well past 231B. The number can't be right for either reading of "three records".

Suggested fix: make the example self-consistent — either match the test fixture (3 records, 115B → (stdout)) or label it as illustrative with a realistic real-record count (three real lines are closer to a few kB).

Why it matters here: the PR holds itself to its claims elsewhere with admirable precision, so the one number a reader might actually check shouldn't be the odd one out.

@huang195 huang195 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My two items from 52d14fb are fixed. I checked both against the head (27198c2).

  1. must-fix (truncated export exits 0): fixed in #1830 (9c2d752, panic(http.ErrAbortHandler) after the Warn). TestRunExport_TruncatedWalkExitsNonZero pins the CLI side. Note: this branch does not contain 9c2d752 yet. The CLI fix is correct only after #1830 merges, so merge #1830 first, as the PR body says.
  2. suggestion (--since refusal got the session hint): fixed with ErrNoDetail. The noDetail wrapper keeps errors.Is(err, ErrBadRequest) true, and the message text does not change.

One new suggestion, inline. I agree with @clawgenti's open nit on defer f.Close() (L184), so I do not post it again.

Checks: the 12 TestRunExport_* tests and ./apiclient pass. go vet ./... and gofmt -l . are clean in cmd/agentop.

Author: mrsabath (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop, apiclient), docs
Agent/IDE config (.claude/.vscode): none
Commits: 9. The merge commit 71b9fde has no sign-off, but the DCO check passes.
CI status: passing (DCO and title only, because the base is session-export-walk)

Assisted-By: Claude (Anthropic AI) [email protected]

Comment thread cmd/agentop/cmd_export.go
if counted.err != nil {
fmt.Fprintf(stderr, " writing %s failed; it may end in a partial line\n", where)
} else {
fmt.Fprintf(stderr, " the walk failed part-way; %s holds every complete record before it\n", where)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: a failed read can also stop mid-line, and then the walk did not fail.

The comment above says a failed read "only ever ends the stream at a record boundary". That is true for the server's abort, because the server flushes once per record. It is not true when the connection breaks for another reason:

  • the proxy restarts or stops during the export (agentop service restart, agentop update)
  • exportTimeout expires during the body read

I ran runExport against a server that writes {"a":1}\n{"b":, flushes, and then aborts:

code=1 stdout="{\"a\":1}\n{\"b\":" stderr="agentop export: unexpected EOF\n  the walk failed part-way; (stdout) holds every complete record before it\n"

The file ends in half a record, and jq then fails on the last line. The hint names the walk as the cause. The "every complete record" text is still true, but a reader takes it to mean the file is clean.

Suggested fix: use one neutral read-side message, for example the export stopped part-way; %s holds every complete record before it, and may end in a partial line. Also change the comment at L198, and the same sentence in docs/session-export.md ("says the file holds every complete record before the failure").

@mrsabath
mrsabath merged commit 243d52b into session-export-walk Nov 16, 2026
3 checks passed
@mrsabath
mrsabath deleted the session-export branch November 16, 2026 21:14
mrsabath added a commit that referenced this pull request Nov 16, 2026
main had moved 196 commits ahead, and `agentop import` landed there while
`agentop export` landed here, so the two collided in cmd/agentop/main.go in the
three places a subcommand is registered: the dispatchableSubcommands slice, the
usage block, and main's switch.

Both belong, so both are kept, with export before import to match the slice
order. Nothing of main's import work is dropped -- the diff against main is three
pure additions.

Resolved by merge rather than rebase: the branch is pushed, reviewed, and already
contains #1831's merge commit, so rewriting it would discard history others have
reviewed against. main takes PRs as merge commits anyway.

TestRootUsage_ListsEverySubcommand and
TestUnknownSubcommandMessage_NamesEverySubcommand are the gates here -- both hold
the usage text and the error message to the slice -- and both pass, as do the
export and import suites and core/sessionapi + core/sessionexport. All four
modules build and vet clean.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>
mrsabath added a commit that referenced this pull request Nov 17, 2026
…1830)

* Feat: Walk the archive into content-free records over GET /v1/export

The projection from #1812 had no caller: nothing could ask for an export.
This adds the walk and the transport, the two pieces #1810 leaves after the
schema.

core/sessionexport.Walk composes what the archive already exports —
Summaries for the session list, Earlier for the events, tunnel rows included
where ReplaySince drops them — into the Writer from #1812. Filter selects
sessions and floors event time; an unknown session id is an error naming the
archived ones, raised before the first record so a caller can still answer a
status.

GET /v1/export streams it as application/x-ndjson, one line per event,
flushed per record. session and since (a Go duration or a day count) are
parsed before the first byte; without an archive the endpoint is a 404, the
shape WithUsage and WithCatalog set. The index gains its line by folding the
GET /v1/sessions/{id} entry to one, keeping the 18-line cap.

The durable archive only, not the store: a backfill, at most a tick behind
the open segments, documented as the gap it is. sessionIncarnation stays out
(#1739), as does a live tap.

docs/session-export.md is the reference: the reading rules a consumer gets
wrong otherwise (zero means absent, order by at then seq, never subtract
timestamps, the token split), the privacy claim restated at the HTTP layer
and pinned there by test.

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Answer a status when the export walk dies before its first record

Three must-fixes from the #1830 review, plus the small findings around them:

- Walk cloned the caller's Sessions map before matching ids against it. The
  delete-as-you-match loop used to empty the caller's own Filter, so a reused
  filter silently widened to every session — the one direction a safe export
  must not fail in. A twice-walked-filter regression test pins it.
- The handler now reads flushWriter's wrote flag, which is what it existed
  for: a walk that fails before its first record answers 500 (search.go's
  archive-read-failed shape) instead of 200 with a body byte for byte equal
  to an empty archive's. Past the first record it still truncates, now
  logged at Warn — the only trace a truncated export leaves.
- The doc's one record example carried promptTokens and completionTokens,
  the very double count Record's own rules warn about; it now carries the
  projection's real token fields, pinned by a strict decode into Record so
  the doc cannot drift from the wire again.

Around them: parseSince rejects day counts past 106751 (the multiplication
used to overflow time.Duration negative and read as an empty export), a
repeated since parameter is a 400 rather than a silent first-wins, the 400
body is json.Marshal-escaped rather than Go-%q-quoted, UnknownSessionsError
renders its ids capped (first few and a count of the rest) so the answer
always fits what a client reads, Walk folds the in-flight session's records
into its stats before an error return, and the docs stop calling a
since-filtered session carried whole or an export blanket-safe to pipe
anywhere.

The session-skip branch is pinned on its own now: the fixture writes one
session under an archive clock a week back with events above the floor, the
one placement where the UpdatedAt skip rather than the per-event stop does
the excluding.

Refs #1810
Assisted-By: Claude (Anthropic AI) <[email protected]>

Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Bound the unknown-session refusal in bytes, not in ids

Two review findings, one root cause and one claim that outran its code.

THE REFUSAL OVERRAN THE READ IT IS SIZED FOR. cappedList capped the number of
ids in UnknownSessionsError's message, not its length, and a session id is
client-asserted and bounded only by session.MaxSessionIDLen (256). So the cap
held for the short ids the tests used and failed for real ones: five requested
UUIDs against eight archived rendered 538 bytes, four against a 50-session
archive 512, one maximum-length id 618. agentop reads 512 bytes of a 400 body,
so past that the JSON is cut mid-string, badRequestDetail returns "", and a typo
answers "apiclient: bad request" — no names, no hint, nothing to act on.

cappedList now spends a byte budget instead: half to the requested ids (the
asker's own words come first), the rest to the archived ones, with an id past 64
bytes truncated so one pathological id cannot spend the whole budget or hide
every other. The budget is 400, under the 512 the client reads, leaving room for
the {"error":...} wrapper and for JSON escaping. The struct's fields stay
complete — the bound is in the rendering, as before.

All three overflow cases now land at 441-448 bytes wrapped, still naming every
requested id and five archived ones.

A SEGMENT THAT WILL NOT DECODE *DOES* READ AS AN EMPTY ARCHIVE. The handler's
comments and docs/session-export.md promised the opposite ("so a broken archive
never reads as an empty one"), but readRecordsWith reports a torn or undecodable
line as truncated=true with a nil error, and Page discards the flag — so the walk
sees nothing and the handler falls through to an empty 200. Only a segment that
cannot be OPENED reaches the 500. Rather than widen this PR into the archive
package, the claims now say what the code does, and the archive change has its
own issue (#1855).

TESTS. TestWalk_UnknownSessionErrorIsBoundedInBytes covers the shapes a count cap
could not hold, asserting the WRAPPED body length a client actually reads.
TestHandleExport_UnknownSessionRefusalFitsAClientRead drives a 50-session archive
of UUID-length ids through the real handler — the existing fixture's "s1"/"old"
refusal is 60-odd bytes and could never go red. Confirmed red before this fix
(568 bytes) and green after.

TestHandleExport_BrokenSegmentIs500 swaps chmod 0 for a self-referential symlink:
root ignores mode bits, so the old fixture passed CI and failed for anyone running
go test as root. A directory would not do either — os.Open succeeds on one on
macOS and the read fails later, which readSegment calls truncated, i.e. a 200.
ELOOP is refused for every uid and needs no chmod-back cleanup.

ok  core/sessionexport
ok  core/sessionapi
ok  core/model

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* Fix: Budget the unknown-session refusal in JSON-escaped bytes

The 512-byte bound on the 400 body was counted in raw bytes, but the handler
sends the message inside a JSON string (sessionapi/export.go marshals
err.Error()). encoding/json HTML-escapes `<`, `>` and `&` to six bytes each by
default, and a control rune becomes a six-byte \u00XX, so a 64-byte id could
cost 384 bytes on the wire. Session ids are client-asserted and need only be
printable, so all of this is reachable.

Measured on the previous commit, through the real handler and archive:

  requested "<"x64 and "<"x63+"a"          -> 400, 1064 bytes
  requested "\x01"x64 and "\x02"x64        -> 400, 1069 bytes
  20 archived ids of "&"x40, requested typo -> 400, 2035 bytes

The last case needs no hostile query: `&` is printable, so one in a client's
own ids made every typo against that archive unparseable to agentop — the bare
`apiclient: bad request` this branch set out to stop.

Three changes:

- escapedLen charges a string at json.Marshal's width, and every budget is
  counted in it: cappedList tracks `used` beside the builder, and the known
  list's share is the escaped width of the requested one.
- truncateToEscaped caps an id at errorListIDMaxLen ESCAPED bytes rather than
  raw ones, cutting on rune boundaries. Truncating raw was what let the "at
  least one id is always rendered" rule overrun the whole budget with a single
  pathological id. Rune-safe cutting also keeps a multi-byte id from ending in
  the U+FFFD that a mid-rune byte slice produces.
- the fixed text comes out of the budget before either list gets a share, and
  errorMsgBudget drops 400 -> 360: at 400 the worst case landed at 502 bytes,
  ten short of the limit. It is now 306-346.

TestHandleExport_UnknownSessionRefusalFitsAClientReadWhenIDsEscape covers the
three cases above through the HTTP handler with url.Values-encoded queries; it
fails at 1064/1069/2035 bytes against the old code. The existing bounded-ness
test computed its expected prefix with a raw byte slice, which encoded the old
truncation; it now asks truncateToEscaped, the same helper the message uses.

Signed-off-by: Mariusz Sabath <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>

* fix: Reset the connection when the export walk dies part-way

A walk that failed past its first record logged a Warn and returned normally.
net/http then wrote the terminating chunk, so the client read a clean EOF off a
200: io.Copy returned nil, `agentop export` printed its success summary and
exited 0, and a short file was indistinguishable from a whole one. The only
trace was a line in the proxy log.

Panic with http.ErrAbortHandler after the Warn instead. The forward proxy's
stream relay already fixed this bug class the same way in three places (#1543),
and classifyBrokenStream's note spells out why a normal return is wrong: it
hands the client a COMPLETE response off a stream that was cut off. There is no
recover() between the mux and this handler, and the standard library suppresses
the stack trace for ErrAbortHandler specifically.

The Warn stays -- it is the server's trace, and the panic only tells the client.
Every complete NDJSON line already flushed stays valid, so a consumer keeps what
arrived and reads an error at the end rather than a clean end of body.

The branch had no test. The new one breaks the OLDER of two segment files, since
Page reads newest-segment-first, so records are written before the walk dies; it
goes red without the panic, printing the 3 whole records and clean EOF this
fixes. Two open/close cycles to get two segments -- rolling is by size and idle,
never by an event's timestamp -- and a self-referential symlink for the fault,
because os.Remove is skipped as fs.ErrNotExist and a directory reads as merely
truncated. A clean-walk control pins that healthy exports are not aborted, and
readKeepingError exists because getBody and getPath both t.Fatalf on the read
error this has to assert on.

Reported by huang195 in review of #1831.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Refuse a signed day count, and pin the truncation fixture's clock

Two review findings, both about a contract quietly not matching its words.

parseSince accepted "+7d". strconv.Atoi allows a leading sign, so it parsed to
168h while being a form nothing documents -- docs/session-export.md and the 400
message both say "a Go duration or a day count", and the day-count grammar has
no sign in it. This is the parameter grammar a client codes against, so refuse
it in that branch. The duration branch is untouched: a sign IS part of
time.ParseDuration's documented grammar, and a negative value is already refused
for being non-positive.

TestParseSince_Grammar pins the whole accepted set rather than just this row --
parseSince had no direct test at all before, only the HTTP-level since test. It
goes red on exactly the +7d row with the check removed.

And TestHandleExport_TruncatedWalkReachesClientAsError reopened its archive on
wall time while writing fixed November 2026 segments. Open prunes to the 30-day
retention as it reconciles, so from mid-December the segments would be gone, the
os.Remove of the older one would fail, and the test would have stopped
exercising the walk well before anyone noticed. Pass the fixture clock. Verified
by dating the fixture three months back: it fails with "no such file or
directory" without the clock and passes with it.

Reported by clawgenti (+7d) and coderabbitai (the fixture clock).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Stop calling the export "safe anywhere" in the same breath as its metadata

The sentence named what a record still carries -- hosts, models, session ids,
timestamps -- and then called the file "safe anywhere the dump is not", which
reads as a blanket assurance sitting next to the list of what leaks. Split the
two claims: content-free is what makes it shareable, and it is explicitly not
anonymous, because those four fields together describe who talked to what and
when.

Matches the wording docs/session-export.md already uses ("content-free is not
detail-free"), so the two pages now make the same promise.

Reported by coderabbitai.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* Feat: agentop export writes the archive's record export to a file (#1831)

* Feat: agentop export writes the archive's record export to a file

The endpoint from the previous commit, as a command: agentop export
streams GET /v1/export to stdout or --out, with --session and --since as
the endpoint's parameters and a summary line on stderr — stdout may be
the export itself, so nothing human goes there.

apiclient.Export is a thin query builder over getBody, which already maps
the endpoint's whole error contract: an unknown session or a bad since is
a 400 the server answers before its first byte, carrying its own words
(the archived ids, the accepted forms), and a proxy without an archive is
a 404. That made the planned client-side pre-check via ListSessionsArchived
redundant and subtly wrong — the archived list also names resident
sessions the archive has not flushed yet, which the endpoint would rightly
refuse — so validation stays where the archive is, and the command opens
its output file only after the proxy answered: a typo costs nothing.

The command owns its own budget (exportTimeout, ten minutes) rather than
inheriting getBody's 60s deadline-less default: the walk reads every
segment single-threaded (~10s for a 30-day archive), and HeaderTimeout
remains the liveness backstop for a proxy that never starts answering.

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Refuse the silent widenings in agentop export

The #1831 review's must-fix — the 400 path going silent past ~11 archived
sessions because getBody reads 512 bytes of the body while the server listed
every archived id — is fixed server-side in the commit below: the error now
names the first few ids and a count of the rest, so the answer always
arrives whole. This commit carries the client half: the help text, the
ErrBadRequest comment and apiclient's Export doc now say what actually
happens instead of promising the uncapped list.

And the two silent widenings a filter flag must not have:

- A --session that yields no ids is a usage error, not an absence. Empty
  is the dangerous direction for a filter: `--session "$(ids)"` with an
  empty expansion used to export the whole archive, exit 0.
- A stray positional is a usage error too. `agentop export out.ndjson`
  used to ignore the filename and dump the archive to stdout, exit 0;
  every sibling command already rejected positionals.

The 404 hint now names the other proxy that answers it — one predating
/v1/export, the mixed-version window during an update — rather than
asserting the archive is off.

Refs #1810
Assisted-By: Claude (Anthropic AI) <[email protected]>

Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Leave a typo somewhere to go when the refusal does not fit

The review's point, and it was right: this command's only answer to a refused
--session was the proxy's own words, and those words only arrive if they fit the
512 bytes getBody reads of a 400 body. Past that the JSON is cut mid-string,
badRequestDetail returns "", and the user gets:

  agentop export: /v1/export?session=nope: apiclient: bad request

No names, no hint, and this branch added nothing on top.

#1830 fixes the cause — the refusal is now rendered under a byte budget rather
than an id count, so a current proxy's words fit, and that commit is merged in
below. This one handles what the budget cannot reach: an older proxy, which caps
by count and still overruns on long ids. When the detail did not survive, the
command now prints the curl that lists the archived sessions, so a typo is never
a dead end.

THE PROSE THAT OUTRAN THE CODE, in all three places the review named: the --help
paragraph, Export's doc comment and docs/session-export.md said the list was
"capped server-side so the answer always arrives whole". That was a count cap and
it did not guarantee that. They now describe the byte budget, and say plainly that
an older proxy can still overrun it and what happens when it does.

TestRunExport_RefusalTooLongToParseStillPointsSomewhere drives a 538-byte refusal
— what a count-capping proxy answers for 5 unknown UUIDs against 8 archived ones
— rather than exportServer's canned 72-byte body, which always fits and so could
never go red. Verified red before this change (printing exactly the bare
"apiclient: bad request" above) and green after.

ok  cmd/agentop            (1034 tests in 8 shards; the 3 failures are
                            pre-existing sandbox-environment artifacts —
                            xcode-select, polkit/systemd, a foreign PID —
                            and fail identically on the base)
ok  cmd/agentop/apiclient

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Print the session hint only when the refusal would not say why

Three review findings on the ErrBadRequest branch, all on the same few lines.

The hint fired on a refusal that HAD explained itself. The condition was "a
session was asked for and the words do not mention sessions", so
`--session s1 --since bogus` printed "the proxy did not name the sessions it
holds" underneath the proxy's own perfectly clear complaint about since,
sending the reader to look at sessions when since was the problem.

What the branch wants to know is whether any detail arrived at all, and getBody
already knows: it either wraps the server's words or does not. Carry that as an
exported ErrNoDetail sentinel beside ErrBadRequest and check it with errors.Is,
rather than matching on either the server's wording or getBody's own formatting.
It is wrapped in a type that adds nothing to the message, because the text is
printed to a user and "bad request: apiclient: no detail" reads worse than the
bare refusal it would replace. errors.Is(err, ErrBadRequest) is unaffected.

The hint's curl was not runnable. It printed the raw --endpoint, so
`--endpoint http://host:47601/` produced `host:47601//v1/sessions`, which
ServeMux answers with a 307 whose HTML body is all `curl -s` shows -- the one
fallback meant to rescue a dead end leading into another. Keep the client and
print Endpoint(), the trimmed form the request itself uses.

And the Export doc comment claimed a failed walk "simply ends the body, which
NDJSON tolerates". It resets the connection as of #1830, so the caller sees an
error rather than a short success; the help text now says the command exits
non-zero and what the output holds.

Tests: a refusal that named a different problem gets no hint, a trailing-slash
endpoint produces no doubled slash, a truncated export exits 1, and ErrNoDetail
is pinned across all three 400 shapes -- parseable, undocumented, and cut by the
512-byte read. The first two go red against the old conditions.

Reported by clawgenti and huang195.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Say that a truncated export resets rather than ends cleanly

The same two places #1830 corrects, carried here so this branch's own diff does
not describe the old behaviour: a walk that dies part-way resets the connection,
so a client reads an error and `agentop export` exits non-zero, rather than
ending the body cleanly and looking complete.

Identical text to #1830's, so merging that into this branch changes nothing.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* chore: Drop a stray .commitmsg from the previous commit

`git add -A` picked up the heredoc file the commit message itself was written
from, before the rm. Not meant to be tracked.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Blame the disk, not the walk, when the write is what failed

io.Copy reports a failed read and a failed write as the same non-nil error, and
this branch described only the read side. An --out to a small partition printed
"the walk failed part-way" over an ENOSPC: wrong cause, pointing the user at
Cortex when the disk is full. It was wrong twice, because a short write can stop
mid-line, so "holds every complete record" is not true there either -- only a
failed walk ends the stream at a record boundary.

lineCounter already saw the write error and dropped it; keep it and branch on it.

The test uses a writer that always fails rather than /dev/full, which does not
exist on macOS: the destination goes through the same lineCounter either way, so
this runs everywhere instead of silently skipping outside CI. It goes red
against the old message, printing the same line the review quoted.

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

---------

Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Refuse a malformed query and an empty --since; pin two more fixture clocks

Round five. Three must-fixes, two overclaims.

A malformed query exported the WHOLE archive. URL.Query() drops the pairs it
cannot decode and returns the rest, so ?session=%GG and ?since=%ZZ read as
absent filters and answered 200 with every record -- more data than was asked
for, which is the one direction a filter must not fail in. ?since=1h&since=%ZZ
was worse: both values were dropped, so even the repeated-since 400 never saw
them and no floor applied. Parse with url.ParseQuery and refuse what will not
decode. agentop never reaches this (Values.Encode escapes), curl does.

An empty --since was the sibling of the --session hole fixed last round, and I
had written the rule and then not followed it: `--since "$(window)"` with an
empty expansion was indistinguishable from an unset flag, so a broken variable
exported the whole archive at exit 0. fs.Visit sees only the flags given, so an
omitted --since still means no floor. Whitespace-only counts too -- my own test
caught that first pass, since f.Value.String() is " " rather than "".

Two more fixture clocks, same bug as 7f03559 fixed in export_test.go's twin: the
reopen in walk_test.go's TestWalk_SinceSkipsOnUpdatedAtNotJustEvents ran
retention on wall time, and so did fixtureArchive and exportFixture, whose `old`
sessions are dated a week back. From mid-December each would have quietly stopped
carrying that session. Verified by dating the fixtures three months back: the
skip test fails without the clock and passes with it.

And two claims the code did not support. The --help said the file is "safe to
hand to anything the full events must not reach" -- the exact overclaim 7bb4607
took out of session-dump.md, and --help is what users actually read. The
exportTimeout comment said the ~10s walk figure was "measured"; it was
extrapolated from a smaller fixture, as I admitted on the Earlier thread, so it
now says so and points at the missing benchmark. Dropped the number from the
--help and the flushWriter note rather than repeat it.

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Label the export's refusals application/json, not text/plain

http.Error sets `text/plain; charset=utf-8` unconditionally, and on this route it
also overwrote the `application/x-ndjson` set for the success path -- so one
endpoint's two surfaces disagreed about a header they both send, over a body
that is `{"error":...}` either way. docs/session-api.md documents the route's
content type, and a client negotiating on it would be misled; agentop is not,
because badRequestDetail parses the body regardless.

A file-local jsonError rather than a package-wide helper: the other handlers
share the wart, and changing them is a repo-wide edit with its own blast radius.
This keeps the endpoint this PR introduces honest without quietly altering
responses from endpoints it does not own.

TestHandleExport_RefusalsAreLabelledJSON covers the four refusal shapes plus the
success path, and asserts the label is TRUE -- each body has to parse as a JSON
refusal, so a future handler cannot satisfy the header and send prose.

Raised three times by clawgenti (as consistent-with-search.go, then twice as a
wire-consistency nit); cheap enough to just fix.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Point the walk's cost estimate at the benchmark issue

#1895 tracks the three things the Earlier-paging thread raised: benchmarking the
walk, skipping segments below the ?since floor, and reading forward per segment
instead of paging backwards. The exportTimeout comment now names it, so the
extrapolated ten seconds has somewhere to be resolved rather than just a
disclaimer.

Also rewraps two comments this PR's earlier edits left running long.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Add a walkthrough for exporting and analysing the archive

session-export.md is the reference -- what each field means. This is the
task-oriented half: check you have an archive, get a first export, make it
answer a question, and recognise the ways it can mislead you.

Every command and every output in it was run against a served archive seeded
with two sessions, rather than written from the code. That caught two things
worth having:

- the obvious `jq -s 'map(.inputTokens) | add / length'` is 43% low on the
  fixture, because omitted fields arrive as null and average in as zero. Both
  the wrong and right forms are shown with their real numbers.
- the session-splitting recipe fails outright: `at` carries fractional seconds
  and fromdateiso8601 rejects them. Fixed with a sub() and the output shown.

Three traps get their own section, since each produces a plausible wrong answer
rather than an error: absent-is-not-zero, order by at-then-seq, and a session id
not being a unit of work.

Covers the three ways people reach this: a laptop user with jq/DuckDB/pandas, an
operator against a cluster sidecar (which normally has no archive and 404s --
documented with the real message), and a script author, with the exit-code table
and the truncation-exits-non-zero guarantee.

Linked from docs/README.md and from the reference.

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Rewrite the export and dump docs in the spirit of ASD-STE100

The session-export guide explained `"resident": false` as "sessions memory has
already evicted", which is a garden-path sentence -- "sessions memory" reads as a
compound noun -- and it assumed the reader knew the store/archive split. It now
defines the field in four short sentences, says what each value means for the
viewer and for the export, and says why the field is the reason to export at all.

Applied the same treatment across all three documents:

- One topic per sentence, and sentences under 20 words. Long sentences fell from
  46 to 10 across the three files; mean length is now 8-11 words. The ones left
  are deliberate enumerations.
- One term per concept. A "record" is a line of the export, an "event" is what
  Cortex captured, the "store" is memory and the "archive" is disk. Each
  document now states these once and does not vary them.
- Procedures as single actions. The guide's walkthrough is four numbered steps,
  one command each, instead of prose that bundled several actions per sentence.
- Active voice, and the em-dash subclauses split into their own sentences. Those
  were carrying load-bearing facts in the least readable position.

Every technical fact is preserved; checked by grepping each figure, field name
and issue reference before and after. TestDocExampleRecordMatchesWire still
passes, so the record in session-export.md is still wire-accurate.

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Say where a session id comes from, and what the timeline cannot answer

Three gaps a user hit while following the guide.

The guide never said what --session takes. It takes a session id, matched
exactly: walk.go does a map lookup on s.ID, so no title and no prefix works.
Step 2 also listed ids with no titles, which is useless for choosing one. It now
shows the id-plus-title listing, and Step 4 links back to it.

A title is user content. It is derived from a /rename, else a user query, else
ordinary conversation, so it contains prompt text -- on a test fixture a planted
prompt surfaced verbatim as the title. The discovery command therefore prints
exactly what the export excludes, and the guide now warns about that. The export
carries no title at all, so labelling a report means joining back to
/v1/sessions.

The timeline carries outputTokens and liveTokens only -- no inputTokens, no
cache counts. A user built a two-request join with temp files to get a
per-request token table, because nothing said so. The export has all four token
fields, so the same table is one request and no join, and it fills toolCallCount
which the join left blank. Added that recipe, plus a table of which endpoint
holds what.

Also documented why the join appears to lose tool names: the timeline's tools
array holds tool spans, which is real tool traffic through the proxy, not the
toolCalls a model asked for. A join on a model call's seq finds nothing, and
that is expected.

Every command and output in this commit was run against a served archive seeded
with paired request/response events.

Refs #1810

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Render the export's `at` in UTC, and pin the escaped-width budget

Round six. One behaviour change, two test gaps, one nit.

`at` was the listener's time.Now(), so it carried the proxy's local offset. That
made an export unreadable to the obvious tools: jq's fromdateiso8601 is a strict
Z parser and errors on "+01:00" (exit 5, before the first line of output),
pandas raises "Mixed timezones detected" for a window spanning a DST change, and
a lexical sort of mixed offsets misorders the hour the clocks go back. FromEvent
now converts to UTC. The instant is unchanged; only the rendering is uniform.
docs/session-export.md's own example carried -05:00 and is now the same instant
as 15:52:26Z, which TestDocExampleRecordMatchesWire still holds.

TestFromEvent_AtIsUTC pins it across CET, EST and UTC, and asserts the INSTANT
survives rather than only the suffix -- a test that checked the Z alone would
pass for a record that shifted the event by its offset.

The escaped-width budget had no test in the package that owns it. Verified: with
escapedLen mutated to return len(s), TestWalk_UnknownSessionErrorIsBoundedInBytes
passed and only core/sessionapi caught it, so a refactor of the sessionapi test
would have left the regression invisible. Every row in the sessionexport table
was bytes json.Marshal leaves alone. Added the ampersand case, which now fails
at 1532 bytes under that mutation, and a multi-byte rune case asserting no
U+FFFD -- the one shape truncateToEscaped's doc claims and nothing exercised.
Added the same rune case and U+FFFD assert to the sessionapi table.

flushWriter set `wrote` even for a write that moved no bytes, so a failed FIRST
write skipped the pre-record 500 and reset the client instead, for a failure it
had seen nothing of. Set it only when n > 0.

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Fix the guide's jq, and stop promising what the refusal does not do

Four findings on the walkthrough, all verified before changing anything.

The resident column could never print false. In jq, `a // b` yields b when a is
null OR false, so `(.resident // true)` reported every session as resident --
including the one case the four sentences below it explain, and contradicting
the sample output on the same page. A reader would conclude the archive holds
nothing memory had lost, which is the stated reason to export. Now `!= false`,
with a line saying why, since this is a trap for anyone writing their own query.

The at recipes now work on a non-UTC proxy, because FromEvent renders UTC as of
the previous commit. Verified against a CET-seeded server: the gap recipe used
to die with exit 5 on the first record and now exits 0 with the right gap. The
sort recipe needed its own fix regardless -- fromdateiso8601 rejects a fraction
even with a Z, so it strips the fraction and adds it back, and the output shows
the tie ordering that a string sort gets backwards.

The percentile recipe printed a confident p50=0ms at n=1, indexing a[0] in an
array that starts at 1 -- the exact failure trap 1 warns about. Fixed for any
n >= 1.

The pandas line parses with utc=True and format="ISO8601", and its comment said
"fill before you aggregate" while the code deliberately does not fill. It now
says not to fill, and why min_count=1 is the right call. NOTE: pandas is not
installed in this environment, so that snippet is the one thing here I could not
execute.

Also: a sidecar runs no archive "normally", restoring a qualifier a previous
rewrite dropped and which contradicted a later paragraph; and the refusal always
names at least one id, so the curl hint fires when the message outran the
client's read, not when no id fits.

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Correct the tools/seq explanation, and stop a column shift hiding absence

Three findings on the guide, two of them must-fix.

I had the timeline backwards. The guide said `tools` holds "real tool traffic
that passed through the proxy" and that a join on a model call's seq finds
nothing "by design". The source says otherwise: t.Tools is appended in exactly
one place (agents.go:211), from c.resp.Inference.ToolCalls, and Tool.Seq is
c.resp.Seq. So tools IS the model's requested calls, and the join works -- on
the RESPONSE seq. Turn.Seq is c.req.Seq, one lower, which is what finds nothing.
My own earlier blank TOOLS_ASKED column came from a fixture with no tool calls,
and I wrote it up as a design limitation. The paragraph also contradicted the
table two lines above it, which was right.

The per-request table dropped values into the wrong columns. @TSV writes an
empty cell for an absent field and `column` merges adjacent blanks, so a
response with no cacheWriteTokens -- ordinary on a cache hit -- reported its
output tokens as cache writes, with no error. Reproduced: 67 output tokens
printed under CACHE_W. `map(. // "-")` keeps the columns aligned and makes
absence visible, which is what trap 1 asks for anyway. Also `printf` instead of
`echo -e`, which prints a literal "-e" under dash.

And the session listing dropped every untitled session via select(.title) --
tunnel-only traffic and utility clients, which are the rows a reader most needs
an id for, since no other command names them. Now shows "(untitled)" and keeps
the row.

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* fix: Make the mid-rune asserts able to fail, and undo the flushWriter gate

Round seven, and two of these are mine to own.

Reverting last round's `if n > 0 { f.wrote = true }`. clawgenti retracted the
nit that prompted it and was right to: net/http's response.write calls
WriteHeader(200) BEFORE it looks at len(p) or at any error, so ANY call has
already committed the status line. Gating on n did not preserve the 500 path, it
only made the handler believe a status was still available. Probed: a
zero-length Write commits 200 application/x-ndjson, and the 500 path then logs
"superfluous response.WriteHeader" while the client reads a clean 200 whose body
is {"error":"archive read failed"} -- the #1543 class this endpoint exists to
avoid. Unconditional again, with a comment saying why n is not consulted.

Both U+FFFD asserts I added last round could not fail, which is worse than not
adding them: they looked like coverage. On the Go side err.Error() holds raw
invalid bytes, not the replacement rune, so a search for U+FFFD never matches --
now utf8.ValidString. On the wire json.Marshal writes the six characters �,
never the rune, so an interpreted "�" searched for something that is never
sent -- now a raw string literal.

The test data was also wrong, which clawgenti's mutation did not reach: "ż" is
two bytes and divides the budget evenly, so even a raw-byte cut lands on a
boundary. Switched both rows to "日" (three bytes), which does not. Verified by
mutating truncateToEscaped to cut on raw bytes: both tests now fail, showing the
dangling \xe6 on the Go side and the � escape on the wire, and both pass
against the real implementation.

Also: TestRecord_CarriesNoContent had lost its doc comment, because the new
test's block was pasted onto the end of it with no func between. The privacy
test is the one this PR leans on, so it gets its label back. And a flushWriter
comment line that ran to 152 columns is wrapped.

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

* docs: Stop claiming a turn's seq is one below its response

"which is one lower" was true of my fixture and nothing else. seq is a
per-session counter over EVERY event (store.go:499), so tunnel rows, other
hosts and the side calls the timeline drops all take numbers in between. On live
traffic a turn's response is often seq+2 or more -- pairCalls' own doc notes the
side calls were more than half the main role's requests on a real session, and
parallel subagents interleave too.

A reader joining turn.seq+1 to the tools would get wrong names, or none, with no
error: the trap-1 class again, in a paragraph that already had to be corrected
once.

The guide now says the two are not adjacent, and names requestId as the stable
key for getting from a request record to its response -- which is what the
timeline itself pairs on (agents.go:395).

Reported by clawgenti.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Mariusz Sabath <[email protected]>

---------

Signed-off-by: Mariusz Sabath <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants