Skip to content

fix(export): stop advertising a signed compliance export that does not exist - #76

Merged
Coding-Dev-Tools merged 1 commit into
mainfrom
fix/export-claims
Jul 26, 2026
Merged

fix(export): stop advertising a signed compliance export that does not exist#76
Coding-Dev-Tools merged 1 commit into
mainfrom
fix/export-claims

Conversation

@Coding-Dev-Tools

Copy link
Copy Markdown
Owner

The contradiction

The dashboard and README sold a "Signed compliance export" that was never built — and the 501 that customers hit pointed them at Engraphis Cloud, which does not implement it either. Both ends deferred to each other.

Evidence (this repo)

Claim Evidence
Sold in the upgrade panel engraphis/static/dashboard.js:162'Signed compliance exports with bi-temporal checksums' in the Pro benefits list
Sold in the pricing table README.md:426Signed compliance export (checksummed bi-temporal bundle)
Sold in the changelog CHANGELOG.md:800 — "Pro analytics dashboard and compliance export"
No signing code /export's docstring referenced :func:`_sign_export` grep -rn "_sign_export" matches only that docstring. The function does not exist.
The 501 pointed at Cloud routes/v2_api.py:1326"Signed compliance exports are available in Engraphis Cloud."
So did /analytics/export routes/v2_api.py:1293"Download analytics reports from the Engraphis Cloud dashboard."

Evidence (engraphis-cloud)

  • No export route — no @router path matching export.
  • No export:* token scope_token_scopes (api/control.py:567-599) mints only analytics / automation / device / entitlement / job / organization / sync / workspace scopes.
  • No export job kindapi/managed.py:283 is kind: Literal["analytics", "consolidate", "dream"].

A private hosted service cannot serve an export the control plane never authorizes and never schedules, so the absence is definitive rather than a visibility gap.

What is not affected

Plain local workspace export is real, and always was free. GET /export returns the full bi-temporal dump (memories + sessions + audit) on every plan. It is deliberately not entitlement-gated so data portability survives recovery mode — confirmed by tests/test_dashboard_v2.py, whose test was already named test_raw_owner_export_is_free_....

The old docstring called it "Pro-gated" and exportWorkspace() caught a 402 with "Export is a Pro feature" — both were wrong. HostedFeatureError/LicenseError is never raised anywhere in engraphis/, so the 402 handler in dashboard_app.py:150 is entirely dormant. This PR corrects the docstring and drops the dead 402 branch; the README now lists local export as the free capability it is.

Changes

Feature tables (mirroring the server change)

  • routes/v2_api.py — drop export from _PRO_FEATURES and _FEATURE_LABELS
  • hosted_client.py — drop export from _REQUIRED_PLAN

Honest failures — both 501s now state the capability is unimplemented and name the working alternative, instead of implying it exists in Cloud:

  • GET /export?signed=true{"error": "Signed compliance exports are not implemented. Omit signed=true for the unsigned workspace export, which contains the same data.", "implemented": false, "alternative": "/export"}. It still refuses rather than silently returning an unsigned bundle — a caller asking for tamper-evidence must not be handed something that merely looks like it.
  • GET /analytics/export → points at GET /analytics, which serves the same data the control plane exposes as JSON via /analytics/latest.

Customer-facing copy

  • dashboard.js — benefit line removed; exportWorkspace() drops its unreachable signed argument and the false 402 toast (it was never wired to any UI element)
  • README.md — Pro row removed, free local-export row added
  • CHANGELOG.md — historical line corrected, with an [Unreleased] / Removed entry recording the withdrawal and explicitly noting that no entitlement behaviour changed

Enforcement impact

None. These tables are presentation only — entitled_features' own docstring says so ("This decides which lock badges the dashboard draws, never whether an operation is permitted"), as does HostedFeatureError ("presentation metadata only. It never decides entitlement"). Every paid operation is still authorized by the cloud's token scopes and paid-entitlement dependencies.

Cross-repo drift

The server's plan→feature table was hand-copied into six places, not the three previously flagged. All six updated:

  1. tests/test_client_launch.py:48-49
  2. tests/test_licensing_launch.py:31-32
  3. tests/test_hosted_plan_resolution.py:56-57
  4. tests/test_cloud_session.py:314 (found during this audit)
  5. tests/e2e/commercial.spec.js:7-17 (found during this audit)
  6. tests/test_dashboard_auth_placement.py:333 (benefit copy)

There is still no automated cross-repo check — these remain hand-maintained. The server-side PR adds a guard that at least prevents a new undeliverable key being introduced there.

Verification

  • pytest tests/ -q: 1411 tests, 0 failures, 14 skipped — identical to the origin/main baseline
  • ruff check .: All checks passed!
  • scripts/externalize_dashboard_assets.py: clean (exit 0)
  • scripts/check_commercial_manifest.py: commercial manifest check: OK

Cross-repo

Companion server PR: Coding-Dev-Tools/engraphis-cloud#27

🤖 Generated with Claude Code

…t exist

The dashboard's Pro upgrade panel sold "Signed compliance exports with
bi-temporal checksums" and the README pricing table sold "Signed compliance
export (checksummed bi-temporal bundle)", but the capability was never built:

* no signing code in this client -- `/export`'s docstring referenced
  `:func:`_sign_export``, which does not exist anywhere in the repo;
* `GET /export?signed=true` answered 501 "available in Engraphis Cloud", and
  `GET /analytics/export` answered 501 "download from the Engraphis Cloud
  dashboard";
* but Engraphis Cloud has no export route, no `export:*` token scope
  (`_token_scopes`, api/control.py:567-599), and no export job kind
  (`Literal["analytics", "consolidate", "dream"]`).

Both ends pointed at each other and neither implemented it.

Changes:
* drop `export` from `_PRO_FEATURES`, `_FEATURE_LABELS`, and `_REQUIRED_PLAN`,
  mirroring the server's PLAN_FEATURES change;
* make both 501s truthful -- they now say the capability is not implemented and
  name the working alternative instead of implying it exists in Cloud;
* remove the benefit line from the upgrade panel and the README pricing row;
* `exportWorkspace()` drops its unreachable `signed` argument and its false
  "Export is a Pro feature" 402 toast.

Plain local workspace export is unaffected and always was free: `GET /export`
returns the full bi-temporal dump on every plan and is deliberately not
entitlement-gated so data portability survives recovery mode. It is now listed
in the README as the free capability it is.

No enforcement behaviour changes. These tables are presentation only (see
`entitled_features`' docstring); `HostedFeatureError`/`LicenseError` is never
raised anywhere in the client, so `required_plan` fed nothing but a dormant
handler.

Updates all six hand-copied mirrors of the server's plan->feature table:
test_client_launch, test_licensing_launch, test_hosted_plan_resolution,
test_cloud_session, tests/e2e/commercial.spec.js, and
test_dashboard_auth_placement. There is still no automated cross-repo check.

Companion server change: engraphis-cloud PR "fix(entitlements): stop selling
"export", which is implemented nowhere".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@greptile-apps

greptile-apps Bot commented Jul 26, 2026

Copy link
Copy Markdown

Greptile Summary

This PR removes all advertising of a "Signed compliance export" feature that was never implemented on either the client or the Engraphis Cloud side, replacing misleading 501 error bodies with honest ones that name the working alternative (GET /export unsigned).

  • v2_api.py and hosted_client.py drop export from the plan→feature tables (presentation-only); both 501 responses now state the capability is unimplemented and point callers at what exists instead of implying it lives in Cloud.
  • dashboard.js removes the false Pro benefit line and the dead signed argument from exportWorkspace(); README.md and CHANGELOG.md are corrected to reflect that local workspace export is free.
  • Six hand-maintained copies of the plan→feature table across the test suite are updated consistently, and a regression guard is added to test_dashboard_auth_placement.py to prevent the false copy from returning.

Confidence Score: 4/5

Safe to merge — all changes are strictly corrective and no entitlement logic is touched.

The change is well-scoped and internally consistent: both 501 bodies are updated, all six hand-maintained feature-table copies in the test suite are corrected, and a regression guard prevents the false benefit from reappearing. The only gap is that the analytics_export 501 response body is not validated in the test suite the same way the export?signed=true body is.

Files Needing Attention: tests/test_dashboard_v2.py — the test_portfolio_and_report_analytics_are_hosted_only test only checks the status code for analytics/export, unlike the thorough shape assertions added for export?signed=true.

Important Files Changed

Filename Overview
engraphis/routes/v2_api.py Removes export from _PRO_FEATURES and _FEATURE_LABELS; replaces misleading 501 bodies for both GET /export?signed=true and GET /analytics/export with honest implemented: False responses naming working alternatives.
engraphis/hosted_client.py Removes "export": "pro" from the presentation-only _REQUIRED_PLAN map; no entitlement logic is affected.
engraphis/static/dashboard.js Drops "Signed compliance exports with bi-temporal checksums" from the Pro upgrade panel benefit list; simplifies exportWorkspace() by removing the dead signed argument and the unreachable 402 toast handler.
tests/test_dashboard_v2.py Renames and strengthens the signed-export test to verify the new honest 501 shape; the analytics_export sibling test still only checks the status code without validating the updated response body.
tests/test_dashboard_auth_placement.py Removes the false benefit assertion and adds a regression guard asserting "compliance export" never reappears in the upgrade panel script.
README.md Replaces the non-existent Pro-only "Signed compliance export" row with an accurate free-tier "Local workspace export" row available on all plans.
CHANGELOG.md Adds a detailed [Unreleased] / Removed entry explaining the withdrawal and explicitly noting no entitlement behaviour changed; corrects a historical release line that overstated shipped scope.

Comments Outside Diff (1)

  1. tests/test_dashboard_v2.py, line 279-282 (link)

    P2 analytics_export response shape left unverified

    The parallel fix to GET /analytics/export changed its 501 detail from {"managed_cloud": True} to {"implemented": False, "alternative": "/analytics"}, but this test still only checks the status code. The export?signed=true test (just below) explicitly asserts "cloud_only" not in detail and "Engraphis Cloud" not in detail["error"]; the same guard is missing here. A future accidental revert of the analytics_export body would pass this test undetected.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: tests/test_dashboard_v2.py
    Line: 279-282
    
    Comment:
    **`analytics_export` response shape left unverified**
    
    The parallel fix to `GET /analytics/export` changed its 501 detail from `{"managed_cloud": True}` to `{"implemented": False, "alternative": "/analytics"}`, but this test still only checks the status code. The `export?signed=true` test (just below) explicitly asserts `"cloud_only" not in detail` and `"Engraphis Cloud" not in detail["error"]`; the same guard is missing here. A future accidental revert of the `analytics_export` body would pass this test undetected.
    
    How can I resolve this? If you propose a fix, please make it concise.

    Fix in Claude Code

Fix All in Claude Code

Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
tests/test_dashboard_v2.py:279-282
**`analytics_export` response shape left unverified**

The parallel fix to `GET /analytics/export` changed its 501 detail from `{"managed_cloud": True}` to `{"implemented": False, "alternative": "/analytics"}`, but this test still only checks the status code. The `export?signed=true` test (just below) explicitly asserts `"cloud_only" not in detail` and `"Engraphis Cloud" not in detail["error"]`; the same guard is missing here. A future accidental revert of the `analytics_export` body would pass this test undetected.

Reviews (1): Last reviewed commit: "fix(export): stop advertising a signed c..." | Re-trigger Greptile

@Coding-Dev-Tools
Coding-Dev-Tools merged commit b12d4fc into main Jul 26, 2026
12 checks passed
Coding-Dev-Tools added a commit that referenced this pull request Jul 26, 2026
…aces

Three unresolved review threads on #75, plus one semantic conflict the merge with
main could not see.

`default_compute_url` now reads the manifest's `compute_plane` and falls back to
`DEFAULT_COMPUTE_URL`. The review asked for the constant to be replaced outright,
but the shipped `engraphis-commercial/v2` manifest declares only `control_plane`:
reading the absent key alone resolves `""`, and `cloud_session.configured()` then
rejects the session a production connect just saved, leaving a paying customer
"connected" but unusable. Preferring the key removes the drift point the review
named -- a manifest-only endpoint change needs no code change -- while the constant
stays as the fallback that keeps today's manifest working.

`_validated_timeout` refuses a non-finite or non-positive timeout. `argparse`'s
`type=float` accepts `nan` and `inf`, which reach the pinned opener's deadline
arithmetic and raise `ValueError`/`OverflowError` from inside `urllib`, neither
caught by `post_connect`. That broke this module's contract that every failure is a
`DeviceConnectError`, so `engraphis connect --timeout nan` printed a traceback
instead of the command's error and exit code. Checked at the top of `connect()` so a
bad flag is reported as a bad flag rather than masked by whatever the identity or
storage pre-flight hits first, and again in `post_connect()` because it is public and
owns the socket call.

`connect()` now also translates `OSError` from `save_bootstrap`. The pre-flight
added in aae7d93 closes the common case, but the state directory can still change
between the pre-flight and the write, and `UnsafeStateFile` is an `OSError`, not a
`CloudSessionError`, so it escaped as a traceback at the worst moment. The token is
spent by then, so the copy says so instead of promising a retry with the same one.

The `REGISTRATION` fixture no longer claims the cloud grants `export`. #76 removed
that key from the plan->feature tables in both repos because the signed compliance
export was never implemented; a fixture asserting the control plane returns it would
re-establish exactly the drift that removal cleaned up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Coding-Dev-Tools added a commit that referenced this pull request Jul 27, 2026
…aces

Three unresolved review threads on #75, plus one semantic conflict the merge with
main could not see.

`default_compute_url` now reads the manifest's `compute_plane` and falls back to
`DEFAULT_COMPUTE_URL`. The review asked for the constant to be replaced outright,
but the shipped `engraphis-commercial/v2` manifest declares only `control_plane`:
reading the absent key alone resolves `""`, and `cloud_session.configured()` then
rejects the session a production connect just saved, leaving a paying customer
"connected" but unusable. Preferring the key removes the drift point the review
named -- a manifest-only endpoint change needs no code change -- while the constant
stays as the fallback that keeps today's manifest working.

`_validated_timeout` refuses a non-finite or non-positive timeout. `argparse`'s
`type=float` accepts `nan` and `inf`, which reach the pinned opener's deadline
arithmetic and raise `ValueError`/`OverflowError` from inside `urllib`, neither
caught by `post_connect`. That broke this module's contract that every failure is a
`DeviceConnectError`, so `engraphis connect --timeout nan` printed a traceback
instead of the command's error and exit code. Checked at the top of `connect()` so a
bad flag is reported as a bad flag rather than masked by whatever the identity or
storage pre-flight hits first, and again in `post_connect()` because it is public and
owns the socket call.

`connect()` now also translates `OSError` from `save_bootstrap`. The pre-flight
added in aae7d93 closes the common case, but the state directory can still change
between the pre-flight and the write, and `UnsafeStateFile` is an `OSError`, not a
`CloudSessionError`, so it escaped as a traceback at the worst moment. The token is
spent by then, so the copy says so instead of promising a retry with the same one.

The `REGISTRATION` fixture no longer claims the cloud grants `export`. #76 removed
that key from the plan->feature tables in both repos because the signed compliance
export was never implemented; a fixture asserting the control plane returns it would
re-establish exactly the drift that removal cleaned up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Coding-Dev-Tools added a commit that referenced this pull request Jul 27, 2026
* feat(dashboard): opt-in canvas graph engine behind ?graph-engine=next

A second knowledge-graph renderer wrapping the already-vendored force-graph,
opt-in behind ?graph-engine=next. Classic stays the default and the rollback
path; graphRender falls through to it on any failure. Four styles are applied
CSP-safely through a data-graph-style attribute rather than inline style.

Fixed while reviewing, before this shipped:

- XSS. setData stamped name on every node, and force-graph's nodeLabel
  defaults to that accessor and renders through innerHTML. Node names are
  entity labels extracted from ingested memories. Classic never set name, so
  the sink did not exist until this feature added it. Both accessors are now
  explicit and escaped.
- Recursive Tarjan overflowed the stack at roughly 29.6k nodes on a chain
  component; rewritten iteratively.
- The rAF loop never stopped: a hidden canvas kept repainting for the whole
  session. Added pause/resume driven from selectView and a real destroy().
- Unbounded O(V*E) betweenness on the main thread with Array.shift queues,
  now lazy, pivot-sampled and budgeted: 60k nodes went 25s to 3s, and 0s in
  the default view.
- prefers-reduced-motion was ignored, against an existing dashboard contract.

The CSP drift gate never scanned this asset -- it only ever read index.html,
dashboard.css and dashboard.js -- so "the gate passes" was vacuous for any new
first-party script. Extended to hold them to the same contract and to check
that every /static script index.html references actually exists. All four new
rules were negative-tested.

The original test asserted formatting strings. Replaced with 24 tests that
execute the asset under Node with only a bare window in scope, which is itself
the load-order proof, and mutation-tested: removing the escaping fails them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(dashboard): lazy-load the graph assets so the CSP stays clean

Adding force-graph.min.js and engraphis-graph.js to index.html loaded them
on every dashboard page, not just the graph view. force-graph applies inline
styles at runtime, the production CSP is style-src 'self', so the browser
blocked them and logged an error per attempt. Eleven pre-existing e2e tests
assert a clean console and failed -- a regression this branch introduced.

dashboard.js already had loadForceGraph() lazily fetching the vendor bundle
for the Classic renderer, so neither script ever needed to be in index.html.
Both tags are removed and engraphis-graph.js gets a matching memoized loader.

The naive version of that would silently downgrade a ?graph-engine=next deep
link to Classic, because graphRenderEngine's guard cannot tell "not fetched
yet" from "unavailable". The engine fetch now starts alongside the vendor
bundle -- one round trip, not two -- and graphRender waits on it and
re-enters, so only a genuine load failure degrades, and that path warns.
Proved by executing the real routing source under Node with a stub DOM:
deep link renders the engine, a failing asset falls back and warns. Both are
tests, and reverting to defer-without-await fails them.

The "referenced scripts exist" gate rule became three, so removing the tags
strengthens it rather than hollowing it out: lazy script.src references are
existence-checked (their only reference is a JS string literal), neither
asset may reappear as a parsed script src in index.html, and each must keep
a lazy loader so deferring cannot orphan them. All negative-tested.

Local gate: 1429 passed, 0 failed. The CSP fix itself cannot be proven
locally -- Playwright needs node_modules, which is not installed here -- so
CI is the real verification for the 11 e2e assertions.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(graph): address review findings on the opt-in engine

Six findings from PR #74 review.

Particles were assigned per relation with no regard for graph size, so the
Cyber style with flow enabled created tens of thousands of animated
particles on a large workspace. Capped against the existing large-graph
signal.

Community clustering added every link to the adjacency, so one sparse
influences relation merged two unrelated topics into a single component and
Community Islands gave them the same colour and force centre. Matched to the
classic renderer's semantics.

Hover changed hilite/hoverSet without invalidating the canvas, so with
reduced motion on, flow off, or the simulation settled, highlight changes
were invisible. The redraw is now requested.

Show unlinked nodes never reached the engine: graphData() supplied
degree-zero nodes while the engine's own filter still dropped them.

Leaving the graph view before /graph or a lazy script resolved ran pause
against a null renderer, so the pending callback could still create and
start one against a hidden pane -- the rAF leak this PR fixed once already,
by another route.

The CSP gate parsed script tags case-sensitively, so an equivalent HTML
spelling browsers load eagerly slipped past both the eager-load rejection
and the existence check. Now uses the HTMLParser already in the file, which
normalises case.

1441 passed, 0 failed (+12 tests). All asset gates pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(graph): rank communities, settle large galaxy graphs, follow the theme

Three further findings from PR #74 review.

Community IDs were assigned in raw payload order while graphRenderLegend()
sorts communities by size and calls the largest "Cluster 1". Node colour
indexes the palette by the ID itself, so whenever a smaller component
appeared first the legend described one component with another's swatch.
Components are now ranked by size before the IDs escape, matching the
classic graphComputeCommunities().

Galaxy style held autoPauseRedraw(false) unconditionally, so a settled
large graph repainted every node and link every frame forever. The
starfield is the only paint force-graph cannot see; the classic path drops
it past GPERF.large, so the same 600-node/2400-link signal now skips it and
hands the redraw loop back to the vendor.

Type colours resolved from hard-coded dark-theme constants, so switching to
Light, Midnight, Solarized or Sepia moved the legend and controls while the
canvas stayed dark. The engine cannot read CSS custom properties from a
canvas, so the dashboard resolves --entity-* and supplies them through a new
setThemeColors(), below style palettes and user overrides in priority.

1446 passed, 0 failed (+5 tests). ruff, externalize and manifest gates pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(licensing): make the outage-is-not-a-cancellation test actually test that

The test raised CloudSessionError(..., status=503, transient=True), but that
class takes only status -- transient belongs to CloudFeatureError. So
the construction raised TypeError, the caller's broad except Exception
swallowed it, and getattr(exc, "status", None) was None rather than 503.

The assertion therefore passed while never exercising a transport failure at
all, and could not have caught the regression it exists to prevent: loosening
the 402 gate so any error clears a paying customer's access.

Verified by mutation -- with the gate changed to any-truthy-status the test now
fails with "an outage revoked a paying customer"; before this change it passed
even with that mutation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(graph): close the remaining review threads on the opt-in engine

Six findings from the PR #74 review, all cases where the opt-in renderer
diverged from the classic path it is meant to replace.

- Relation labels: the dashboard's Labels checkbox drives two label layers
  on the classic path, but the engine configured no linkCanvasObject, so
  ticking it painted entity names only and a relation could be read only
  by hovering it. Paint them, with the classic gates (zoom, dense-graph).
- zoomToNode: graphFocus() treats a false return as "run the recovery
  path". The engine answered from raw.nodes, which keeps the coordinates
  force-graph left on a node, so an entity hidden by a scope filter or by
  the auto-collapsed cluster view still reported success and the camera
  moved to nothing. Expand a collapsed view, then verify against the data
  force-graph is actually holding.
- Reseeding: render() called graphData() unconditionally with newly
  allocated arrays, so Style, Color by, Labels and Flow each reset the d3
  alpha and restarted the layout. Reseed only when the visible set really
  changed, and invalidate the paint when it did not.
- Cooldown: nothing overrode force-graph's 15s default simulation window,
  so a large store kept simulating (and repainting) far past the 1.1s/80
  ticks the classic path allows. Mirror its size-dependent bounds.
- Dense graphs: curvature and arrowheads stayed on past the classic
  GPERF.dense threshold, paying a bezier and a filled triangle per
  relation across thousands of links.
- Community colours: the cluster legend swatches are CSS (.graph-cluster-N)
  encoding the Cyber palette, but the engine's Cyber and Solar palettes were
  ordered differently from dashboard.js, so on the default style the legend
  described each of the first clusters with another cluster's colour.

Each is covered by a test that fails without the change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(graph): reheat the simulation when a physics slider moves

Under ?graph-engine=next the Repel/Link/Gravity/Size sliders appeared dead.
dashboard.js::graphSet routes them through api.setSettings, which only asked
render() for a reheat when `mode` was present. applyForces() writes the new
charge / link / forceX-forceY / collide values straight into the simulation
force-graph is already running, and a settled graph sits at alpha~0 — so the
new forces were installed and nothing moved until the user found the Reheat
button. `size` is affected too: it feeds d3.forceCollide.

The classic branch of that same function does the opposite — it treats
`repel|link|gravity|size` as a layout change and reheats unless the user asked
for reduced motion. setSettings now matches that set (plus `mode`, which swaps
the whole force arrangement); render() already carries the reduced-motion
exemption, so it is honoured for free. Appearance-only settings (font,
link width, label density, labels, flow) still must not reheat: restarting the
layout because a label got bigger throws away the arrangement being read.

The regression test drives the API against the force-graph stand-in and counts
d3ReheatSimulation() calls per key. Pre-fix it reported
{repel: 0, link: 0, gravity: 0, size: 0, mode: 1}.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(licensing): settle cached access on entitlement 402

* Add `engraphis connect --token` so a purchased client can actually connect

`cloud_session.save_bootstrap()` is the only function that writes
`~/.engraphis/cloud_session.json`, and it had zero production callers — only
tests reached it. Meanwhile `docs/AGENT_CONNECT.md` and `.env.example` told
customers to prefer that file. Nothing created it, so a paying customer had no
supported way to connect a client and every paid feature was undeliverable.

This adds the client half of the device-connect flow that the control plane
already serves:

- `engraphis/device_connect.py` — token validation, stable client identity, the
  POST to `/v1/devices/connect`, status-keyed error copy, and the call into
  `save_bootstrap`.
- `scripts/connect.py` — the CLI, following `scripts/init.py` conventions
  (`main(argv=None) -> int`, argparse, no prompts).
- `scripts/entry.py` — an `engraphis` front door that dispatches to the existing
  `engraphis-<verb>` mains, so the portal's `engraphis connect --token ...` is a
  runnable command. `engraphis-connect` is installed too.

Credential handling: the connect token travels in the request body and nowhere
else — never printed, logged, or persisted, and never quoted back in an error.
Malformed or truncated tokens are rejected before any network call, so a bad
paste costs no rate budget and consumes no token. Network access uses the repo's
pinned opener with redirects blocked and an explicit timeout; provider bodies are
never reflected into messages. A 401 (expired / already used / invalid, which the
service deliberately makes indistinguishable) stays distinct from a 402 lapsed
subscription, because the fixes differ.

Client ids are minted-once random ULIDs in the owner-only state directory rather
than a hardware fingerprint: a MAC- or hostname-derived id is a cross-account
identifier the customer never agreed to ship, and it changes under exactly the
conditions where stability was the point.

The command verifies `cloud_session.configured()` after writing, and says so
explicitly when only the compute endpoint is missing rather than half-reporting
success.

Docs updated: `docs/AGENT_CONNECT.md` and `.env.example` now describe
`engraphis connect --token` as the real path to the session file.

Tests: 43 new, covering the happy path writing a usable session, 401 printing
actionable copy and writing nothing, 402 staying distinguishable, the token never
appearing in stdout/stderr or any written file, and short/malformed tokens being
rejected before the network.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Pre-flight session storage before redeeming the connect token

`connect()` spent the single-use connect token on the POST and only then called
`save_bootstrap()`. If the state directory had become unwritable, or
`cloud_session.json` had been replaced by a symlink, a hard link or a directory,
the write failed after the token was already consumed: the customer was left with
a spent token and no session, and had to go back to the portal for a new one.

Worse, `atomic_private_text` raises `UnsafeStateFile`, which is an `OSError` and
not a `CloudSessionError`, so it escaped `connect()`'s handler entirely and
surfaced as a raw traceback rather than actionable copy.

`cloud_session.preflight_save()` now runs before the exchange. It lives beside
`_session_path()`, `_refresh_lock()` and `_save()` because that module owns the
paths and the atomic write it predicts; a private copy of those rules in
`device_connect` would drift from the save it is meant to model. It reuses the
existing primitives -- `private_file_stat` on the session leaf and on its refresh
lock, plus the randomized sibling temp file `atomic_private_text` has to create --
and never opens, creates or replaces the session leaf, so an existing session
survives a failed pre-flight untouched and a first connect is not left half
written. `_refresh_lock()` picks up the extracted `_refresh_lock_path()` so the
lock filename is not duplicated.

`device_connect._preflight_session_storage()` translates the failure into a
`DeviceConnectError` that names the path to fix and states that the token is
still redeemable, and `connect()` reuses the returned path for the summary
instead of rebuilding it from `_state_dir()`.

Tests: 6 new, all asserting `opener.calls == []` -- the POST is never issued.
Session leaf and refresh lock replaced by a directory, a genuinely hard-linked
session, an uncreatable state directory (`ENGRAPHIS_STATE_DIR` under a regular
file), a read-only mount, and a pre-flight that creates nothing and leaves no
probe file behind. All six fail against the pre-fix code.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Address connect review: manifest compute endpoint, timeout and save races

Three unresolved review threads on #75, plus one semantic conflict the merge with
main could not see.

`default_compute_url` now reads the manifest's `compute_plane` and falls back to
`DEFAULT_COMPUTE_URL`. The review asked for the constant to be replaced outright,
but the shipped `engraphis-commercial/v2` manifest declares only `control_plane`:
reading the absent key alone resolves `""`, and `cloud_session.configured()` then
rejects the session a production connect just saved, leaving a paying customer
"connected" but unusable. Preferring the key removes the drift point the review
named -- a manifest-only endpoint change needs no code change -- while the constant
stays as the fallback that keeps today's manifest working.

`_validated_timeout` refuses a non-finite or non-positive timeout. `argparse`'s
`type=float` accepts `nan` and `inf`, which reach the pinned opener's deadline
arithmetic and raise `ValueError`/`OverflowError` from inside `urllib`, neither
caught by `post_connect`. That broke this module's contract that every failure is a
`DeviceConnectError`, so `engraphis connect --timeout nan` printed a traceback
instead of the command's error and exit code. Checked at the top of `connect()` so a
bad flag is reported as a bad flag rather than masked by whatever the identity or
storage pre-flight hits first, and again in `post_connect()` because it is public and
owns the socket call.

`connect()` now also translates `OSError` from `save_bootstrap`. The pre-flight
added in aae7d93 closes the common case, but the state directory can still change
between the pre-flight and the write, and `UnsafeStateFile` is an `OSError`, not a
`CloudSessionError`, so it escaped as a traceback at the worst moment. The token is
spent by then, so the copy says so instead of promising a retry with the same one.

The `REGISTRATION` fixture no longer claims the cloud grants `export`. #76 removed
that key from the plan->feature tables in both repos because the signed compliance
export was never implemented; a fixture asserting the control plane returns it would
re-establish exactly the drift that removal cleaned up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Report post-redemption connect failures instead of raising tracebacks

Both paths fail *after* the control plane has consumed the single-use connect
token, so a raw traceback left the customer unable to tell whether to retry or
fetch a new token from the portal.

`http.client.IncompleteRead` (a truncated chunked reply) subclasses
`HTTPException`/`ValueError` -- neither `OSError` nor `URLError` -- so it escaped
both of `post_connect`'s handlers. A third clause is added *after* the transport
clause, because `RemoteDisconnected` is both a `ConnectionResetError` and a
`BadStatusLine` and means the peer never answered: that one keeps the retryable
503 copy, and a test pins the ordering.

`save_bootstrap` re-runs `validate_cloud_base_url` on both endpoints, which
resolves the host. A resolver that dies mid-connect raises `CloudUrlUnresolved`
and an endpoint that starts resolving to a rejected address raises a bare
`ValueError`; both are `ValueError`, so neither the `CloudSessionError` nor the
`OSError` handler in `connect()` covered them. Translated in `connect()` rather
than by dropping the re-validation, which is still wanted for `save_bootstrap`'s
other callers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Read the trial and the access state the cloud sends, and render them

`/api/license` hardcoded `"is_trial": False` and `"trial": {"used": False}`.
Those were the only assignments in the file, and the client read none of
`status`, `trial_ends_at`, or `trial_duration_seconds` from anywhere, so three
customer-visible states were wrong or unreachable:

* the dashboard's `'TRIAL'` badge branch could never be taken — a trialist saw
  the same confident PRO/TEAM badge a subscriber sees;
* `trial.used` never became true, so "Start hosted Pro/Team trial" was offered
  to everyone forever, including active subscribers and customers whose trial
  was already spent. `start_trial` refuses any organization that already holds
  an entitlement, so for every connected customer that button could only ever
  return a `TrialAlreadyConsumedError`; and
* `cloud_access_active` was computed, returned, and rendered nowhere. After a
  trial expired or a subscription lapsed the client kept `plan="pro"` and
  cleared the feature list, so the customer got a confident PRO badge over
  rows of locked features with no explanation of what had happened.

The client now reads what the control plane already sends on the calls it
already makes. `cloud_session` persists `status`, `is_trial`,
`trial_consumed`, and `trial_ends_at` from the registration/refresh handshake
alongside the plan fields, under the same wire names so one parser serves the
saved record, the entitlements read, and the compatibility cache. Every field
stays individually optional: an older control plane omits them and the honest
answer is "not a trial, none consumed", never an invented one. A billing
denial keeps the trial facts — a lapse does not un-consume a trial or move its
boundary — and drops the status it just contradicted.

`/api/license` derives one `access_state` from that: active, trial,
trial_expired, lapsed, or inactive. Each is a different thing to tell the
customer and a different thing to ask them to do, and the dashboard now says
which:

* active trial   — TRIAL badge, the trial's end date, no trial CTA;
* spent trial    — TRIAL ENDED, "your free trial has ended, your memories are
                   still local and usable, the trial cannot be started again",
                   subscribe;
* paying         — PRO/TEAM badge, no trial CTA (a subscriber who never
                   trialled would still be refused one);
* lapsed         — PRO INACTIVE, why it lapsed when the cloud named a status,
                   and update billing;
* never          — LOCAL CORE, the local engine is complete on its own, and
                   the trial CTA — the one state it can actually be started in.

`plan_source`/`plan_checked_at` were emitted for support and displayed
nowhere; the panel now shows which rule produced the answer and when the cloud
last confirmed it. No inline styles or handlers were added; both asset gates
and `node --check` pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(connect): honor cloud-assigned compute endpoints

* fix(graph): trim large graph render costs

* fix(review): address open client release findings

* fix: close final release hardening gaps

* perf(graph): apply the classic renderer's large-graph guards to the opt-in engine

The engine already computed `large` (>600 nodes / >2400 links, the classic `GPERF.large`
signal) and used it for cooldown, alpha decay and the galaxy starfield, but two per-frame
costs the classic path drops at that cutoff were still being paid:

- `applyForces()` pinned `forceCollide().iterations(2)`. The second pass is another full
  quadtree traversal per node per tick, and a large store pays it on the initial layout and
  on every reheat. Now `iterations(large ? 1 : 2)`, matching `.iterations(GPERF.large?1:2)`.
- Every `rich` node still got a glow: the galaxy halo, the solar corona *and* its sphere
  shading, and the cyber `shadowBlur`. A gradient is a fresh object per node and a blur is a
  convolution of the drawn shape, both per frame. All three are now gated on `!large`, with
  the flat `fillStyle = col` fallback the classic path uses for the solar sphere.

Both are pinned by tests that drive the asset under Node and read the recorded force/canvas
calls back, and both fail against the previous asset (601 collision iterations of 2; 607
gradients painted on a large solar graph).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(graph): exercise the opt-in engine in a real browser

The Node harness in tests/test_graph_engine_asset.py drives the asset against a recording
force-graph stand-in, which is right for the logic and proves nothing about a browser: no
CSP, no real canvas, no vendor bundle, no <script> loading. The three defects this feature
shipped and then fixed were all in that gap. This adds the browser half to the Playwright
suite CI already runs (.github/workflows/ci.yml runs `npx playwright test`).

Five checks, each pinning a claim this PR makes:

- A dashboard page that never opens the graph fetches neither graph script and reports zero
  CSP violations. This is the actual reason both loads are lazy.
- `?graph-engine=next` fetches both assets exactly once, registers EngraphisGraph, assigns
  GRAPH_ENGINE, hides the degree-zero entity, and puts non-uniform pixels on a sized canvas.
- Moving the Repel slider after the layout has settled changes node coordinates. Verified by
  mutation: narrowing LAYOUT_KEYS back to ['mode'] fails this test, which is the dead-slider
  regression exactly as a user would have hit it.
- The opt-in renderer adds no CSP violation the classic renderer does not already cause.
  Opening the graph is not CSP-clean under either: force-graph injects <style> elements that
  `style-src 'self'` blocks (4 of them, identical on both paths, one-time at attach). That is
  a pre-existing vendor behaviour, and confining it to the graph view is what the lazy loading
  buys. What this pins is that the new engine contributes nothing on top and touches no inline
  style attribute.
- Without the flag the graph view stays on Classic and never fetches engraphis-graph.js.

The force-graph instance is reached by intercepting the vendor global from an init script
rather than by adding a test-only accessor to the engine's public API.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Fix the same IncompleteRead escape in cloud_session._post_refresh

Found while fixing the device-connect drain: `_post_refresh` carried the identical
`except (OSError, ValueError)` guard around its error-body drain, and had no
`http.client.HTTPException` clause at all -- it did not even import `http.client`.

Two consequences, both reproduced as failing tests first:

- A refresh reply that begins and then stops mid-body makes `HTTPResponse.read` raise
  `IncompleteRead`, which is not an `OSError`, so it escaped `_post_refresh` as a raw
  traceback. This is the token-refresh path every paid feature runs through, so the
  crash surfaced far from its cause.
- `IncompleteRead` raised while draining an `HTTPError` body escaped the drain guard and
  replaced the status-specific copy (401 "connect this installation again", 403, 429)
  with a traceback.

The drain guard is now the shared `_DRAIN_FAILURES` tuple, and a new `HTTPException`
clause maps a truncated reply to the existing "temporarily unreachable" copy. That clause
sits deliberately *after* the transport clause so `RemoteDisconnected` -- which is both a
`ConnectionResetError` and a `BadStatusLine` -- keeps the behaviour it already had.

In scope for this PR: it already modifies `cloud_session.py`, and `device_connect`'s drain
comment cites this function as the same shape, which was only true of the bug.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Say the token was spent on every post-2xx failure, and verify the session before printing success

Second review round, same family as the first: a failure that can only happen after the
control plane answered must never advise retrying a token that answer consumed.

- `post_connect`'s oversized / unparseable / non-object body branches said only "invalid
  connect response". `urllib` raises `HTTPError` for every status >= 400 and `_NoRedirect`
  turns a 3xx into one, so reaching those branches means a 2xx -- the token is gone. They
  now carry the same portal guidance as the truncated-reply and missing-credential paths,
  via a shared `_SPENT_TOKEN_SUFFIX`.
- `save_bootstrap` failing with `CloudSessionError` forwarded the bare message. That is how
  `_refresh_lock` reports a lock that vanished or turned unsafe after the pre-flight, and
  because it is a `CloudSessionError` rather than an `OSError` it bypassed the clause that
  explains the token was spent. It now keeps the cause *and* the guidance.
- `scripts/connect.py` printed the summary before calling `cloud_session.configured()`.
  That call reads the session back and can raise, so a complete `--json` success object
  reached stdout and the command then exited 1 -- a consumer parsing stdout accepted a
  failed connect. The check now runs first; on failure stdout stays empty.

All three reproduced as failing tests first (7 new cases). The oversized case carries an
explicit `pytest.param(id=...)` because a 64 KiB parameter overflows the 32767-character
limit on `PYTEST_CURRENT_TEST`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Separate connection failures from post-response failures, and fail the preflight when a probe cannot be removed

Third review round. `OSError` means opposite things either side of `opener.open()`, and
both call sites had them sharing one `try`.

- `device_connect.post_connect` now opens and reads in separate `try` blocks. Once `open`
  returns, urllib has parsed a success status line, so the control plane answered and the
  single-use token is spent; a `TimeoutError` or `ConnectionResetError` *mid-body* was
  inheriting the connection-phase copy and telling the customer to retry a token that
  could not work. Failures before the status line keep the retry copy, which is still
  right for them.

- `cloud_session._post_refresh` gets the same split, with sharper consequences. The
  rotated credential reaches disk only after the body parses, so a post-response failure
  leaves the *spent* credential stored. `_public_session_error` maps 503 to
  `transient=True`, and `CloudFeatureClient.run_job` acts on that by retrying — which
  resubmits the spent credential, and this module already documents that the control plane
  answers replay by revoking the whole credential family. Every post-response branch
  (truncated body, oversized, unparseable, non-object, incomplete credentials) now returns
  409, the existing non-transient "connect this installation again" bucket. A test asserts
  the status still maps to `transient is False`, since that mapping is the thing that
  actually prevents the retry.

  This prefers a false "reconnect" over a replay: if the truncation preceded the server's
  commit the reconnect was unnecessary, but the opposite mistake revokes the whole family
  and forces the same reconnect from a worse state.

- `cloud_session.preflight_save` no longer swallows a failed `os.unlink` of its probe.
  Creating a file and removing one are separate rights: a directory ACL granting add-file
  but denying delete let `mkstemp` succeed and `unlink` fail, and `atomic_private_text`
  finishes with `os.replace`, which needs exactly the right that just failed. The preflight
  passed on a directory the real save could not use, redeeming the token before failing,
  and littered a probe on every attempt — the precise drift the preflight exists to prevent.

Ten new test cases; every one failed before its fix.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix: close latest release review gaps

* Require credential fields to actually be strings

`str(response.get(key) or "").strip()` reads like a coercion but is not a validation. JSON
arrays and objects arrive as Python `list`/`dict`, and `str()` renders their repr:

    str(["tok_abc"] or "").strip()  ->  "['tok_abc']"   # truthy, non-empty

So a control-plane reply carrying `"refresh_credential": ["tok_abc"]` passed the
missing-credential check, `save_bootstrap` persisted the literal text `['tok_abc']`,
`configured()` read it back as a usable session, and the CLI reported a successful
connection -- while the next refresh submitted that junk and failed. By then the single-use
connect token was spent, so the customer could not retry without a new one.

Adds `cloud_session.text_field()`, which returns the value only when it is genuinely a
string, and uses it at every untrusted-provider boundary: `save_bootstrap`, the rotation
handling in `access_for_workspace`, and the pre-save check in `device_connect.connect` --
the last one via the same helper the writer uses, so the two cannot disagree about what
counts as present.

Identity fields (`installation_id`, `device_id`, `member_id`, `refresh_expires_at`) are
dropped rather than stored as a repr, since the dashboard displays them verbatim.

Six new cases covering list / dict / int / bool credentials, the writer boundary directly,
and the identity fields; all failed before the fix.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: declare version 1.1.0

Bump the five places the client version is written, all of which
`tests/test_packaging.py` requires to agree: `pyproject.toml`, the
`PackageNotFoundError` fallback in `engraphis/__init__.py`, the commercial
manifest that `scripts/check_commercial_manifest.py` cross-checks against
pyproject, and the plugin/marketplace pair under `.claude-plugin/`.

Editing the two `.claude-plugin/*.json` files invalidates their entries in
`.claude-plugin/skill-assets.sha256`, which `test_packaging.py` verifies by
hashing the files on disk, so those two digests are regenerated here. All
six files are LF, as `.gitattributes` requires.

1.1.0 rather than 1.0.2: the unreleased work adds commands and changes the
managed-compute consent default, which is a minor bump. Note that 1.0.1 was
declared and dated in the changelog but never tagged or published — PyPI's
latest is 1.0.0 — so 1.1.0 is the first release to actually carry it.

No tag is pushed by this commit; publishing stays a separate, deliberate step.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(graph): honor theme and validate lazy assets

* fix(graph): restore readable entity labels

* fix: absorb current release review heads

* fix(connect): harden ambiguous device activation failures

* feat(graph): serve renderer from v2 dashboard

* fix(graph): keep v2 assets lazy and themed

* fix: close remaining client review gaps

* test: pin ambiguous refresh timeout handling

* fix(graph): bound label rendering density

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
@Coding-Dev-Tools
Coding-Dev-Tools deleted the fix/export-claims branch July 28, 2026 07:21
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