Surfaced vs relevant: capture which SageOx context the agent actually used
Context
Today ox records what context reached an agent session fairly well (prime docs, whisper deliveries, ox tool calls as invoked events in context-trace.jsonl) but almost nothing records whether the agent found any of it relevant. The only "used" signals are: consulted events inferred at CLI finalize from file reads and retrieval commands, free-form influenced events the agent writes only when prompted by ox usage, and a single self-reported ox session score category per session.
Dev and Ryan agreed on Oct 26 ("Ox CLI status line design feedback", https://sageox.ai/c/cnv_01a17990-4cb6-7bf9-9584-4728f14b54f1): ~99% of whispered murmurs are not useful, only context the agent actually found useful should be shown, and the co-author decision is "hand-waving, no metrics". This plan adds the metadata so ox can show here is what surfaced vs here is what was relevant, and compute (for display only, for now) what SageOx would have co-authored.
Decisions already made (Dev):
- Capture relevance through all three evidence layers: agent self-report at the moment of use, deterministic detection from the transcript, and an LLM judge at finalize.
- Co-author trailer logic stays display only: compute a derived category and show it, do not change
cmd/ox/hooks_commit_msg.goor the score threshold. - Persist a compact rollup in session
meta.jsonand expose counts for a statusline segment. - Ownership split: this session owns capture, ranking, rollup, and the report data fields. Another session (ox-usage-pane-plan) owns rendering in
internal/usage/render.go, the pane, and the statusline, and is first renamingox usagetoox brief(skillox-cli-brief, pane/ox-brief, configbrief_pane). Our PRs branch from main after that rename merges. The display session builds against the field names in §3.
Ground truth that shapes the design (verified on origin/main)
- Local
mainis behind origin/main;cmd/ox/usage*.go,internal/usage/*,internal/usagepane/*exist only on origin/main. Start withgit pull. contexttrace.Event(internal/session/contexttrace/contexttrace.go) already hasSeq, Mechanism, Ref, RefType, Query, Score, WhisperID, Decisionplusinvokedfields. Readers switch onType, so a new event type is ignored by old readers.- Two
Seqframes exist: whisper/invoked writers usestate.EntryCount;consultscan.ScanRawFileuses the raw.jsonl line index (header line makes it +1). "Used after surfaced" comparisons must normalise to one frame. consultscanruns only on the CLI finalize path (cmd/ox/session_consult_tagging.gofromcmd/ox/agent_session_incremental.go:266); the daemon finalize (internal/daemon/agentwork/session_finalize.go) never tags. Both paths copy the score file into meta.json (~L1835/1955 daemon;cmd/ox/agent_session.go~L1756 CLI).writeTeamWhispers(cmd/ox/agent.go~L1710) emits<entry>without anid, so the agent cannot cite a whisper.writeXMLAttributeexists atcmd/ox/agent.go:1737.- The recall preamble (
cmd/ox/agent_hook_recall.go) writes nothing to the trace;usage.Unmeteredlists it. It runs inhandlePromptbeforeagentIDis resolved. agent_query.goalready has aGuidancefield (L160) andexecuteQuery(L186);ledgersearch.Result.SourceIDis the citable ref for local hits; cloudQueryResultcarriesSourceID,Title,URL.oxactivity.Classifyalready labelsagent session context-traceas "reported context use" (internal/oxactivity/classify.go~L337).- Judge adapter (
internal/daemon/agentwork/judge_adapter.go) is a genericsummaryeval.Completer, gated byOX_SUMMARY_JUDGE=on, daemon-only, cached under.sageox/cache/summary-judge/. - ADR-027 (
docs/adr/ADR-027-consultation-attribution-privacy.md): a use record lives in the reader's own session record, refs only, never content; team views aggregate only.
1. Evidence model
| Layer | Mechanism | evidence values | Writer | Grade |
|---|---|---|---|---|
| A. Deterministic | retrieval (read/requery), citation (new) | read, requery, cited, cited_commit | finalize scan + post-commit hook | provable |
| B. Self-report at moment of use | self-report | reported, none | ox agent <id> context used | reported |
| C. LLM judge | judge (new) | judged | daemon finalize, opt-in | judged |
Display buckets map 1:1: read (read + requery), cited (cited + cited_commit), reported, judged.
A. Deterministic scan (extend internal/session/consultscan)
- Extend
consultscan.EntrywithTypeandContent(assistant text). AddScanUses(entries, surfaced []contextuse.SurfacedRef, roots, seqOffset) []contexttrace.Event. Oneusedevent per (ref, evidence) where the normalised entry index is>= surfaced.Seq:read: Read/view of a path matching a surfaced doc name (MEMORY.md, SOUL.md, team doc names, distilled-discussions.md) or a ledger path undersessions/<ref>/data/plans/<slug>.requery: shell commandox agent team-ctx <slug>,ox session view <name>,ox conversation show <id>,ox plan show <slug>,ox murmur show <id>whose argument equals a surfaced ref (reuseextractCommand,firstQuotedOrToken).cited: an assistant entry contains the surfaced ref as a whole token (word boundary; min length 6, or any length for id-shaped refsOx[0-9A-Za-z]{4,},ses_,cnv_,rec_,pln_,/c/<id>). Never user/system entries, which contain the injected context itself.cited_commit: written bycmd/ox/hooks_post_commit.goat commit time: readgit log -1 --format=%B, match surfaced refs from the live trace, appendused{evidence:cited_commit, ref, commit:<sha>}. Works on both finalize paths.
- Idempotent: skip any
(type, ref, evidence, seq)already in the trace so daemon re-finalize or CLI retry never double-writes.
B. Self-report command (thin, JSON-first)
ox agent <id> context used <ref> [--why "<one line>"] [--ref-type <t>], ox agent <id> context used --none, and ox agent <id> context list --json (surfaced refs with their current evidence, titles, urls).
- New
cmd/ox/agent_context_used.go; dispatchcase "context":in thecmd/ox/agent.gosubcommand switch (~L705). Output viacli.PrintJSONTo; JSON carries aguidancefield (thin-relay rule). - Validates
<ref>againstcontextuse.Surfaced(events)(exact, case-insensitive basename, or unique prefix). Unknown ref returns an error JSON listing surfaced refs so the agent corrects rather than invents. - Writes
used{mechanism:self-report, evidence:reported, ref, ref_type, title, url, decision:<why, capped 200>, seq:state.EntryCount, surfaced_seq}.--nonewritesused{evidence:none}. Not recording → the per-agent cache fileusageTraceWriteralready uses. - Guidance injection: prime
<attribution>block (cmd/ox/agent_prime_xml.go~L250-296,internal/prime/attribution.go) replaces "report a score" framing with "record use at the moment it happens;ox session scoreremains an override";<murmur-context>gets one sentence; recall preamble header gets the command (still inside the 5-line budget);agent_query.goGuidance;ox briefguidanceTextstep (1) only fires whenrelevant.count == 0and says "if you already reported during work, do not report again". - End-of-work nudge: Stop hook stdout never reaches Claude Code, so follow the
emitUnsavedPlanNudgepattern incmd/ox/agent_hook.go handlePrompt: once per session, whensurfaced >= 1 && turns >= N && no used events && no score file, emit a<system-reminder>namingcontext used <ref> --why/context used --none. Stamp in the recording cache. internal/oxactivity/classify.go:{"agent","context","used"}→ "reported context use",KindWrite.
C. Judge (opt-in, last PR)
Second prompt through NewRunnerCompleter in the daemon finalize: input is surfaced refs + titles (refs only per ADR-027) and the transcript the summariser already has; output {ref, used, why} per ref, written as used{mechanism:judge, evidence:judged, decision:why}. Gated by OX_SUMMARY_JUDGE=on and a new recap.judge_context_use config (default off). Judged evidence never enters Derive unless attribution.allow_judged_evidence: true.
2. Data model
contexttrace.Event additive fields (internal/session/contexttrace/contexttrace.go)
goEventUsed EventType = "used" MechanismCitation Mechanism = "citation" MechanismJudge Mechanism = "judge" SourceLocalRecall SourceType = "local-recall" Evidence string `json:"evidence,omitempty"` // read|requery|cited|cited_commit|reported|none|judged SurfacedSeq int `json:"surfaced_seq,omitempty"` Commit string `json:"commit,omitempty"` // sha for cited_commit Title string `json:"title,omitempty"` // display title of the ref (discussion/plan/session/skill) URL string `json:"url,omitempty"` // sageox.ai link when one exists (/c/<id>, /plan/<id>) FromName string `json:"from_name,omitempty"` // whisper sender display name
Rules: every new writer sets Seq in the EntryCount frame; Decision carries --why (no new Why field); nothing new carries content (prompt text, murmur body, doc text). Legacy influenced with mechanism self-report or empty still counts as reported.
Metadata capture at the writers (ours)
| Writer | Adds |
|---|---|
cmd/ox/agent_prime_context_trace.go | Seq from recording state (0 if prime precedes it); title = doc basename |
cmd/ox/agent.go traceWhisperDelivery | from_name via the existing DisplayName helper used by the statusline; title = topic + first 60 chars |
cmd/ox/agent_hook_recall.go + agent_hook.go handlePrompt | resolve agentID before the recall block; new traceRecallDelivery writes one provided{source:local-recall, mechanism:injection, ref, ref_type, title, seq, inline_tokens} per hit (ref = session name / plan slug / murmur id; never the prompt). Remove "recall preamble" from usage.Unmetered |
cmd/ox/agent_query.go executeQuery | one provided{source:on-demand, mechanism:retrieval, ref:source_id, ref_type:doc_type, title, url, score, seq} per returned hit, cap 5 |
cmd/ox/usage_trace.go recordOxToolCall | for retrieval commands whose JSON output carries hits (ox conversation show/search, ox plan show/list, ox session view, ox kb describe, ox skills), parse ref/title/url from stdout into the invoked event (ref, title, url) with a size cap; fall back to command words |
Rollup: new pure package internal/session/contextuse
gotype SurfacedRef struct{ Ref, RefType, Via, Title, URL, FromName string; Seq int } type UseRef struct{ Ref, RefType, Evidence, Grade string; Mechanism contexttrace.Mechanism; Seq int; Decision string; MatchedSurfaced bool } type Rollup struct { Surfaced int `json:"surfaced"` UsedProvable int `json:"used_provable"` UsedReported int `json:"used_reported"` UsedJudged int `json:"used_judged,omitempty"` ReportedNone bool `json:"reported_none,omitempty"` ByEvidence map[string]int `json:"by_evidence"` // read|cited|reported|judged Refs []UseRef `json:"refs,omitempty"` // deduped per ref, strongest evidence wins, cap 20 DerivedCategory string `json:"derived_category"` DerivedReason string `json:"derived_reason,omitempty"` } func Surfaced(events []contexttrace.Event) []SurfacedRef func Build(events []contexttrace.Event, producedCommits int, allowJudged bool) Rollup
Dedup order per ref: cited_commit > cited > read > requery > reported > judged. usage.buildSurfaced is refactored to call contextuse.Surfaced so the two never disagree.
lfs.SessionMeta additive (internal/lfs/meta.go) and summary mirror
goContextUse *contextuse.Rollup `json:"context_use,omitempty"`
plus SessionMetaBuilder.ContextUse(r). Written at both finalize paths (cmd/ox/agent_session.go writeInitialSessionMeta, internal/daemon/agentwork/session_finalize.go meta RMW) and mirrored as an optional field in pkg/sessionsummary/types.go via cmd/ox/session_push_summary.go. No new file locations.
3. Derived attribution (display only)
internal/session/contextuse/derive.go: Derive(in DeriveInput) (category, reason string), categories are the existing session.ScoreCategory literals. First match wins:
significant: ≥2 distinct provable refs; or ≥1 provable ref withref_type ∈ {session, discussion, murmur, plan, kb}andProducedCommits ≥ 1; or anycited_commit.moderate: ≥1 provable ref; or ≥1reportedref with non-emptyDecisionandMatchedSurfaced.minor: only unmatched/why-less reported refs, or only judged refs.none: otherwise (including--none).
critical is never derived. Reason is deterministic and ref-listing: derived from context use: cited murmur Ox7f2a in commit 3e1c9d; read MEMORY.md (turn 14).
Not wired into the commit hook. It appears in the ox brief report as attribution {would_attribute bool, category, reason, threshold, manual_score?} (would_attribute = CategoryValue(category) >= attr.ScoreThreshold), in the meta rollup, and in ox session stop JSON. Flipping it live later is one call-site change in shouldAttributeCommit, after Ryan reviews the data.
Report fields the display session builds against (internal/usage/types.go, build.go)
surfaced[]gainsseq,title,url,from_name, andused {evidence: read|cited|reported|judged, seq, grade}(nil when not used).- Top-level
relevant {count, surfaced_count, by_evidence {read,cited,reported,judged}, items[{ref, ref_type, title, url, evidence, grade}]}. - Top-level
attribution {would_attribute, category, reason, threshold, manual_score}. used.statusaddsreported_none;used.self_report.commandbecomesox agent <id> context used <ref> --why "…".internal/knowledgeflow/knowledgeflow.go:gradeOfmapscitation→ provable;flowForrendersusedevents ("You used X (read, turn 14)" / "(you reported)").
4. PR sequence (after the ox brief rename merges)
PR1 — schema, ids, metadata, self-report, report fields (additive, no finalize changes)
internal/session/contexttrace/contexttrace.go(+tests),internal/session/contextuse/{surfaced.go,rollup.go}(new, +tests)cmd/ox/agent_context_used.go(new),cmd/ox/agent.go(dispatch,<entry id>, murmur-context sentence,from_name),internal/oxactivity/classify.gocmd/ox/agent_hook_recall.go,cmd/ox/agent_hook.go(recall trace, agentID plumbing, end-of-work nudge),cmd/ox/agent_prime_context_trace.go,cmd/ox/agent_query.go,cmd/ox/usage_trace.gointernal/usage/{types.go,build.go}data fields only (render.go/goldens are the display session's; keep goldens passing by not changing rendered lines),internal/knowledgeflow/knowledgeflow.go- Prime guidance:
internal/prime/attribution.go,cmd/ox/agent_prime_xml.go
Statusline integration (agreed with the display session): the display PR adds oxactivity.RecordInfluence(projectRoot, agentID, harnessSessionID, refType, ref) (dedup by refType+ref, file-locked, writes the statusline state file). Our two live writers call it, passing RecordingState.AgentSessionID: context used and the post-commit cited_commit detector. Finalize-time evidence (scan, judge) does not call it. Add the calls in PR2, after the helper is on main.
PR2 — deterministic evidence, rollup in meta, derived attribution (display)
internal/session/consultscan/consultscan.go(Entry.Type/Content,ScanUses, seq-frame offset, idempotent tagging),cmd/ox/session_consult_tagging.gocmd/ox/hooks_post_commit.go(cited_commit)internal/session/contextuse/derive.go(+tests),internal/config/attribution.go(AllowJudgedEvidence *bool, default false)internal/lfs/meta.go,pkg/sessionsummary/types.go,cmd/ox/agent_session.go,internal/daemon/agentwork/session_finalize.go,cmd/ox/session_push_summary.gotests/acceptance/features/session-recording/context-use.feature(content-only) + Go E2E
PR3 — daemon parity, judge, docs
session_finalize.go BuildPromptrunsconsultscanwithRoots{Ledger: payload.LedgerPath}(team-context root unavailable there; documented gap); judge prompt viajudge_adapter.go/summaryeval;recap.judge_context_useconfigdocs/adr/ADR-027-consultation-attribution-privacy.mdstatus note (usedevents follow the same four rules;--whyis the one free-text field, capped, reader-authored, redaction-scanned); rewritedocs/architecture/session-capture-components.md§F (describes a non-existenteidkey); regeneratedocs/reference(ox docs --output docs/reference)
5. Tests
- Table-driven, ≥85%:
contextusesurfaced/rollup/dedup/derive (empty→none; one read→moderate; reported with why+matched→moderate; reported without why→minor; two distinct reads→significant; session-ref read + commit→significant; doc read + commit→moderate; cited_commit→significant; judged only→minor;--nonethen read→moderate; same ref read+reported→moderate);consultscan.ScanUses(per evidence, word-boundary negatives, before-surfaced-seq negatives, header-line frame offset, idempotency);usagebuild fields;context usedref validation and error JSON; recall trace never contains the prompt string;<entry>carries and escapesid; metadata parsing caps. - E2E (red-first, per
.claude/rules/bdd-authoring.md): scratch repo, live recording whose trace has a whisperprovidedand aused{read}event;ox brief --jsonreportsrelevant.count == 1andattribution.would_attribute == true; red run removes theusedevent →relevant.count == 0,would_attribute == false. Second scenario: manualnonescore shown asmanual_scorewithwould_attributereflecting the manual value. Record both outputs in the PR body.
6. Team context signals (ox plan enrich)
- Collisions:
cmd/ox/agent_hook.go,cmd/ox/agent_session.go,internal/daemon/agentwork/session_finalize.goare in open PR #959 (lpavel);cmd/ox/agent_prime_xml.gois in open PR #804 (realtobyfu). Rebase after they merge or keep our edits to small, additive blocks in those files. - Expert routing: Galex owns
cmd/ox/agent_session_incremental.go; Madhur ownscmd/ox/agent_query.go; Ryan owns the attribution/prime files. Ryan must review anything touching data access ergonomics (ADR-027 status note, meta.json rollup).
7. Risks
- Seq frames (raw-line vs EntryCount): normalise in
ScanUses; test with a header line present. - Citation noise: generic doc names or short ids in unrelated text; mitigated by assistant-only scan, word boundaries, shape/length thresholds, after-surfaced-seq.
by_evidenceexposes the rate so it can be measured before anything feeds the trailer. - Privacy (ADR-027):
--whyis the only free text, capped; verifycontext-trace.jsonlgoes through the pre-push secret gate inpushLedger(theusage_trace.gocomment claims it does);ox brief --teamstays aggregate. - Double counting: legacy
influenced+ newused, multiple evidence per ref, daemon re-finalize; handled by per-ref dedup and writer idempotency, each covered by tests. - Daemon vs CLI finalize: PR2 writes the rollup from whatever the trace holds (self-report +
cited_commitwork on both); PR3 adds ledger-root scanning on the daemon path. - Two self-report paths coexist (usage-time batch vs moment-of-use command): guidance states which to use when, or agents report twice.
8. Verification
git pull, thengo test ./internal/session/... ./internal/usage/... ./internal/knowledgeflow/... ./cmd/ox/ -run 'Brief|Usage|ContextUse|ConsultScan|Whisper|Recall|PostCommit';go test -coveron new packages.make lint && make test.- Manual: start a recorded session, receive a whisper, run
ox agent <id> context used <entry id> --why "…", thenox brief --json→relevant.count == 1,surfaced[].usedset,attribution.category == moderate;ox agent <id> context list --jsonshows titles/urls for query hits. - Commit with a surfaced ref in the message →
used{cited_commit}appears in the trace; finalize on both paths and inspectmeta.jsoncontext_use. - Red/green E2E outputs captured in the PR2 description;
gh pr comment <n> --body "@greptileai"before merge.

