Skip to content

feat(application): structured graph reads - #29

Open
bweinzierl wants to merge 32 commits into
mainfrom
feat/structured-graph-reads
Open

bweinzierl wants to merge 32 commits into
mainfrom
feat/structured-graph-reads

Conversation

@bweinzierl

@bweinzierl bweinzierl commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

The application layer (pkg/application) now returns graph content as typed data instead of rendered text, so callers outside the agent shells, such as a web surface browsing a graph, can use entries and references directly. Plan: 20261128-231153-d-tac-1a6.

What changes

  • Show and Search return typed entries (pkg/application/types); two new reads: ListEntries (filters, paging, facet counts) and Changes (diff between two revisions).
  • Search and ListEntries share one filter, EntryFilter (IDs, types, kinds, layers, statuses, participants, creation dates).
  • Reads can pin an exact revision; a revision the store no longer holds fails with revision_unavailable.
  • One mapping in the model layer selects an entry's fields. MCP, engine injection and the CLI render their text from the typed entries with the existing presenters.
  • Fixed-value fields (type, kind, layer, status, ref kind, …) are named public types; status is one struct.
  • The procedure spec is typed (types.ProcedureSpec) from file to client: the model layer parses and writes it, the engine validates it, the presenters render it. A spec that does not decode is an entry warning and leaves Procedure empty. This departs from the plan, which kept the spec as YAML text; the decision is 20261206-131400-d-tac-utm.
  • Show reports each entry's total direct links per direction, also refs from the opening project to a dependency's entry, and pages through them (UpstreamPage, DownstreamPage); without a page every link is read.
  • Every read has an upper bound; larger requests fail with invalid_argument. A Changes diff above its bound fails with too_many_changes: reload through ListEntries, since retrying the same diff hits the same bound.
  • Vector search re-queries the index until filters cannot change the top N.
  • Search filters take full names; the MCP adapter resolves the abbreviations agents pass.
  • sdd summarize and Application.ReplaceSummary patch the summary key into the entry file instead of rewriting it, so unknown keys, comments and a procedure spec that does not decode survive.

Text output changes

  • Attachments show their name instead of a storage path over MCP; the CLI keeps the path below the graph directory.
  • show of a procedure renders its spec from the typed form: params and state in alphabetical order, maps and lists holding only scalars in flow style (e.g. a transition as {when: …, to: …}), no YAML comments. The spec's content is unchanged for all shipped procedures.
  • A dependency's entry lists the project's entries that cite it below it.

Not in this PR

  • CLI read commands still load the graph themselves instead of going through the application layer (gap 20261201-145640-s-tac-evo).
  • Filters are applied after the vector index ranks; passing them into the index is open.
  • Revisions are pinned for the local graph only; dependencies read at their current authority.

Confidence Score: 2/5 Tier: plusRetriggerView in Greptile

Do not merge until procedure loading stops changing saved values and summary edits cannot erase workflow fields.

Findings

  1. P1 Returned procedures share writable values ▶
  2. P1 Summary edits erase workflow fields ▶
Fix with agent prompt
### Issue 1
internal/model/structured.go:202-205
`cloneProcedureSpec` copies the outer maps but still shares each mutable `Default` value and nested `Args` values with the snapshot. Changing an item in a returned list default therefore changes the stored procedure too. Since stores may reuse snapshots, later reads and workflow loads can see the caller's edits under the same revision. Concurrent edits can also race with reads.

Recursively copy these values before returning them.

### Issue 2
internal/model/entry.go:581-585
A procedure with one bad key now loads with `ProcedureSpec` unset, losing all its machine fields in the model. An unrelated `sdd summarize <id> --text ...` then calls `FormatFrontmatter` and overwrites the file without `params`, `state`, `steps`, or `framing`. Previously the raw YAML survived that rewrite.

Retain the raw fields when decoding fails, or refuse to rewrite the entry.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR returns typed graph entries from Show and Search, adds paged ListEntries and revision-based Changes, and moves text rendering to callers.

  • Graph reads return typed entries that callers can browse or render as text.
  • Callers can page through entries and compare graph revisions.
  • Vector search widens its index query until filters leave a settled top-N list.
  • Procedure specs now use typed fields from storage through rendering.

Reviews (3) · Last reviewed commit: "refactor(application): type the procedur..." · Reviewed by Greptile

bweinzierl and others added 4 commits November 23, 2026 00:31
SDD-Mutation: v1:320fccf60db8bf7a47dd380b2723a59b163648e3f523445d55beaab0aff0ec30
SDD-Mutation: v1:8eef1b129b6bef65346f6edc1402a008fd1639f8af376d874b189cd7d35966ae
SDD-Mutation: v1:6b0e6386a7ac9d86a2a3c2bc794880eb3efd17e356781de87b290bb17b0938ea
Show and Search return typed results beside the rendered text;
ListEntries filters, pages and counts facets; Changes diffs two
revisions. Plan: 20261123-003335-d-tac-g4r.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@bweinzierl bweinzierl self-assigned this Nov 24, 2026
Show and Search return typed entries only; MCP, engine injection and the
CLI render text from them through one mapping. Fixed-value fields are
public named types, status is one struct and topics are paths.
Record each entry's owning graph where it is resolved, bound every read,
report only unknown revisions as revision_unavailable, widen vector search
until filtered rankings are final, keep attachment names below the entry
directory, and take full filter names in Search with abbreviations resolved
in the MCP adapter.
SDD-Mutation: v1:4a02f2308a9947b1c0408fedb397189bb0321d7c3f4dfd455298c35f8efd7b9b
@bweinzierl bweinzierl changed the title Feat/structured graph reads feat(application): structured graph reads Nov 28, 2026
SDD-Mutation: v1:fa8fe8427e385509dd0454fdaaa02917884f1b8d4acd79fa28ad3200bd4c7cbd
SDD-Mutation: v1:ff7405926458aa81523140d76a2e1b2a93f5f5943d2aa7a6d915ee52f5fd0798
@bweinzierl
bweinzierl marked this pull request as ready for review November 28, 2026 22:25
Comment thread pkg/application/vector_search.go Resolved
Comment thread internal/model/structured.go Resolved
Comment thread internal/query/show.go Resolved
Comment thread internal/query/search.go Resolved
Comment thread pkg/application/graph_reads.go Resolved
Comment on lines +202 to +205
func cloneProcedureSpec(s types.ProcedureSpec) types.ProcedureSpec {
s.Params = maps.Clone(s.Params)
s.State = maps.Clone(s.State)
s.Framing = cloneInjects(s.Framing)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Returned procedures share writable values

cloneProcedureSpec copies the outer maps but still shares each mutable Default value and nested Args values with the snapshot. Changing an item in a returned list default therefore changes the stored procedure too. Since stores may reuse snapshots, later reads and workflow loads can see the caller's edits under the same revision. Concurrent edits can also race with reads.

Recursively copy these values before returning them.

Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/model/structured.go
Line: 202-205

Comment:
**Returned procedures share writable values**

`cloneProcedureSpec` copies the outer maps but still shares each mutable `Default` value and nested `Args` values with the snapshot. Changing an item in a returned list default therefore changes the stored procedure too. Since stores may reuse snapshots, later reads and workflow loads can see the caller's edits under the same revision. Concurrent edits can also race with reads.

Recursively copy these values before returning them.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. cloneProcedureSpec now deep-copies the decoded literals in Default and inject Args (lists and maps of them). TestStructuredEntryCopiesSpecLiterals edits nested values in a returned spec and reads the entry again. Fixed in d08900c.

Comment thread internal/model/entry.go
Comment on lines +581 to +585
spec, err := decodeProcedureSpec(&fm.Params, &fm.State, &fm.Steps, &fm.Framing, fm.ServeBudget)
if err != nil {
e.Warnings = append(e.Warnings, Warning{Field: ProcedureSpecWarningField, Message: err.Error()})
} else {
e.ProcedureSpec = spec

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Summary edits erase workflow fields

A procedure with one bad key now loads with ProcedureSpec unset, losing all its machine fields in the model. An unrelated sdd summarize <id> --text ... then calls FormatFrontmatter and overwrites the file without params, state, steps, or framing. Previously the raw YAML survived that rewrite.

Retain the raw fields when decoding fails, or refuse to rewrite the entry.

Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/model/entry.go
Line: 581-585

Comment:
**Summary edits erase workflow fields**

A procedure with one bad key now loads with `ProcedureSpec` unset, losing all its machine fields in the model. An unrelated `sdd summarize <id> --text ...` then calls `FormatFrontmatter` and overwrites the file without `params`, `state`, `steps`, or `framing`. Previously the raw YAML survived that rewrite.

Retain the raw fields when decoding fails, or refuse to rewrite the entry.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We must implement proper YAML patching for the summary field so the structure is preserved. I think we already solved that for the config.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Agreed—patching just the summary field is the better fix, and the repo already has YAML-patching helpers. But they are not used by summary writes: both the generated and --text paths in internal/handlers/handler_summarize.go still call model.FormatFrontmatter(entry), which rebuilds the frontmatter from the parsed model. If procedure decoding fails, those fields are absent from that model and can still be dropped. So the config patching work gives us a pattern to reuse, but this finding remains until the summary paths patch the existing frontmatter instead.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. sdd summarize now patches the summary key into the existing frontmatter (model.SetEntryField over the YAML patch helpers the config already uses) instead of rewriting the file with FormatFrontmatter. Unknown keys, a procedure spec that does not decode, and comments stay as they are; TestSummarize_ExplicitText_KeepsWhatTheModelDoesNotCarry covers a procedure with an unknown step key. Over the 1498 entries in this repository's graph, patching each summary to its own value leaves every file byte-identical. rewrite and lint --fix still rewrite whole files; both are slated for removal. Fixed in a3b18fe.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in a3b18fe: summary writes go through the YAML patch helpers from the config work. patchYAML now takes the indent, so entry files keep their four spaces.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Follow-up: Application.ReplaceSummary rewrote the whole file the same way and was missed in a3b18fe. It now patches the summary key through model.SetEntryField too; pkg/application/replace_summary_test.go covers a procedure whose spec does not decode. Fixed in a74b4bc.

@greptile-apps

greptile-apps Bot commented Dec 4, 2026

Copy link
Copy Markdown

Comments Outside Diff

These findings could not be posted inline.

  • P1 Loading removes procedure caps internal/engine/spec.go:216 ▶

    injectCall now receives the stored Args map directly, then deletes maxBytes from it. For a procedure using the supported legacy args.maxBytes spelling, the first ParseSpec keeps the cap, but another parse of the same entry loses it and falls back to the registered cap. Shared reads can also race with this deletion.

    Copy Args before removing the legacy key.

Comment thread internal/model/show_tree.go Outdated
}
key := owner.nodeKeyFor(e)
upChildren := upstreamChildren(e)
downChildren := owner.downstreamChildren(e.ID)

@hlubek hlubek Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex (GPT-6.2-Astra) authored this review. The findings and recommendations are the model’s own.

Include backlinks from the project that opened the graph. In an application test, a local plan referenced a gap in a dependency. Show(plan, UpDepth: 1) returned the gap. Opening that gap through the same project with DownDepth: 1 returned DownstreamTotal == 0. The owner graph has no index of the local plan’s outgoing edge, so navigation loses the edge when the reader follows it in reverse.

Please include incoming edges from the caller’s readable graph in both the downstream items and the total. The two reads above would make a regression test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid, reproduced with your two reads: the gap's downstream was empty with a total of 0. Each graph now also indexes its refs to other repos' entries, and a dependency's entry gets, besides its own graph's downstream edges, the refs from the graph the read opened, in the items, the truncated refs and DownstreamTotal. The chain continues in the opening graph from the citing entry. TestShowListsRefsFromTheOpeningProject runs your two reads plus the unexpanded total; TestBuildShowTree_DependencyEntryListsRefsFromTheOpeningGraph covers the model side. CLI and local MCP show the same backlinks. Fixed in c07546c.

Comment thread pkg/application/application.go Outdated
for _, entry := range searchResult.Entries {
if entry.Entry != nil {
search.EntryIDs = append(search.EntryIDs, entry.DisplayID())
search.Hits = append(search.Hits, entry.Structured())

@hlubek hlubek Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex (GPT-6.2-Astra) authored this review. The findings and recommendations are the model’s own.

Deduplicate embedded search hits before taking the final limit. I reproduced this with text search over one project and one dependency. The same embedded procedure appeared twice with the same Hits[i].Entry.DisplayID, while the second EntryIDs[i] had the dependency prefix. A caller keying nodes by display ID loses a ranked slot, and a caller using the parallel ID list sees a different identity.

Use the structured display identity for deduplication and for EntryIDs. A cross-repo test should assert unique hit IDs, agreement between both fields, and that a duplicate cannot displace the next eligible hit.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid, reproduced: with one dependency, every embedded procedure the term matched came back twice, and EntryIDs carried the dependency prefix while Hits did not. Search now builds the structured hits in rank order, skips a display ID already listed, and stops at the limit, so a copy cannot take a slot; EntryIDs comes from Hits[i].Entry.DisplayID. TestSearchAcrossReposListsAnEmbeddedEntryOnce asserts unique IDs, agreement of both fields, and that the top two equal the first two of the full result. Fixed in 23382f6.

Comment thread pkg/application/read_limits.go Outdated
if err := atMost("up depth", request.UpDepth, MaxShowDepth); err != nil {
return err
}
return atMost("down depth", request.DownDepth, MaxShowDepth)

@hlubek hlubek Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex (GPT-6.2-Astra) authored this review. The findings and recommendations are the model’s own.

Bound the number of links a Show response can return. One requested ID at depth one passes these checks regardless of how many entries cite it. With the default budget every neighbour is returned. Even MaxChildren: 1 can move every remaining edge into DownstreamTruncated, so the response still grows with the degree of the node.

For an explorer, keep the exact total and provide a bounded way to request more links. Please cover a node whose degree exceeds the cap and assert a bound across both expanded and truncated items.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Partly addressed. ShowRequest gained UpstreamPage and DownstreamPage (types.LinkPage{Offset, Limit}): the tree expands only the selected direct links of each requested entry, in tree order, while UpstreamTotal/DownstreamTotal stay exact; a limit above MaxShowLinkPage (200) or a negative value is rejected. Links outside the page do not land in the truncated lists, so an explorer reads a hub in bounded pages. The zero value still reads every link, so explicit pulls from the CLI and MCP arrive complete (d-tac-rzi). TestShowPagesThroughDirectLinks pages through three links one at a time and expects the unpaged order; TestBuildShowTreeBounded_LinkPages covers first, middle, short last, past-the-end and offset-only pages.

We keep node-level truncation as it is: a node at the depth boundary still names its own unexpanded links. That bounds a page by page size times the neighbours' degree rather than by a constant, which the page size keeps in check (in this repository's graph of about 1500 entries, 99% of entries have at most 21 inbound refs). A count-only variant would mean two kinds of truncation in the application surface, and an explorer gets the count as the list's length. Implemented in 59e2980.

Comment thread pkg/application/read_limits.go Outdated
}

func checkChangesSize(diff model.GraphDiff) error {
if n := len(diff.Added) + len(diff.StatusChanged) + len(diff.SummaryChanged); n > MaxChanges {

@hlubek hlubek Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex (GPT-6.2-Astra) authored this review. The findings and recommendations are the model’s own.

Count nested Added[].RefIDs in the diff budget. The new guard counts one added entry as one item regardless of how many reference IDs it returns. A diff containing only one new entry can therefore exceed MaxChanges in returned IDs and still succeed. Please include nested reference IDs in the size check and cover the single-addition case. The existing too_many_changes response already gives callers a way to recover.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid. checkChangesSize now adds the RefIDs of each added entry; the bound test gained a revision with one added entry citing MaxChanges IDs. Fixed in 23382f6.

Comment thread internal/query/search.go
// Structured maps the hit to its exported form.
func (e SearchEntry) Structured() types.SearchHit {
hit := types.SearchHit{Entry: e.Owner.StructuredEntry(e.Entry, e.RepoID, false), Score: e.Score}
for _, c := range e.Citations {

@hlubek hlubek Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Codex (GPT-6.2-Astra) authored this review. The findings and recommendations are the model’s own.

Honor MaxCitations when merging hybrid search hits. With a term and a phrase matching the same entry, Limit: 1, MaxCitations: 1 returned three citations, two identical. The duplicates already exist when this mapping runs. In pkg/application/vector_search.go, hybridResult copies the first hit with its citations and then appends that same slice’s contents again. It also appends citations from the other search mode without applying the per-hit cap.

Please fix fusion and add an application-level test for a hit present in both modes. With a cap of one it should return one citation.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Valid, reproduced: three citations, two identical. hybridResult now starts a merged row without citations, then drops citations of the same chunk and caps at MaxCitations, text-mode citations first since the two modes' scores are not comparable. TestHybridSearchHonorsMaxCitations covers a hit present in both modes with a cap of one. Fixed in 23382f6.

@hlubek

hlubek commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex (GPT-6.2-Astra) authored this review. The findings and recommendations are the model’s own.

Architecture and plan fit

I support the four application reads and the typed procedure spec. Show, ListEntries, Search, and Changes give an explorer the pieces it needs to open a node, page through a pinned revision, rank matches, and refresh after a change. The model owns identity, status, and reference semantics. The CLI and MCP can render the same data. The shared EntryFilter is worth keeping.

Keep the procedure spec typed. Callers can inspect params, state, steps, and framing through the same Go types the engine reads. Returning YAML would make each structured consumer parse the workflow declaration and track its schema separately. The plan’s YAML carve-out was a mistake. Please update the PR description to reflect the decision. There is also a separate text-compatibility decision to record. Plain show output changed for all 10 procedures I compared on the same graph. For example, a transition that occupied two lines now renders as a flow mapping. If that formatting change is intentional, please include it among the documented output changes.

I tested the consumer against 681eaa29. Moving its list and search filters under EntryFilter was sufficient for its GraphQL integration suite to pass, including navigation, search, and change subscriptions. On upgrade, consumers should also handle too_many_changes by reloading the listing. Retrying the same diff from the same revision will hit the same limit.

The full SDD test suite passed, including the example module. I’d keep the architectural direction and address the open correctness findings before merging. CLI acquisition through the application and per-dependency revision pinning can stay separate follow-ups.

@bweinzierl

Copy link
Copy Markdown
Collaborator Author

Re the outside-diff finding Loading removes procedure caps (internal/engine/spec.go): valid. injectCall now folds the legacy args.maxBytes on a copy of Args, so the entry keeps it. TestParseSpec_LegacyCapSurvivesReparse parses the same entry twice and expects the cap both times. Fixed in d08900c.

@bweinzierl

Copy link
Copy Markdown
Collaborator Author

Re the architecture review: the description now records the typed procedure spec (the YAML carve-out is gone) and the text output changes, including the procedure rendering in flow style with alphabetical params/state, which is intentional. It also notes that a too_many_changes diff is recovered by reloading through ListEntries. All five inline findings are answered; CLI acquisition through the application and per-dependency revision pinning stay follow-ups.

SDD-Mutation: v1:dc7d3e7d5ba2c725904fb1fe9560d981d6e1238dd9bd81c6919eb9802b52e3db
SDD-Mutation: v1:14ad2796a118ee1d96c2d5ef05944d4264fd1f530c70bc2cfe7ceec1bc25a947
SDD-Mutation: v1:7fbce1424c76a5197e2a5617e60b6212d51e9bee553f69b6ecf19e5d1f450cb2
SDD-Mutation: v1:d2789484a1ead8101149b47af0689820f02562616a922a269379c0c2be710100
SDD-Mutation: v1:a81ebb9281798e90cb262ba476c3d7098b3d4ef34fc96b973e58196b7381d4bc
SDD-Mutation: v1:f93d9f089c5387063e0c1e87e9cfff261825521586aa6c8908bf0d00f120be1a
SDD-Mutation: v1:7db27266fdc713fd42a635ee542cc8b04e1b2dbaf0e231032368815c6f659601

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants