Skip to content

fix: address application architecture review findings - #562

Merged
stefan-ernst merged 12 commits into
mainfrom
fix/architecture-review-findings
Nov 24, 2026
Merged

stefan-ernst merged 12 commits into
mainfrom
fix/architecture-review-findings

Conversation

@stefan-ernst

Copy link
Copy Markdown
Contributor

Summary

Addresses the highest-value findings from the application architecture review (docs/application-architecture-review.md), following its suggested sequence: fix the SCM event metadata and the agent tool write paths first, then the workspace cache invalidation and the architecture guards.

1. SCM milestone attachment keeps its automation chain

ItemUpdateApplicationService.AddMilestoneWithContext forwarded the action context to the post-commit emitter but passed only item/user IDs into the transactional update. The committed item fact therefore fell back to source application with no chain, depth, or source application, so downstream automation could not identify the originating chain.

The metadata is now built once from the command context and passed into AddMilestone, matching normal updates. A regression test asserts the committed fact (not just the emitter event) carries the chain, depth, and source.

2. Agent tools write through the shared application services

create_item, update_item, and log_time implemented part of the operation they invoked: the first two called the low-level create/update services, and log_time wrote the repository directly. Agent writes skipped description-mention processing, hierarchy cache invalidation, the created/updated event pipeline, and the worklog description policy, so the result depended on how the write entered the system.

ItemApplicationService and TimeWorklogService are now injected into the tool environment and used by those tools. Tool scopes, key resolution, and output formatting stay in the adapter. Agent actor/source/run provenance is passed through explicitly (UpdateWithMetadata) so it is not replaced by the human-only application default. Embedders that do not wire the shared services fall back to a local pipeline, matching the previous behavior.

3. Frontend invalidates the assigned workspace's effective configuration

The assignment client writes /workspaces/{id}/configuration-set, but the invalidation table only matched plural configuration-sets or an exact workspace URL. Neither matched, so the independent effective-screen cache could keep serving the previous configuration without a request after a successful assignment.

The singular endpoint now matches and drops only that workspace's cached effective configurations, discarding in-flight pre-change reads so a slow response cannot repopulate the cache.

4. Architecture guards

  • The handler DB guard scanned legacy handlers and v1 only; it now includes internal/restapi/v2 and allowlists the three existing database/sql imports.
  • The layering guard matched an import path with a closing quote, so the cacheutil leaf rule against windshift/internal missed subpackage imports. It now matches the forbidden package exactly or any subpackage of it.

Not addressed in this change

  • Importer hierarchy rules (finding 3): converging Plane/Jira historical-import writes on a transaction-scoped hierarchy operation and moving Jira job phase ownership out of the HTTP handler is a larger change. It should be done with importer-specific tests and is left for a follow-up.
  • Structural risks table: constructing one configured set of item commands in server wiring, binding the SLA observer to the recorder, and removing the v2-to-legacy-handler dependency are lifecycle/wiring changes with a wider blast radius. The first fixes in the review do not require them.

Tests

  • internal/services: full package (includes the new committed-fact regression test).
  • internal/aitools, internal/scm, internal/mcp, internal/handlers: full packages.
  • frontend: referenceDataInvalidation.test.js (new per-workspace invalidation case), plus biome check/lint and svelte-check on the changed files.
  • scripts/check-layering.sh and scripts/check-handler-db-access.sh pass; the layering prefix match was verified with a temporary subpackage import.

Test changes live in the companion core-tests-internal branch fix/architecture-review-findings.

@github-actions

Copy link
Copy Markdown

Size Change: 0 B 🆕

Total Size: 0 B

compressed-size-action

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

I’d address the Standard Agent wiring and the cache invalidation before merging. I found five issues on d3e7b69:

  1. P1 — Standard Agent writes still skip side effects. Dispatcher.execute constructs an aitools.Env without ItemApplication. A description edit from chat processes mentions; the same update_item from a Standard Agent falls back to a service without the mention processor, event emitter, or hierarchy cache. Please inject the shared services before Resume can start a queued run, and cover a write through the dispatcher.
  2. P2 — Invalidating workspace A discards valid in-flight reads for B. invalidateScreenConfigsFor bumps the global epoch. B’s response still resolves, but it never reaches screenConfigs[B]; the backlog reads that map directly to decide whether to show story points. A two-workspace regression test should assert that after invalidating A, B’s pending response is cached and A’s pre-change response is not.
  3. P2 — Assignment leaves the collection priority picker stale. The assignment rule clears screen configs, but the picker loads from collectionEditorOptions, which caches priorities for five minutes. Opening the picker before and after reassignment can still show the old set’s options. Please invalidate the workspace’s priority options and prevent a pending old load from restoring them.
  4. P2 — log_time turns storage failures into successful MCP calls. The catch-all error branch returns a payload with a nil Go error. A failed insert used to set MCP’s IsError; now a client checking that flag sees success. Handle known input errors in the payload and return nil, err for unexpected service failures.
  5. P3 — log_time drops sanitization warnings. The success response returns the stored description but omits result.Warnings, so a caller isn’t told when its description was shortened. An optional warnings field would match HTTP behavior.

The committed-fact milestone regression test, MCP log-and-list test, focused aitools tests, and both architecture guards passed locally. The Standard Agent test filter matched no tests.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Two additional P2 cache issues remain in the assignment rule, including with the local follow-up that invalidates priority options:

  1. Direct assignment leaves workflow statuses and item types stale. Assign a compatible set with a new status or item type, then return to the same workspace board. The board reads workspaceDataStore.statuses and .itemTypes, which still contain the previous bootstrap values. The collection editor also caches statuses independently. Refresh the active workspace’s scoped catalogs and invalidate its status options; a scoped refresh matters because _fetchField("itemTypes") currently reads the global catalog.
  2. Assignment through the migration assistant skips priority-option invalidation. When migration is required, the assistant posts /configuration-sets/execute-comprehensive-migration and deliberately skips the assignment PUT. The plural endpoint clears screen configs only. A priority picker opened before migration can still offer the old set’s priorities for five minutes. Invalidate the affected workspace IDs on migration success as well, including pending reads. A test that primes the picker and completes the migration path would catch this.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Addressed all five in 3ba61656 (core) and 13f586b7 (core-tests).

  1. P1 — Standard Agent writes. Options now carries ItemApplication and TimeWorklogService; both aitools.Env constructions pass them through. The dispatcher is now constructed and Resumed after itemApplication exists (moved in initialize), so a queued run cannot start before the services are installed. Added TestDispatcherItemWriteUsesInjectedApplicationService, which drives a real update_item through the dispatcher and asserts the injected update pipeline emitted; it fails when the Env wiring is removed.
  2. P2 — Cross-workspace invalidation. invalidateScreenConfigsFor no longer bumps the global epoch; it tracks a per-workspace epoch and clears only that workspace's keys/pending entries. Added keeps another workspace pending read cacheable when one workspace is invalidated and drops only the assigned workspace cached configurations.
  3. P2 — Priority picker. The assignment rule now also invalidates the workspace's priorities collection-editor options. collectionEditorOptions.invalidate bumps a per-key generation and drops the pending entry, so a stale in-flight load cannot restore the old options. Added tests for the stale-load case and for one family not disturbing another.
  4. P2 — log_time storage failures. Extracted worklogServiceError: known input errors return a payload, everything else returns nil, err so MCP marks the call failed. Unit-tested (TestWorklogServiceErrorKeepsStorageFailuresAsGoErrors).
  5. P3 — log_time warnings. The response now carries warnings from the worklog service. TestTimeWorklogServiceSanitizesDescriptionAndWarns proves the shared service sanitizes and reports.

Tests run against this branch: full internal/services, internal/aitools, internal/standardagent, internal/scm, internal/mcp, internal/handlers, plus the three frontend store suites (65 tests). Both architecture guards pass.

One note on test placement: I could not add the MCP log_time warning assertion to tests/mcp_time_test.go, because on origin/main that package references StartIsolatedTestServer, which currently exists only in the local working tree — so the committed tests package does not build. I covered the warning path at the service level instead and left tests/mcp_time_test.go untouched.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Re-reviewed 3ba61656 with companion tests at 13f586b7. The five findings in my first review are addressed. I’d still request changes on three points:

  1. P2 — create_item can report failure after committing the item. I reproduced this on the PR head: a test canceled the caller context from EmitItemCreated, then queried the database after the tool returned. The result was {"error":"create failed: load labels for items: context canceled"}, but one item was committed. Create enriches the response after commit, and the tool returns before AuditWrite. A retry can create a duplicate. Please preserve and audit the committed ID when response enrichment fails; the previous tool could return just the ID. A regression test can use the same post-commit cancellation and assert the result identifies the stored item.
  2. P2 — Direct assignment still leaves scoped statuses and item types stale. The assignment rule invalidates screens and editor priorities, but the active workspace snapshot and the editor’s status options retain the old catalogs. For example, opening the create dialog without leaving the workspace can read the old item types for its parent picker. Refresh the assigned workspace’s scoped catalogs and invalidate its status options.
  3. P2 — Migration-based assignment still skips picker invalidation. The migration assistant deliberately skips the assignment PUT because the migration POST already reassigned the workspace. That POST only clears screen configs, so previously loaded priority options can remain available for five minutes. Apply the same per-workspace invalidation after either path succeeds, including for pending reads.

Verification: all 65 tests in the three affected frontend store suites passed, as did the focused Standard Agent and worklog tests and both architecture guards. The post-commit case above was checked separately in a temporary test; no production or companion test files were changed.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Addressed all three in 2d6dfbca (core) and 4200a42b (core-tests).

  1. P2 — create_item post-commit failure. ItemApplicationService.Create now returns the committed item alongside the enrichment/render error, and the tool audits as soon as the row exists and reports the stored item summary instead of a retryable create failure. Added TestCreateItemToolReportsCommittedItemWhenEnrichmentFails, which cancels the context from the created emitter, asserts the tool returns an itemSummaryDTO with a stored ID, and counts exactly one row. It reproduces your exact failure (map[string]string{"error":"create failed: load labels for items: context canceled"}) without the fix.
  2. P2 — Direct assignment scoped catalogs. The assignment rule now also re-fetches the assigned workspace's bootstrap catalogs (workspaceDataStore.invalidateWorkspaceCatalogs, which is the only workspace-scoped source for item types) and invalidates the editor's statuses alongside priorities. The editor rule field now accepts a list. Covered by the updated invalidation test and invalidateWorkspaceConfiguration.
  3. P2 — Migration-based assignment. MigrationAssistant now calls the same per-workspace invalidation for every affected_workspaces entry after a successful migration (either the comprehensive or single-set path), including pending reads. Added a MigrationAssistant.test.js case that fails when the invalidation call is removed.

Verification: full internal/services, internal/aitools, internal/standardagent, internal/scm, internal/mcp, internal/handlers suites; the four affected frontend suites (69 tests) including the two new regression tests. Both architecture guards pass, and the frontend silent-error/typecheck/inline-style guards pass.

@stefan-ernst

stefan-ernst commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Re-reviewed 2d6dfbca with companion tests at 4200a42b. I’d request changes, but I’m revising the implementation advice: please replace the special cases rather than adding another fallback or cache counter. Two behaviors should drive the design:

  1. A committed create returns its ID. I forced the first detail read after commit to fail. The tool reported create failed, but one row existed; retrying could create a duplicate. Make the ID already returned by the transaction the shared create command’s success result. The tool can audit that ID and include a summary when available. Keep permissions and event handling in the shared service. Remove the tool’s need to interpret “item plus error”; don’t add a second recovery branch around this earlier read.
  2. Reassignment reloads the workspace, and an old response cannot undo it. I held a pre-assignment bootstrap response, let the assignment refresh install status 20, then released the old response. The store reverted to status 10. Have direct assignment and successful migration call one configuration-change operation: reset the relevant workspace and editor caches, then reload the active scope using the existing reset/initialization lifecycle that already rejects superseded reads. Replace the assignment-specific field rules and refresh path this makes redundant. A few extra reads after a rare admin change are preferable to another generation counter.

Please keep regression coverage at those two boundaries: fail a detail read after a real commit and assert the tool returns the stored ID; settle an old refresh last and assert the new catalogs remain. All 69 committed frontend tests in the four affected suites and the three focused Go regressions passed; the two additional cases above failed.

Separately, the Go Vulnerability Check flagged GO-2026-6974 on this revision.

@stefan-ernst
stefan-ernst force-pushed the fix/architecture-review-findings branch from 2d6dfbc to 438138c Compare November 24, 2026 08:50
@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Revised both designs in 438138cd (core) and cd5873ae (core-tests), and rebased onto main (which now carries the GO-2026-6974 OpenTelemetry bump).

  1. A committed create returns its ID. ItemCreateResult now carries the transaction's ID; the post-commit FindByIDWithDetails only decorates the response and its failure is logged, not returned. ItemApplicationService.Create returns the committed identity when the detail read is unavailable, so the tool has no "item plus error" branch — it audits created.ID and returns the summary. TestCreateItemToolReturnsCommittedIDWhenDetailReadFails forces the detail read to fail with a DB wrapper and asserts the tool returns the stored ID and exactly one row; it fails on the previous revision with create failed: failed to find item with details.
  2. Reassignment reloads the workspace. Direct assignment and successful migration now call one invalidateWorkspaceConfiguration → workspaceDataStore.reloadForConfigurationChange, which resets the active scope and reloads it through the existing reset()/initialize() lifecycle. That advances the generation, so a bootstrap read that started before the change is discarded. I removed the per-workspace screen-config epoch, the per-key editor generation counter, the workspaceCatalogs/screenConfigsForWorkspace/editor: [...] rule fields, and the invalidateScreenConfigsFor/invalidateWorkspaceCatalogs methods; the assignment rule is now a single configurationChanged flag and editor caches use their existing reset(). reloads the active workspace and rejects a bootstrap read from before the change settles an old refresh last and asserts the new catalogs remain; it fails with the previous _fetchAll-based refresh.

Verification: full internal/services, internal/aitools, internal/standardagent, internal/scm, internal/mcp, internal/handlers; the four affected frontend suites (67 tests); both architecture guards and the frontend biome/silent-error/inline-style guards.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Re-reviewed 438138cd with companion tests at cd5873ae. The workspace reset/reinitialize path fixes the stale-refresh case without another cache counter. All 67 tests in the four affected frontend suites passed. The agent tool now returns the committed ID in its detail-read regression test. I’d still request changes on two backend issues.

  1. P1 — Other create callers can panic after a successful commit. The shared create now returns success with result.ID set and result.Item == nil. I applied the same detail-read fault to the existing asset-action test: item 1 committed, then executeCreateItem panicked at result.Item.ID. The bundle importer makes the same dereference, and the v1 create handler passes nil to maskProjectNamesOne, which dereferences it. The early return also skips the item.created webhook. Finish the contract change at the source: ID-only consumers should use result.ID; callers that need a row or an event should get a guaranteed creation snapshot. The transaction already builds one. That avoids independent nil fallbacks and a synthetic item with an empty title and workspace 0.
  2. P1 — The enrichment-error path discards permission masking. ItemApplicationService.Create enriches a copy, but returns the original joined row on error. Enrichment masks project names and related-item metadata before loading labels and milestones. A failure in either later read discards those redactions, and v2 serializes the original row. Keep a single caller-facing copy and return that sanitized copy; don’t use the raw repository row as the error response.

The asset-action panic was reproduced in an isolated test; the other affected callers and the masking issue were verified by source tracing. The committed agent-create and Standard Agent regression tests passed.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Finished the contract at the source in 63d9ef70 (core) and e78f9358 (core-tests).

  1. The create command returns a guaranteed snapshot. The creation transaction already builds the row in recordCreation/eventItem, so itemCreation now keeps it and createItemWithSnapshot returns it. ItemCreateResult.Item is therefore always the committed row (the joined read only replaces it when it succeeds), and ID is always set. The item.created emitter now fires with the snapshot when the joined read fails, so the webhook is no longer skipped. ID-only callers use result.ID (asset_action_service, workspace_bundle_import); callers that need a row (v1 handler, v2) get the snapshot. No synthetic item and no independent nil fallbacks. TestAssetActionCreateItemReturnsCommittedIDWhenDetailReadFails reproduces your asset-action case with the same detail-read fault and asserts no panic plus the committed ID; the existing tool regression still passes.
  2. Enrichment failure keeps the sanitized copy. ItemApplicationService.Create now always returns &items[0], the copy enrich mutates. Since project-name and related-item masking run before the label/milestone reads, a failure in either later read no longer discards those redactions with the raw repository row.

Verification: full internal/services, internal/aitools, internal/standardagent, internal/scm, internal/mcp, internal/handlers suites. Both architecture guards pass. Go Vulnerability Check is green after the rebase.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Re-reviewed 63d9ef70 with companion tests at e78f9358. Both previous P1s are resolved. The asset-action and agent-tool regressions pass, the item.created webhook is dispatched once when the joined read fails, and a separate test confirmed that a subsequent label-read failure preserves the masked project name. The workspace reload fix is unchanged. I found one narrower issue I’d fix before merging.

P2 — A successful v1 create can return a fabricated item key. With only the post-commit detail read forced to fail, the stored item was TEST-1 but the production v1 response mapper returned key: "-1". The creation snapshot has WorkspaceItemNumber but no WorkspaceKey. Both the v1 mapper and the creation notification unconditionally format the two fields. The numeric ID is correct, but the published key can’t identify the item.

Carry the workspace key into the shared creation snapshot. The existing workspace validation already reads the workspace, so it can return the key instead of just checking existence. That keeps one source of identity for the response and notification without a second post-commit lookup or per-caller fallbacks. Extend the detail-read-failure regression to assert the exact display key as well as the numeric ID.

@stefan-ernst

Copy link
Copy Markdown
Contributor Author

Fixed in 28ab4150 (core) and a4c767fa (core-tests). ValidateItemCreation now returns the validated workspace's key, ItemCreationParams carries it into the transaction, and eventItem stamps it on the snapshot. The v1 mapper and the created notification therefore format the same key as a joined read, with no second lookup or per-caller fallback. The detail-read-failure regression now asserts the exact key (CTL-1) as well as the numeric ID; it fails with key = "" when the key is not carried.

AddMilestoneWithContext passed the action context to the post-commit
emitter but not into the transactional update, so the committed item
fact fell back to source "application" with no chain, depth, or source
application. Build the metadata once from the command context and pass
it into AddMilestone, matching normal updates.

Downstream automation derives the action from the committed fact, so it
could not identify the originating chain or depth for SCM attachments.
MCP and chat tools implemented part of the operation they invoked:
create_item and update_item called the low-level create/update services,
and log_time wrote the repository directly. Agent writes therefore
skipped description-mention processing, hierarchy cache invalidation,
the created/updated event pipeline, and the worklog description policy,
so the result depended on how the write entered the system.

Inject the shared ItemApplicationService and TimeWorklogService into the
tool environment and call them. Tool scopes, key resolution, and output
formatting stay in the adapter; agent actor/source/run provenance is
passed through explicitly so it is not replaced by the human-only
"application" default. Embedders that do not wire the shared services
fall back to a local pipeline, matching the previous behavior.
The assignment client writes /workspaces/{id}/configuration-set, but the
invalidation table only matched plural configuration-sets or an exact
workspace URL. Neither matched, so the effective-screen cache could keep
serving the previous configuration without a request after a successful
assignment.

Match the singular endpoint and drop only that workspace's cached
effective configurations, discarding in-flight pre-change reads so a slow
response cannot repopulate the cache.
The handler DB guard scanned legacy handlers and v1 only, so new direct
DB access in v2 would pass unnoticed; include internal/restapi/v2 and
allowlist the three existing database/sql imports.

The layering guard matched an import path with a closing quote, so the
cacheutil leaf rule against windshift/internal missed subpackage
imports. Match the forbidden package exactly or any subpackage of it.
The catch-all error branch returned a payload with a nil Go error, so a
failed insert looked like a successful MCP call. Map known input errors
to the payload and return nil, err for unexpected service failures.

Also forward the worklog service's sanitization warnings in the success
response, matching the HTTP worklog responses, so a caller learns when
its description was shortened.
Standard Agent tool writes skipped the mention processor, event emitter,
and hierarchy cache because the dispatcher's aitools.Env omitted
ItemApplication. Pass the shared item and worklog pipelines through
Options and install them before Resume can start a queued run by moving
the dispatcher construction after the item application service exists.
Per-workspace screen-config invalidation bumped the global epoch, which
discarded valid in-flight reads for other workspaces. Track a
per-workspace epoch so only the assigned workspace's pre-change response
is dropped.

The assignment endpoint also left the collection priority picker stale
because it loads from collectionEditorOptions with a five-minute TTL.
Invalidate the workspace's priorities and bump a per-key generation so a
pending old load cannot restore them.
ItemApplicationService.Create enriched the response after the create
transaction committed and returned a nil item on failure, so create_item
reported a retryable error for an item that already existed. A retry
could duplicate it.

Return the committed item alongside the enrichment error, and have the
tool audit and report the stored row instead of a create failure.
The assignment rule only cleared screen configs and priorities, leaving
the active workspace's bootstrapped statuses and item types stale; a
create dialog could read the previous item types for its parent picker.

Re-fetch the assigned workspace's bootstrap catalogs, invalidate its
status options, and apply the same per-workspace invalidation from the
migration assistant, whose POST reassigns the workspace without the
assignment PUT.
Create now returns the transaction's ID as the success result; the detail
read only decorates the response, so a post-commit read failure no longer
turns a committed create into a retryable error.

Configuration changes reload the active workspace through the existing
reset/initialization lifecycle, which supersedes in-flight reads, instead
of assignment-specific field rules and per-workspace cache counters.
…mand

The create transaction already builds the created row, so return it as
the create result instead of leaving callers with a nil item when the
joined read fails. ID-only consumers use result.ID; callers that need a
row or an event use the snapshot, and the created event still fires.

Also return the caller-facing copy from ItemApplicationService.Create on
enrichment failure, so project-name and related-item masking applied
before a later read failure is not discarded.
The snapshot had the item number but not the workspace key, so the v1
response mapper and the created notification formatted a key like
"-1". ValidateItemCreation already reads the workspace, so return its
key and carry it into ItemCreationParams; the snapshot then has the same
display key as a joined read.
@stefan-ernst
stefan-ernst force-pushed the fix/architecture-review-findings branch from 28ab415 to 3da1237 Compare November 24, 2026 10:24
@stefan-ernst
stefan-ernst merged commit 921e1de into main Nov 24, 2026
22 checks passed
@stefan-ernst
stefan-ernst deleted the fix/architecture-review-findings branch November 24, 2026 10:35
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.

1 participant