Steward cut 1: delete dead scaffolding and sync AGENTS/service-contract docs
This commit is contained in:
parent
58d183231c
commit
477ff0dee5
10 changed files with 9 additions and 1415 deletions
77
AGENTS.md
77
AGENTS.md
|
|
@ -26,12 +26,8 @@ The planned non-shared-by-default layer is:
|
|||
|
||||
## Canonical State
|
||||
|
||||
- Treat `state/map.yaml` as the canonical current project map.
|
||||
- Treat `state/scratch.md` as disposable working memory for one bounded subgoal.
|
||||
- Treat `state/evidence.jsonl` as the distilled durable ledger of decisions,
|
||||
verified boundaries, and rejected paths.
|
||||
- Treat `state/branches.json` as hypothesis tracking, not phase/status prose.
|
||||
- Treat `notes/fresh-workspace-handoff.md` as the compact re-entry packet.
|
||||
- Treat `docs/architecture.md` as the source-grounded shared architecture note.
|
||||
- Treat `docs/implementation-plan.md` as the forward plan.
|
||||
- Treat `docs/app-profiles/repixelizer.md` and
|
||||
|
|
@ -50,75 +46,17 @@ every absolute path in here rotted the moment it happened.
|
|||
- Repixelizer profile: `docs/app-profiles/repixelizer.md`
|
||||
- StreamPixels profile: `docs/app-profiles/streampixels.md`
|
||||
- Spotiverse profile: `docs/app-profiles/spotiverse.md`
|
||||
- Handoff summary: `notes/fresh-workspace-handoff.md`
|
||||
- State CLI: `tools/heimdall_state.py`
|
||||
- Pre-compaction helper: `tools/heimdall_prepare_compaction.py`
|
||||
|
||||
## Useful Commands
|
||||
|
||||
Both state tools are single-file, standard-library-only Python. They need no
|
||||
virtualenv and no installed dependencies. Run them with `python` from the repo
|
||||
root:
|
||||
|
||||
```powershell
|
||||
python .\tools\heimdall_state.py status
|
||||
python .\tools\heimdall_state.py add-evidence --type design --status accepted --note "..."
|
||||
python .\tools\heimdall_prepare_compaction.py
|
||||
```
|
||||
|
||||
Verified 2026-09-06 against Python 3.13.15 installed to the user scope; `py -3`
|
||||
resolves the same interpreter.
|
||||
|
||||
If `python --version` prints an install prompt rather than a version, PATH is
|
||||
resolving the Microsoft Store alias in `WindowsApps` instead of a real
|
||||
interpreter, and it will still exit 0 while doing so. Install a real Python and
|
||||
put it ahead of `WindowsApps` on PATH rather than hunting for some other
|
||||
interpreter to hard-code here:
|
||||
|
||||
```powershell
|
||||
winget install --id Python.Python.3.13 --scope user
|
||||
```
|
||||
|
||||
## Session Bootstrap And Re-entry Protocol
|
||||
|
||||
On fresh session load:
|
||||
|
||||
1. read:
|
||||
- `state/map.yaml`
|
||||
- `notes/fresh-workspace-handoff.md`
|
||||
- `docs/architecture.md`
|
||||
- `docs/implementation-plan.md`
|
||||
2. run:
|
||||
- `python .\tools\heimdall_state.py status`
|
||||
- `git status --short --branch`
|
||||
- `git log --oneline -5`
|
||||
3. restate the current next action from persisted state before editing
|
||||
|
||||
After compaction or suspicious continuity loss:
|
||||
|
||||
1. rerun `heimdall_state.py status`
|
||||
2. reread `state/map.yaml` and `notes/fresh-workspace-handoff.md`
|
||||
3. treat the persisted next action as authoritative unless fresh evidence
|
||||
contradicts it
|
||||
|
||||
When the user says to prepare for imminent compaction:
|
||||
|
||||
1. run `tools/heimdall_prepare_compaction.py`
|
||||
2. update only the state that actually changed
|
||||
3. rerun the helper
|
||||
4. commit the completed persistence pass unless the work is deliberately
|
||||
mid-surgery
|
||||
|
||||
After any major completed pass, assume compaction may be imminent even if the
|
||||
user did not say so yet:
|
||||
|
||||
1. run `tools/heimdall_prepare_compaction.py`
|
||||
2. sync only the persistent state that genuinely changed
|
||||
3. rerun the helper
|
||||
4. commit the persistence pass before moving on unless the work is
|
||||
deliberately mid-surgery
|
||||
5. push the current branch to `origin` after the major pass unless the user
|
||||
explicitly says not to publish yet
|
||||
|
||||
## Operating Discipline
|
||||
|
||||
|
|
@ -132,18 +70,17 @@ user did not say so yet:
|
|||
- Do not let app profiles turn into duplicate copies of the shared
|
||||
architecture.
|
||||
- If the diff grows while the boundary gets blurrier, stop and simplify.
|
||||
- Before handoff or compaction, sync `state/map.yaml`, refresh
|
||||
`notes/fresh-workspace-handoff.md`, add distilled evidence when future belief
|
||||
changed, and make the next action explicit.
|
||||
|
||||
## Build And Deploy Target
|
||||
|
||||
Heimdall runs as the auth authority behind Yggdrasil-hosted nginx at
|
||||
`heimdall.gamecult.org`, on Linux. Idunn owns the deployment transaction. This
|
||||
workstation is Windows and is where the shell is, not where the artifact runs:
|
||||
a local compile is not evidence about the Linux release, because toolchain,
|
||||
linker, filesystem semantics and path handling all differ. Build for the
|
||||
target, or let the deploy path's own builder do it, and say which one you used.
|
||||
`heimdall.gamecult.org`, on Linux. `deployment/idunn/recipe.toml` is the target
|
||||
deployment declaration (untested against live Idunn; Yggdrasil still runs the
|
||||
hand-written `heimdall.service`). This workstation is Windows and is where the
|
||||
shell is, not where the artifact runs: a local compile is not evidence about the
|
||||
Linux release, because toolchain, linker, filesystem semantics and path
|
||||
handling all differ. Build for the target, or let the deploy path's own builder
|
||||
do it, and say which one you used.
|
||||
|
||||
## External Context
|
||||
|
||||
|
|
|
|||
|
|
@ -83,7 +83,8 @@ Current app slugs:
|
|||
|
||||
- `repixelizer`
|
||||
- `streampixels`
|
||||
- `spotiverse`
|
||||
- `bifrost`
|
||||
- `ghostlight`
|
||||
|
||||
Profile fields:
|
||||
|
||||
|
|
|
|||
|
|
@ -1,272 +0,0 @@
|
|||
# Fresh Workspace Handoff
|
||||
|
||||
This is the re-entry packet for this repo (path: whatever the checkout is; it has moved drives before).
|
||||
|
||||
It is intentionally short. Historical proof belongs in git history and the
|
||||
distilled `state/evidence.jsonl` ledger; the shared architecture belongs in
|
||||
`docs/architecture.md`; the forward build order belongs in
|
||||
`docs/implementation-plan.md`.
|
||||
|
||||
## Rehydrate
|
||||
|
||||
From the repo root:
|
||||
|
||||
```powershell
|
||||
python .\tools\heimdall_state.py status
|
||||
Get-Content '.\state\map.yaml'
|
||||
Get-Content '.\notes\fresh-workspace-handoff.md'
|
||||
Get-Content '.\docs\architecture.md'
|
||||
Get-Content '.\docs\implementation-plan.md'
|
||||
git status --short --branch
|
||||
git log --oneline -5
|
||||
Get-Content '.\state\evidence.jsonl' -Tail 8
|
||||
```
|
||||
|
||||
Do not trust this file for the exact live HEAD. Always check git.
|
||||
|
||||
## Active Work
|
||||
|
||||
Joystick H1 is merged and live (PR GameCult/Heimdall#1; campaign
|
||||
`joystick:campaign:self`). Next: `joystick:follow_up:h1-joystick-consent-round-trip`, then
|
||||
StreamPixels S0/S1 (other sessions). Open Heimdall follow-ups, by id:
|
||||
`joystick:follow_up:cross-process-failed-refresh-marker`,
|
||||
`joystick:follow_up:connect-start-needs-app-auth`,
|
||||
`joystick:follow_up:heimdall-idunn-onboarding`,
|
||||
`joystick:follow_up:joystick-viewer-signin-public-bot`. The Ghostlight KLTST
|
||||
canaries below stay open, behind them.
|
||||
|
||||
## Current Orientation
|
||||
|
||||
Yggdrasil runs Heimdall `d51fa6b`, hand-deployed 2026-10-19 15:51Z;
|
||||
gamecult-ops `210a1af` records backup, rollback and provenance. Facts below
|
||||
about Odin, Ghostlight and CultLib pins were verified at `1086aee` (2026-08-22)
|
||||
and are not re-verified at `d51fa6b`.
|
||||
|
||||
- At `1086aee01169bf60e8a492b2740db1c6f3e8cabf` Heimdall ran with CultLib
|
||||
`5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9`
|
||||
- Heimdall publishes four redacted access records to Odin under unique keys:
|
||||
`eve:provider:heimdall`, `heimdall:command-boundary`,
|
||||
`eve:plugin:gamecult.heimdall.access`, and `heimdall:transport-profile`
|
||||
- Odin `b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a` persists and returns all four;
|
||||
it does not proxy private commands or receive claims
|
||||
- Ghostlight `b515ca90c25573005a616244143803b37f2d06ec` resolves the boundary through
|
||||
Odin and accepted a live canonical anonymous `heimdall.auth.begin`; its unit
|
||||
has no direct Heimdall endpoint
|
||||
|
||||
- `gamecult.heimdall.access` now has a manifest, advertisement, schemas,
|
||||
fixtures, executable `describe`/`validate`/`project` ABI, and browser
|
||||
reference adapter
|
||||
- Heimdall persists OAuth attempts and serves authenticated
|
||||
`heimdall.auth.begin` / `heimdall.auth.complete` / `heimdall.auth.refresh` /
|
||||
`heimdall.auth.logout` through loopback
|
||||
CultNet/RUDP on port `4101`
|
||||
- private commands are source-runtime, app-secret, expiry, nonce, and
|
||||
idempotency bound; their MessagePack payloads and completion claims are
|
||||
AES-256-GCM wrapped
|
||||
- the Ghostlight app profile now requires its caller-owned Discord role policy;
|
||||
Heimdall evaluates it and Ghostlight remains owner of local sessions,
|
||||
memberships, and campaigns
|
||||
- refresh verifies the exact persisted session revision before reissuing a
|
||||
claim; logout expires that session and advances its revision, so a stale or
|
||||
racing refresh cannot resurrect revoked custody
|
||||
|
||||
- this repo now has a first stateful Heimdall service slice
|
||||
- the canonical shared architecture lives in `docs/architecture.md`
|
||||
- the concrete HTTP/JWKS contract lives in `docs/service-contract.md`
|
||||
- app profiles live under `docs/app-profiles/`
|
||||
- the key boundary is explicit:
|
||||
- Heimdall owns OAuth, linking, managed provider credential custody, grants,
|
||||
entitlement refresh, and signed claim issuance
|
||||
- app-domain data stays app-owned by default
|
||||
- host apps verify signed claims locally for routine auth instead of calling
|
||||
Heimdall on every request
|
||||
- the landed service now exposes:
|
||||
- `/.well-known/jwks.json`
|
||||
- `/.well-known/heimdall-configuration`
|
||||
- `/v1/oauth/{provider}/start`
|
||||
- `/v1/oauth/{provider}/callback`
|
||||
- `/v1/apps/{appSlug}/auth-completions/redeem`
|
||||
- `/v1/apps/{appSlug}/sessions/refresh`
|
||||
- `/v1/apps/{appSlug}/managed-credentials/resolve`
|
||||
- the Discord callback path now performs real code exchange, identity
|
||||
resolution, auth persistence, entitlement evaluation, audit logging, and
|
||||
claim issuance for the Repixelizer slice
|
||||
- browser-style auth handoff now uses a one-time completion code posted back to
|
||||
the opener, with backend redemption instead of fragment-token handoff
|
||||
- same-host or Yggdrasil-reachable app integrations can now ask Heimdall to
|
||||
deliver the auth result directly to an app backend callback endpoint, leaving
|
||||
the browser with only status/attempt signaling
|
||||
- signing keys can now load from a persisted file path and bootstrap that file
|
||||
on first boot when explicitly enabled
|
||||
- managed provider tokens are now sealed at rest with AES-256-GCM instead of
|
||||
being dumped into "encrypted" columns raw like an insult
|
||||
- `src/verifier.ts` now provides a small local JWT verifier seam for app
|
||||
backends
|
||||
- Repixelizer has consumed the backend-callback flow in its hosted web layer:
|
||||
it creates local auth attempts, asks Heimdall to start OAuth, receives the
|
||||
direct backend callback, verifies Heimdall Ed25519 access tokens locally, and
|
||||
adopts httpOnly local sessions
|
||||
- Heimdall is now deployed on Yggdrasil at `https://heimdall.gamecult.org`
|
||||
behind nginx/TLS with Postgres storage, file-backed signing-key bootstrap,
|
||||
configured token custody, and public health/discovery/JWKS checks passing
|
||||
- Repixelizer is now deployed on Yggdrasil at
|
||||
`https://repixelizer.gamecult.org` with Heimdall mode enabled, Discord and
|
||||
Patreon as public providers, required access enabled, and queue protection
|
||||
enabled
|
||||
- Repixelizer public auth-start returns Discord and Patreon authorization URLs
|
||||
using the Heimdall callback and Repixelizer backend handoff
|
||||
- Repixelizer auth now has a refresh path: Heimdall issues signed refresh
|
||||
tokens with access claims, `/v1/apps/{appSlug}/sessions/refresh` reissues
|
||||
short-lived access claims, and Discord/Patreon provider tokens refresh inside
|
||||
Heimdall before entitlement re-evaluation
|
||||
- Twitch and YouTube now have generic OAuth exchange and identity runtimes
|
||||
- GitHub is still catalogued, but its callback runtime is not implemented
|
||||
- StreamPixels now delegates viewer and creator Twitch/YouTube OAuth to
|
||||
Heimdall, redeems Heimdall completion codes server-side, writes its own
|
||||
viewer sessions and connector bindings, and resolves current provider access
|
||||
tokens from Heimdall without storing refresh tokens locally
|
||||
- Spotiverse now delegates Spotify OAuth to Heimdall. Heimdall has a
|
||||
`spotiverse` app profile and `spotify` provider runtime; Spotiverse stores a
|
||||
local Heimdall account binding and resolves current Spotify access through
|
||||
`/v1/apps/spotiverse/managed-credentials/resolve` without storing provider
|
||||
refresh tokens.
|
||||
- Bifrost now has a `bifrost` app profile for Discord/Patreon member access.
|
||||
Bifrost sends caller-owned KTLST Discord role and Patreon tier policies
|
||||
through trusted backend-callback OAuth starts; Heimdall owns provider
|
||||
OAuth/token custody and configured backend callback allowlisting.
|
||||
- Bifrost patron support sync now reuses Heimdall's existing linked Patreon
|
||||
identity and membership reader. `POST /v1/apps/bifrost/patron-support/sync`
|
||||
is app-authenticated, refreshes the stored Patreon credential if needed,
|
||||
reads active paid Patreon tier evidence, and emits a signed
|
||||
`RecurringSupportSnapshot` to Bifrost's
|
||||
`/heimdall/patron-support/events` intake.
|
||||
- Public Yggdrasil Heimdall has been deployed with the Spotiverse/Spotify code
|
||||
path, Spotify provider credentials, a Spotiverse shared secret, and an
|
||||
allowlisted loopback portal callback at
|
||||
`http://127.0.0.1:18796/auth/heimdall/callback`.
|
||||
- Heimdall and StreamPixels are deployed on Yggdrasil for the StreamPixels
|
||||
migration slice; Twitch callback handling has been patched so provider token
|
||||
`scope` can be either a space-delimited string or an array
|
||||
- live StreamPixels Twitch sign-in through Heimdall has succeeded on Yggdrasil
|
||||
and Heimdall audit showed callback success, completion creation, and
|
||||
completion redemption
|
||||
- the ignored local `secrets/heimdall-service.env` artifact now has
|
||||
`GC_ACCESS_PROVIDER_TWITCH_*` and `GC_ACCESS_PROVIDER_YOUTUBE_*` populated
|
||||
for the StreamPixels migration slice
|
||||
- the intended first deployment shape is a Heimdall service on Yggdrasil behind
|
||||
nginx, not an embedded cross-runtime shared library fantasy
|
||||
- Heimdall now writes a daemon-owned boundary witness store at
|
||||
`GC_ACCESS_CULTCACHE_PATH` containing provider advertisement, command
|
||||
boundary, transport profile, and daemon-health summary state
|
||||
- Heimdall can now publish `heimdall.cultnet-rudp-provider-health` to Idunn
|
||||
over `cultnet.transport.rudp.v0` when `GC_ACCESS_IDUNN_RUDP_HEALTH` is
|
||||
configured; HTTP `/healthz`, JWKS, discovery, systemd, and nginx routing
|
||||
remain compatibility witnesses
|
||||
- Since `1086aee` Heimdall persists its private
|
||||
provider-health identity at `/srv/heimdall/keys/provider-health-identity.cc`
|
||||
and publishes canonical signed health independently of the slower Verse
|
||||
snapshot cadence. Idunn owns the exact root trust binding, authenticated
|
||||
admission, lifecycle decision, and redacted public `.cc` projection.
|
||||
- Odin commit `b4f9a2e95f0b41cebdeddc49223781d1d3c7b42a` retains the RUDP health
|
||||
reliability cut and registers Heimdall's command-boundary, plugin, and
|
||||
transport schemas so the typed catalog can persist rather than silently drop
|
||||
them. Live proof returned all four exact Heimdall records.
|
||||
|
||||
## Critical Doctrine
|
||||
|
||||
- Persistent state is the agent's mind.
|
||||
- Cut stale architecture notes as ruthlessly as stale code.
|
||||
- Do not mistake "shared auth" for "shared database."
|
||||
- Do not mistake "shared auth service" for "every guarded route must call the
|
||||
mothership."
|
||||
- If compaction hits before boundary findings are persisted, that work is gone.
|
||||
Re-gather it instead of pretending continuity happened.
|
||||
|
||||
## Next Real Move
|
||||
|
||||
The Active Work follow-ups first. Everything below is the standing queue.
|
||||
|
||||
Do not continue implementation automatically from a rehydrate-only request.
|
||||
|
||||
The Idunn/swarm health transport cut is live. Do not regress Heimdall to
|
||||
unsigned `idunn.daemon_health`, merge its private key into Idunn, or make HTTP
|
||||
health an authority. The next product work is the Bifrost and remaining browser
|
||||
verification listed below.
|
||||
|
||||
The active Ghostlight deployment cut is complete. The next Ghostlight work is a
|
||||
real separate-account KLTST completion/refresh/logout canary, followed by the
|
||||
eight-account Session Zero privacy and actor-binding smoke. Keep port `4101`
|
||||
loopback-only and treat any claim, token, completion, app secret, or account
|
||||
state in Odin/CultMesh/browser output as a release-blocking fault.
|
||||
|
||||
If the user asks to continue on Spotiverse, the current next move is the real
|
||||
browser `/auth/login` flow through public Heimdall. The Yggdrasil SSH tunnel
|
||||
must include reverse forward
|
||||
`spotiverse-callback:18796:127.0.0.1:8796`, and local Spotiverse must point at
|
||||
`https://heimdall.gamecult.org` with the matching `HEIMDALL_APP_SECRET`. Verify
|
||||
managed credential resolution after login. Spotiverse should not regain local
|
||||
Spotify OAuth token storage.
|
||||
|
||||
If the user asks to continue on StreamPixels, the current next move is real
|
||||
browser verification:
|
||||
|
||||
- verify viewer claim/link through `https://streampixels.gamecult.org/auth/connect`
|
||||
- Twitch viewer sign-in has already passed once; continue with YouTube and
|
||||
connector attachment verification
|
||||
- verify creator connector attach from an admin creator session
|
||||
- confirm StreamPixels persists local profile/connector binding state while
|
||||
Heimdall retains provider token custody
|
||||
- if a provider callback fails, inspect Heimdall audit events and StreamPixels
|
||||
service logs before touching app/domain boundaries
|
||||
|
||||
Repixelizer still needs its real browser OAuth verification:
|
||||
|
||||
- open `https://repixelizer.gamecult.org/app/`
|
||||
- start Discord sign-in with an account that has the `KLTST` or
|
||||
Patreon-synced `Inner Sanctum` role, or Patreon sign-in with a currently
|
||||
entitled tier titled `Inner Sanctum`
|
||||
- confirm Repixelizer sends its app-owned provider policy in the
|
||||
backend-callback OAuth start
|
||||
- confirm Heimdall receives the provider callback and evaluates entitlement
|
||||
- confirm Repixelizer receives the backend callback, verifies the Heimdall
|
||||
token, adopts a local httpOnly session, and gates hosted/queue routes
|
||||
- confirm the Discord authorization URL requests only `identify
|
||||
guilds.members.read`
|
||||
|
||||
Launch policy is role-gated on purpose: the GameCult Discord can remain public,
|
||||
but Repixelizer access is limited to members with either `KLTST` or the
|
||||
Patreon-synced `Inner Sanctum` role. Repixelizer owns that role policy through
|
||||
its own runtime env and sends it to Heimdall during backend-callback OAuth
|
||||
start; Heimdall owns provider OAuth mechanics and claim issuance, not the
|
||||
per-app role list.
|
||||
|
||||
Patreon access is title-gated on the currently entitled tier title
|
||||
`Inner Sanctum`; do not use currency amount as the durable policy because
|
||||
currencies are weird little traps.
|
||||
|
||||
Bifrost needs browser verification after deployment:
|
||||
|
||||
- configure Heimdall with
|
||||
`GC_ACCESS_APP_BIFROST_BACKEND_CALLBACK_URLS=https://bifrost.gamecult.org/auth/heimdall/callback`
|
||||
- configure Heimdall with `GC_ACCESS_APP_BIFROST_SHARED_SECRET_FILE`,
|
||||
`GC_ACCESS_BIFROST_PATRON_SUPPORT_ENDPOINT=https://bifrost.gamecult.org/heimdall/patron-support/events`,
|
||||
and `GC_ACCESS_BIFROST_PATRON_SUPPORT_SECRET_FILE`, each naming a credential
|
||||
file
|
||||
- configure Bifrost with `Heimdall__DiscordGuildId`,
|
||||
`Heimdall__DiscordAllowedRoleIds__0=<KTLST-role-id>`, and
|
||||
`Heimdall__PatreonTierTitle=Inner Sanctum`
|
||||
- configure Bifrost with the matching `Heimdall__PatronSupportIntakeSecret`
|
||||
- start Discord sign-in from `https://bifrost.gamecult.org/` with a user that
|
||||
has the KTLST cult-member role
|
||||
- start Patreon sign-in with a user that has the configured active tier
|
||||
- confirm Bifrost creates/updates a local account and active standard
|
||||
membership while Heimdall keeps provider token custody
|
||||
- trigger `/v1/apps/bifrost/patron-support/sync` for that linked Heimdall
|
||||
account and confirm Bifrost records a Patreon recurring-support snapshot
|
||||
without owning Patreon webhook or token custody
|
||||
|
||||
## Immediate Re-entry Instruction
|
||||
|
||||
After compaction, first rehydrate and reorient from the listed files and git
|
||||
state. Wait for the user's next instruction unless they explicitly say to
|
||||
continue.
|
||||
|
|
@ -1,241 +0,0 @@
|
|||
{
|
||||
"kind": "cut_spec",
|
||||
"value": {
|
||||
"campaign": "ghostlight-verse",
|
||||
"cut": "heimdall-ghostlight-google",
|
||||
"revision": 1,
|
||||
"title": "Heimdall: ghostlight admits Google, honours the Dungeon's invite grant, and stops gating on the Discord role",
|
||||
"repo": "GameCult/Heimdall",
|
||||
"branch": "ghostlight/google-sign-in",
|
||||
"base": "2bcb2ca4e7fb640e07deae42302b0919a62e5bc4",
|
||||
"depends_on": [],
|
||||
"first": [
|
||||
"Work in the existing worktree F:\\Projects\\Heimdall-wt-ghostlight-google on branch ghostlight/google-sign-in (from origin/main 2bcb2ca). Read AGENTS.md; follow its state/evidence conventions for the closing evidence line.",
|
||||
"Read docs/service-contract.md 'Invite grant' (about line 264) and src/app.ts startOAuthFlow gates (about lines 832-846): the grant mechanism already exists for bifrost. This cut extends it to ghostlight and threads it through the private command plane; it adds no invite records to Heimdall.",
|
||||
"Delete first: AppProfile.requiredEntitlementPolicyKind (app-profiles.ts:41-47, set only by ghostlight at :203) and requireEntitlementPolicyIfProfileDemandsIt (private-command-plane.ts:385-407) with its two call sites (:236 refresh, :272 begin). A caller-sent policy stays accepted and optional as for every other app.",
|
||||
"Heimdall ruling heimdall-body:ruling:bifrost-google-invitation-link-only forbids attaching Google to an existing account by an invitation path. This cut does not: the grant only mints a new account for a sub no account holds and never attaches (contract text at :264-274). Do not widen that.",
|
||||
"Open the Heimdall PR on Forgejo only when Self says so; the brief for this mapping pass forbids it, Hands' own brief decides."
|
||||
],
|
||||
"deletes": [
|
||||
{
|
||||
"path": "src/app-profiles.ts",
|
||||
"lines": 8,
|
||||
"note": "requiredEntitlementPolicyKind field and its doc comment; ghostlight's requiredEntitlementPolicyKind line"
|
||||
},
|
||||
{
|
||||
"path": "src/private-command-plane.ts",
|
||||
"lines": 22,
|
||||
"note": "requireEntitlementPolicyIfProfileDemandsIt and its two awaits"
|
||||
},
|
||||
{
|
||||
"path": "tests",
|
||||
"lines": 30,
|
||||
"note": "tests that pin 'ghostlight authentication/refresh requires its caller-owned discord_role_access policy' are deleted or inverted (a ghostlight begin without policy now starts)"
|
||||
}
|
||||
],
|
||||
"keeps_moves": [
|
||||
"The grant gates in startOAuthFlow (app caller of this slug, sign_in only, mayGrantFirstLogin) and the callback mint under first_login_grant are unchanged.",
|
||||
"Bifrost's profile, its grant and its Google link flow are unchanged.",
|
||||
"The private-plane attempt handle (trustedBrowserAttemptId, never body-supplied) is the ghostlight browser binding and is unchanged.",
|
||||
"Discord stays a ghostlight identity provider; a Discord policy a caller still sends is evaluated by nobody for ghostlight (entitlementSources empty) and is harmless."
|
||||
],
|
||||
"adds": [
|
||||
"ghostlight profile: identityProviders ['discord','google']; entitlementSources []; startRequiresAppCaller: true; mayGrantFirstLogin: true; profileVersion '2026-12-02'.",
|
||||
"ghostlight app_access: anyOf [identityFacts.authenticated] (as streampixels viewer_access at :147), summary 'Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog'. campaign_play summary/localRequirement: 'Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership'.",
|
||||
"beginAuth reads payload.firstLoginGrant: absent/null -> none; exactly 'invite' -> passed to startOAuthFlow input.firstLoginGrant; any other value -> throw 'Auth begin payload is incomplete.' (same refusal shape as a bad provider). startOAuthFlow's existing gate then decides."
|
||||
],
|
||||
"file_changes": [
|
||||
{
|
||||
"location": {
|
||||
"path": "src/app-profiles.ts",
|
||||
"line": 195,
|
||||
"end_line": 218,
|
||||
"symbol": "ghostlightProfile"
|
||||
},
|
||||
"change": "As in adds: providers, entitlementSources [], startRequiresAppCaller, mayGrantFirstLogin, app_access on identity.authenticated, summaries, profileVersion. Import identityFacts is already present."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "src/private-command-plane.ts",
|
||||
"line": 260,
|
||||
"end_line": null,
|
||||
"symbol": "beginAuth"
|
||||
},
|
||||
"change": "Thread firstLoginGrant into the startOAuthFlow input; drop the policy-demand await."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "src/private-command-plane.ts",
|
||||
"line": 221,
|
||||
"end_line": null,
|
||||
"symbol": "refreshAuth"
|
||||
},
|
||||
"change": "Drop the policy-demand await; policy remains optional and passed through when present."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "schemas/heimdall.auth_begin_command.v1.schema.json",
|
||||
"line": 1,
|
||||
"end_line": null
|
||||
},
|
||||
"change": "provider enum gains google; entitlementPolicy leaves required; add firstLoginGrant {enum:['invite']}."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "schemas/heimdall.auth_refresh_command.v1.schema.json",
|
||||
"line": 1,
|
||||
"end_line": null
|
||||
},
|
||||
"change": "entitlementPolicy optional if it is required there."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "docs/service-contract.md",
|
||||
"line": 190,
|
||||
"end_line": null
|
||||
},
|
||||
"change": "startRequiresAppCaller: 'Bifrost and Ghostlight'; mayGrantFirstLogin (about :264): 'bifrost and ghostlight'; Google (about :289): admitted to bifrost and ghostlight; private-plane begin accepts firstLoginGrant 'invite'."
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "docs/app-profiles/ghostlight.md",
|
||||
"line": 1,
|
||||
"end_line": null
|
||||
},
|
||||
"change": "Providers Discord and Google; access rule: Heimdall authenticates, app_access is identity.authenticated, admission is the Dungeon's catalog and one-time invites (ruling dungeon-owns-accounts); a first Google sign-in mints a Heimdall account only under the Dungeon's grant; no Discord role policy; refresh re-evaluates nothing app-specific."
|
||||
}
|
||||
],
|
||||
"reads": [
|
||||
{
|
||||
"location": {
|
||||
"path": "src/app.ts",
|
||||
"line": 832,
|
||||
"end_line": null,
|
||||
"symbol": "startOAuthFlow"
|
||||
},
|
||||
"why": "the app-caller and grant gates the private plane now reaches with a grant"
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "src/app.ts",
|
||||
"line": 2034,
|
||||
"end_line": null
|
||||
},
|
||||
"why": "callback: requires_link + first_login_grant mints and audits account_minted_by_grant"
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "tests/google-link.test.ts",
|
||||
"line": 1,
|
||||
"end_line": null
|
||||
},
|
||||
"why": "the bifrost grant tests to mirror for ghostlight over the private plane"
|
||||
},
|
||||
{
|
||||
"location": {
|
||||
"path": "tests/caller-identity-soul.test.ts",
|
||||
"line": 23,
|
||||
"end_line": null
|
||||
},
|
||||
"why": "private-plane ghostlight fixtures (ghostlightSecret, runtime ids)"
|
||||
}
|
||||
],
|
||||
"authority_map": {
|
||||
"owner": "The Dungeon's account catalog (catalog.cc) owns admission: an identity plays if an account holds it, or if it redeems a live one-time Dungeon invite, consumed in the write that creates the account. Heimdall owns authentication only: it proves which external identity signed in and names the Heimdall account (claim sub) that identity belongs to.",
|
||||
"inputs": [
|
||||
"Dungeon: the invite the browser presents at begin, its catalog, the Heimdall-verified claim at complete",
|
||||
"Heimdall: the app-authenticated begin (ghostlight secret over the private plane), the provider's OIDC/OAuth answer, the signed state"
|
||||
],
|
||||
"outputs": [
|
||||
"Dungeon -> Heimdall: firstLoginGrant 'invite' on a begin whose browser presented an invite the catalog holds live",
|
||||
"Heimdall -> Dungeon: a claim aud=ghostlight with app_access for every authenticated identity",
|
||||
"Dungeon: an account row, the spent invite, an app session"
|
||||
],
|
||||
"derived_state": [
|
||||
"Heimdall's first_login_grant is no longer an invite: it is derived from the Dungeon's live invite at begin and is notification-only (it lets Heimdall mint an auth account for a Google sub no account holds)",
|
||||
"ghostlight app_access is no longer an admission gate: it is derived from identity.authenticated; the Dungeon's app_access checks become claim-shape checks that cannot refuse an authenticated sign-in",
|
||||
"the invite bound to an attempt in AuthGuard is a copy of what the browser presented at begin, memory-only, living no longer than the begin cookie"
|
||||
],
|
||||
"forbidden_writers": [
|
||||
"Heimdall's Discord role policy (requiredEntitlementPolicyKind, entitlementSources discord) no longer decides who enters the Dungeon",
|
||||
"Heimdall holds no invite records for ghostlight and never decides who is invited",
|
||||
"the complete body no longer carries an invite; only the begin-bound invite reaches catalog.sign_in",
|
||||
"no public (secretless) ghostlight OAuth start: startRequiresAppCaller"
|
||||
],
|
||||
"shared_paths": [
|
||||
"Google, Discord and any later provider begin through one auth_begin -> HeimdallClient::begin -> heimdall.auth.begin path; the grant decision is the same catalog read for every provider",
|
||||
"every sign-in, first or returning, any provider, ends in one catalog.sign_in"
|
||||
],
|
||||
"deletion_line": "Delete before adding: Heimdall's requiredEntitlementPolicyKind field and requireEntitlementPolicyIfProfileDemandsIt; the Dungeon's DiscordGate, its two env names and the policy on begin and refresh; the complete body's invite field."
|
||||
},
|
||||
"verification": {
|
||||
"builds": [
|
||||
"pnpm typecheck && pnpm test in the worktree (vendor/CultLib built as AGENTS.md says); report the pre-existing odin-publication failure separately if it still appears"
|
||||
],
|
||||
"tests": [
|
||||
{
|
||||
"name": "ghostlight google first sign-in under grant",
|
||||
"pins": "private-plane begin {provider google, firstLoginGrant invite} -> 201 state with first_login_grant; callback with an unheld sub mints one account and audits account_minted_by_grant {provider google, appSlug ghostlight}; the completion's claim carries app_access"
|
||||
},
|
||||
{
|
||||
"name": "ghostlight google first sign-in without grant",
|
||||
"pins": "same begin without firstLoginGrant -> callback refuses identity_not_linked and mints nothing"
|
||||
},
|
||||
{
|
||||
"name": "returning google identity",
|
||||
"pins": "a sub an account already holds signs in with or without the grant to that same account; the grant attaches nothing"
|
||||
},
|
||||
{
|
||||
"name": "discord without policy",
|
||||
"pins": "private-plane ghostlight discord begin with no entitlementPolicy starts (no throw); refresh without policy refreshes; claim carries app_access"
|
||||
},
|
||||
{
|
||||
"name": "public ghostlight start refused",
|
||||
"pins": "POST /v1/oauth/google/start and /v1/oauth/discord/start for appSlug ghostlight without x-heimdall-app-secret -> 401 app_auth_required"
|
||||
},
|
||||
{
|
||||
"name": "bad grant value",
|
||||
"pins": "private-plane begin with firstLoginGrant 'yes' is refused before any attempt row or state is minted"
|
||||
},
|
||||
{
|
||||
"name": "other apps unchanged",
|
||||
"pins": "repixelizer/streampixels public starts unchanged; firstLoginGrant from repixelizer still 400 first_login_grant_refused"
|
||||
}
|
||||
],
|
||||
"negative": [
|
||||
{
|
||||
"pattern": "requiredEntitlementPolicyKind|requireEntitlementPolicyIfProfileDemandsIt",
|
||||
"scope": "src, tests, docs: zero hits"
|
||||
},
|
||||
{
|
||||
"pattern": "discord_role_access",
|
||||
"scope": "src/app-profiles.ts: zero hits (the policy kind itself stays in contracts and the Discord evaluator)"
|
||||
},
|
||||
{
|
||||
"pattern": "invite",
|
||||
"scope": "src/store/**: no new table, column or row for ghostlight invites"
|
||||
}
|
||||
],
|
||||
"operator": [
|
||||
"Deploy is cut ops-google-sign-in's runbook section, after this merges to Heimdall main; not part of this cut."
|
||||
]
|
||||
},
|
||||
"estimate": {
|
||||
"lines_added": 140,
|
||||
"lines_removed": 70,
|
||||
"dependencies_added": [],
|
||||
"dependencies_removed": [],
|
||||
"formats_added": [],
|
||||
"formats_removed": [],
|
||||
"targets_added": [],
|
||||
"targets_removed": []
|
||||
},
|
||||
"rulings": [
|
||||
"ghostlight-verse:ruling:weksa-owns-dungeon-google-sign-in",
|
||||
"ghostlight-verse:ruling:dungeon-owns-accounts"
|
||||
],
|
||||
"questions": [
|
||||
"ghostlight-verse:question:heimdall-ghostlight-google-twitch-sign-in"
|
||||
]
|
||||
}
|
||||
}
|
||||
161
src/verifier.ts
161
src/verifier.ts
|
|
@ -1,161 +0,0 @@
|
|||
import { createPublicKey, type KeyObject } from "node:crypto";
|
||||
import { isAppSlug, providers, type AccessClaimPayload, type AppSlug, type LinkedIdentityInput, type Provider } from "./contracts.js";
|
||||
import { type PublicSigningJwk, verifyJwt } from "./signing.js";
|
||||
|
||||
export interface HeimdallVerifierOptions {
|
||||
issuer: string;
|
||||
appSlug: AppSlug;
|
||||
jwks: {
|
||||
keys: PublicSigningJwk[];
|
||||
};
|
||||
allowedClockSkewSeconds?: number;
|
||||
}
|
||||
|
||||
export type VerifyAccessTokenResult =
|
||||
| {
|
||||
valid: true;
|
||||
header: Record<string, unknown>;
|
||||
claimSet: AccessClaimPayload;
|
||||
}
|
||||
| {
|
||||
valid: false;
|
||||
error: string;
|
||||
};
|
||||
|
||||
function isLinkedIdentity(value: unknown): value is LinkedIdentityInput {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const record = value as Record<string, unknown>;
|
||||
if (
|
||||
typeof record.provider !== "string" ||
|
||||
!providers.includes(record.provider as Provider) ||
|
||||
typeof record.providerUserId !== "string"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (record.username !== undefined && typeof record.username !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (record.displayName !== undefined && typeof record.displayName !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function parseAccessClaimPayload(payload: Record<string, unknown>): AccessClaimPayload | null {
|
||||
if (
|
||||
payload.typ !== "heimdall_access" ||
|
||||
typeof payload.iss !== "string" ||
|
||||
typeof payload.aud !== "string" ||
|
||||
!isAppSlug(payload.aud) ||
|
||||
typeof payload.sub !== "string" ||
|
||||
typeof payload.sid !== "string" ||
|
||||
typeof payload.jti !== "string" ||
|
||||
typeof payload.iat !== "number" ||
|
||||
typeof payload.nbf !== "number" ||
|
||||
typeof payload.exp !== "number" ||
|
||||
typeof payload.account_id !== "string" ||
|
||||
typeof payload.access_revision !== "number" ||
|
||||
!payload.app ||
|
||||
typeof payload.app !== "object" ||
|
||||
typeof (payload.app as Record<string, unknown>).slug !== "string" ||
|
||||
!isAppSlug((payload.app as Record<string, unknown>).slug) ||
|
||||
typeof (payload.app as Record<string, unknown>).profile_version !== "string" ||
|
||||
!Array.isArray(payload.facts) ||
|
||||
!payload.facts.every((fact) => typeof fact === "string") ||
|
||||
!Array.isArray(payload.capabilities) ||
|
||||
!payload.capabilities.every((capability) => typeof capability === "string") ||
|
||||
!Array.isArray(payload.identities) ||
|
||||
!payload.identities.every(isLinkedIdentity)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (payload.display_name !== undefined && typeof payload.display_name !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return payload as unknown as AccessClaimPayload;
|
||||
}
|
||||
|
||||
function buildKeyIndex(jwks: { keys: PublicSigningJwk[] }): Map<string, KeyObject> {
|
||||
return new Map(
|
||||
jwks.keys.map((jwk) => [
|
||||
jwk.kid,
|
||||
createPublicKey({
|
||||
key: jwk,
|
||||
format: "jwk",
|
||||
}),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
export function createHeimdallAccessTokenVerifier(options: HeimdallVerifierOptions): {
|
||||
verify(token: string, now?: Date): VerifyAccessTokenResult;
|
||||
} {
|
||||
const keyIndex = buildKeyIndex(options.jwks);
|
||||
const allowedClockSkewSeconds = Math.max(0, Math.trunc(options.allowedClockSkewSeconds ?? 30));
|
||||
|
||||
return {
|
||||
verify(token: string, now = new Date()): VerifyAccessTokenResult {
|
||||
const [encodedHeader] = token.split(".");
|
||||
if (!encodedHeader) {
|
||||
return { valid: false, error: "Malformed JWT." };
|
||||
}
|
||||
|
||||
let header: Record<string, unknown>;
|
||||
try {
|
||||
header = JSON.parse(Buffer.from(encodedHeader, "base64url").toString("utf8")) as Record<string, unknown>;
|
||||
} catch {
|
||||
return { valid: false, error: "Malformed JWT header." };
|
||||
}
|
||||
|
||||
if (header.alg !== "EdDSA" || typeof header.kid !== "string") {
|
||||
return { valid: false, error: "Unsupported JWT signing header." };
|
||||
}
|
||||
|
||||
const publicKey = keyIndex.get(header.kid);
|
||||
if (!publicKey) {
|
||||
return { valid: false, error: `Unknown signing key id '${header.kid}'.` };
|
||||
}
|
||||
|
||||
const verified = verifyJwt(token, publicKey);
|
||||
if (!verified.valid) {
|
||||
return verified;
|
||||
}
|
||||
|
||||
const claimSet = parseAccessClaimPayload(verified.payload);
|
||||
if (!claimSet) {
|
||||
return { valid: false, error: "JWT payload is not a valid Heimdall access claim." };
|
||||
}
|
||||
|
||||
if (claimSet.iss !== options.issuer) {
|
||||
return { valid: false, error: "JWT issuer does not match the configured Heimdall issuer." };
|
||||
}
|
||||
|
||||
if (claimSet.aud !== options.appSlug || claimSet.app.slug !== options.appSlug) {
|
||||
return { valid: false, error: "JWT audience does not match the expected app slug." };
|
||||
}
|
||||
|
||||
const nowEpochSeconds = Math.floor(now.getTime() / 1000);
|
||||
if (claimSet.nbf > nowEpochSeconds + allowedClockSkewSeconds) {
|
||||
return { valid: false, error: "JWT is not valid yet." };
|
||||
}
|
||||
|
||||
if (claimSet.exp <= nowEpochSeconds - allowedClockSkewSeconds) {
|
||||
return { valid: false, error: "JWT has expired." };
|
||||
}
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
header: verified.header,
|
||||
claimSet,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
{
|
||||
"branches": [
|
||||
{
|
||||
"id": "main",
|
||||
"hypothesis": "A shared Heimdall authority service on Yggdrasil can be reused across hosted experiments if OAuth, sessions, grants, and capability machinery are centralized while app-domain data and routine route authorization stay app-local.",
|
||||
"status": "active",
|
||||
"artifacts": [
|
||||
"state/map.yaml",
|
||||
"state/scratch.md",
|
||||
"state/evidence.jsonl",
|
||||
"docs/architecture.md",
|
||||
"docs/implementation-plan.md"
|
||||
],
|
||||
"notes": "Current mainline. Repixelizer is the first auth-blank binding target; StreamPixels is the migration and boundary stress test."
|
||||
},
|
||||
{
|
||||
"id": "eureka/joystick-h1",
|
||||
"hypothesis": "One locked refresh primitive plus a Joystick OAuth provider in Heimdall lets StreamPixels ingest Joystick without ever presenting a provider refresh token.",
|
||||
"status": "accepted",
|
||||
"artifacts": [
|
||||
"state/map.yaml"
|
||||
],
|
||||
"notes": "Merged as PR GameCult/Heimdall#1 (d51fa6b), deployed to Yggdrasil 2026-10-19 15:51Z; gamecult-ops 210a1af. Campaign joystick:campaign:self."
|
||||
}
|
||||
]
|
||||
}
|
||||
130
state/map.yaml
130
state/map.yaml
|
|
@ -1,130 +0,0 @@
|
|||
project:
|
||||
name: Heimdall
|
||||
status: active
|
||||
phase: streampixels_migration
|
||||
premise: >
|
||||
Build Heimdall as one reusable GameCult auth authority service for OAuth,
|
||||
linked identities, local sessions, grants, and capability claims without
|
||||
mixing in app-domain audience or product data.
|
||||
|
||||
objective:
|
||||
primary: >
|
||||
Create a shared auth authority service that Repixelizer, StreamPixels, and
|
||||
future GameCult-hosted experiments can consume.
|
||||
current: >
|
||||
Publish the Heimdall Eve access plugin and private CultNet authentication
|
||||
plane, then migrate Ghostlight onto app-local sessions without moving
|
||||
campaign or membership authority into Heimdall.
|
||||
|
||||
constraints:
|
||||
- Heimdall owns auth/control-plane authority; app-domain data stays app-owned by default.
|
||||
- Prefer a same-host Heimdall service on Yggdrasil over duplicated per-app provider stacks.
|
||||
- Host apps verify signed claims locally for routine guarded routes.
|
||||
- App profiles stay thin; the shared architecture note owns the main model.
|
||||
- StreamPixels audience and creator data must not be absorbed into a shared auth store.
|
||||
|
||||
invariants:
|
||||
- The map is canonical and slow-changing.
|
||||
- Scratch is temporary and disposable.
|
||||
- Evidence is durable and distilled; routine activity logs belong in git history and commit messages.
|
||||
- Heimdall owns OAuth, local sessions, grants, entitlement refresh, capability evaluation, and audit surfaces.
|
||||
- App-domain data stays with the host app unless there is a deliberate, source-grounded reason to share it.
|
||||
- Host apps verify signed claims locally and keep resource ownership checks local.
|
||||
- StreamPixels can reuse shared auth authority without centralizing streamer-audience data.
|
||||
- Spotiverse consumes Spotify as a Heimdall-managed credential; Spotiverse does not own Spotify refresh-token custody.
|
||||
- Heimdall's first Odin/Eve daemon boundary publication remains secret-safe: it writes only provider advertisement, command boundary, transport profile, and daemon-health summary state, not per-account auth truth.
|
||||
- Heimdall owns its persistent provider-health signing identity and signed observations; Idunn owns root-bound admission and the public provider-health projection. Unsigned health is never lifecycle authority.
|
||||
- Heimdall owns OAuth attempts and completion redemption; the Eve access plugin and browser can project or carry one opaque handle but cannot grant access.
|
||||
- Private auth commands are app-secret, source-runtime, expiry, nonce, and idempotency bound; sensitive completion claims remain AES-GCM wrapped until the app backend receives them.
|
||||
- Refresh and logout are exact persisted-session transitions. App/account custody and access revision must match; logout advances the revision and stale refresh cannot recreate the session.
|
||||
- Persistent state cruft is the same failure class as architecture cruft.
|
||||
|
||||
data_flow:
|
||||
observe:
|
||||
- task request
|
||||
- shared architecture note
|
||||
- app profile bindings
|
||||
- current app/runtime seams in Repixelizer and StreamPixels
|
||||
- Yggdrasil host topology and nginx/service shape
|
||||
process:
|
||||
- rehydrate from canonical state
|
||||
- choose one bounded architecture or implementation slice
|
||||
- keep auth authority and app-domain data boundaries explicit
|
||||
- keep routine route auth local after claim verification
|
||||
- record only belief-changing evidence
|
||||
- commit or backtrack
|
||||
cut:
|
||||
- reject shared-data creep
|
||||
- reject duplicated auth blobs per app
|
||||
- reject per-request auth round-trip chatter
|
||||
|
||||
active_subgoals:
|
||||
- Joystick H1 is merged and live (PR GameCult/Heimdall#1, d51fa6b; campaign joystick:campaign:self). Open follow-ups by id: joystick:follow_up:h1-joystick-consent-round-trip (next), cross-process-failed-refresh-marker, connect-start-needs-app-auth, heimdall-idunn-onboarding, joystick-viewer-signin-public-bot. StreamPixels S0/S1 run in other sessions.
|
||||
- OPEN, behind the H1 live round-trips: pressure the deployed Ghostlight gamecult.heimdall.access integration with two- and eight-account human canaries.
|
||||
- Keep the shared architecture explicit and separate from app profiles.
|
||||
- Preserve the default boundary that app-domain data remains app-owned.
|
||||
- Align the plan to Heimdall as a Yggdrasil-hosted authority service.
|
||||
- Publish Heimdall daemon health and boundary state for Idunn/Odin without moving auth truth out of Heimdall.
|
||||
- Verify the Discord and Patreon Repixelizer auth paths with real provider credentials, stable signing, persistent storage, and live browser callback verification.
|
||||
- Wire StreamPixels through Heimdall for Twitch/YouTube (Joystick joins under H1) viewer identity and managed creator-provider credentials without moving StreamPixels domain state into Heimdall.
|
||||
|
||||
accepted_design:
|
||||
- `gamecult.heimdall.access` owns access-gate representation and browser navigation semantics; it has no access-grant or provider-state authority.
|
||||
- Heimdall's loopback CultNet operation service owns authenticated auth begin/complete commands, while retained HTTP integrations remain supported for existing consumers.
|
||||
- Ghostlight refresh and logout use the same private CultNet boundary; refresh re-evaluates the caller-owned KLTST policy and logout revokes exact Heimdall session custody.
|
||||
- `docs/architecture.md` is the canonical shared architecture note.
|
||||
- `docs/service-contract.md` records the concrete HTTP/JWKS contract of the landed service slice.
|
||||
- `docs/app-profiles/*.md` are thin app bindings, not duplicate brains.
|
||||
- Heimdall owns provider OAuth, identity linking, signed local sessions, grants, entitlement refresh, capability evaluation, and audit events.
|
||||
- Host apps own their domain data, runtime state, and product-specific resources.
|
||||
- Host apps verify signed claims locally for routine route authorization.
|
||||
- A shared Heimdall store, if it exists, should hold auth/control-plane truth only.
|
||||
- Repixelizer is the first auth-blank hosted-app binding.
|
||||
- StreamPixels is the migration case that proves shared authority must not imply audience-data centralization.
|
||||
- The first service skeleton is a standalone TypeScript/Fastify app with Ed25519 JWT signing, JWKS discovery, signed OAuth `state`, and app-profile-driven shared capability evaluation.
|
||||
- The first stateful slice adds durable auth/control-plane storage plus a real Discord callback path for Repixelizer.
|
||||
- Repixelizer has consumed the Heimdall backend-callback flow in its hosted web layer; Heimdall no longer needs to wait on Repixelizer refactoring before live Discord launch work.
|
||||
- Heimdall is deployed on Yggdrasil at `https://heimdall.gamecult.org` with nginx/TLS, Postgres storage, file-backed signing-key bootstrap, configured token custody, and passing public health/discovery/JWKS checks.
|
||||
- Heimdall now issues signed app refresh tokens alongside short-lived access claims and exposes `/v1/apps/{appSlug}/sessions/refresh` so app backends can reissue local claims without restarting provider OAuth.
|
||||
- Discord and Patreon provider access tokens can refresh inside Heimdall before Repixelizer entitlement re-evaluation.
|
||||
- Repixelizer is deployed on Yggdrasil at `https://repixelizer.gamecult.org` with `GC_ACCESS_MODE=heimdall`, `GC_ACCESS_ALLOWED_PROVIDERS=discord,patreon`, required access, queue protection enabled, app-owned Discord guild/role policy, and app-owned Patreon tier-title policy sent to Heimdall during backend-callback OAuth start.
|
||||
- StreamPixels viewer and creator provider OAuth should start through Heimdall; StreamPixels redeems one-time completion codes, owns local profile/connector binding, and resolves current provider access tokens from Heimdall by app-authenticated managed-credential calls.
|
||||
- Bifrost is a Heimdall app profile for Discord/Patreon member access. Bifrost owns the KTLST Discord role policy and Patreon tier policy; Heimdall owns provider OAuth, token custody, entitlement evaluation, and configured backend callback trust.
|
||||
- Bifrost patron support sync reuses Heimdall's existing linked Patreon identity and membership reader. Heimdall turns active paid Patreon tier evidence into signed support facts; Bifrost owns point/tier/vote derivation.
|
||||
- Heimdall's first runtime Verse cut publishes a service-owned CultCache boundary store and optional Idunn RUDP health pulse; full redacted auth-document witness export remains a later pass.
|
||||
|
||||
landed_baseline:
|
||||
- Heimdall publishes its redacted provider, command boundary, Eve plugin, and transport profile through Odin under globally unique record keys; Ghostlight resolves that boundary instead of owning a direct endpoint.
|
||||
- Yggdrasil runs Heimdall d51fa6b (hand-deployed 2026-10-19 15:51Z; gamecult-ops 210a1af holds backup, rollback and provenance; prior 1086aee) with CultLib 5cefa0db0079a8e3ee22f29d7b9e6e5aa60912a9; live Ghostlight auth.begin through Odin discovery is accepted.
|
||||
- The Heimdall access plugin, persistent OAuth attempts, encrypted private CultNet commands, conformance fixtures, and browser reference adapter are implemented and locally verified.
|
||||
- Exact-session refresh validation and logout revocation are implemented; stale or racing refresh cannot resurrect a revoked session.
|
||||
- Shared architecture extracted into its own repo and renamed to Heimdall.
|
||||
- Repixelizer and StreamPixels app-profile notes created.
|
||||
- Repo-local state, handoff, and compaction scaffolding created.
|
||||
- Initial Heimdall service skeleton landed with discovery, JWKS, OAuth start/callback contract surfaces, and claim issuance scaffolding.
|
||||
- Durable auth persistence landed for accounts, linked identities, sessions, grants, entitlement snapshots, and audit events.
|
||||
- The first real provider slice landed for Discord callback exchange, identity resolution, entitlement evaluation, and session/claim issuance for Repixelizer.
|
||||
- Signing-key persistence/bootstrap, managed token encryption at rest, and a local verifier seam landed for the first real consumer integration pass.
|
||||
- Direct backend callback handoff landed as the preferred same-host app-consumer path, with browser completion-code exchange retained as fallback.
|
||||
- Signed session refresh landed for app-facing claims: refresh tokens remain Heimdall-issued, provider refresh tokens remain sealed in Heimdall, and callers can provide app-owned entitlement policies for re-evaluation.
|
||||
- Repixelizer's hosted web layer now creates Heimdall auth attempts, receives direct backend callbacks, verifies Heimdall Ed25519 access tokens locally, and adopts httpOnly local sessions.
|
||||
- Heimdall now has generic Twitch and YouTube OAuth callback runtimes plus an app-authenticated managed-credential resolve endpoint for app-owned connector runtimes.
|
||||
- StreamPixels now starts viewer and creator Twitch/YouTube OAuth through Heimdall, redeems Heimdall completion codes server-side, writes its own viewer sessions and creator connector bindings, and leaves provider refresh-token custody in Heimdall.
|
||||
- Spotiverse now has a Heimdall app profile and Spotify provider runtime for managed credential custody.
|
||||
- Bifrost now has a Heimdall app profile for Discord/Patreon member access, and backend callback trust is checked through configured app callback allowlists before legacy app-specific defaults.
|
||||
- Heimdall exposes `POST /v1/apps/bifrost/patron-support/sync` as an app-authenticated bridge from linked Patreon membership evidence to Bifrost's signed patron support intake endpoint.
|
||||
- A read-only `gamecult.eve.provider_advertisement.v1` export now advertises Heimdall provider/app surfaces plus redacted CultCache witness document paths for Odin/Eve discovery.
|
||||
- Heimdall now writes a daemon-owned `GC_ACCESS_CULTCACHE_PATH` boundary store containing provider advertisement, command boundary, transport profile, and daemon-health summary state, and it can publish `heimdall.cultnet-rudp-provider-health` to Idunn over `cultnet.transport.rudp.v0` when configured.
|
||||
- Heimdall now persists a machine-bound Ed25519 provider-health identity, publishes canonical `idunn.signed_daemon_health.v1` records on an independent sequential pulse loop, and is admitted by Idunn through an exact root trust binding.
|
||||
|
||||
rejected_paths:
|
||||
- name: per_app_auth_copy_paste
|
||||
reason: duplicates the same provider/session sludge across every experiment
|
||||
- name: per_request_auth_round_trip
|
||||
reason: turns shared auth into a noisy bottleneck instead of local claim verification
|
||||
- name: shared_user_data_swamp
|
||||
reason: reusing auth mechanics does not justify centralizing app-domain audience or product data
|
||||
|
||||
current_status:
|
||||
summary: Yggdrasil runs Heimdall release d51fa6b (hand-deployed 2026-10-19 15:51Z, gamecult-ops 210a1af), which includes Joystick H1 (PR #1). The plugin and encrypted loopback begin, complete, refresh and logout plane, the Odin discovery records and Ghostlight resolution were verified at 1086aee (2026-08-22) and are not re-verified at d51fa6b.
|
||||
next_action: Run joystick:follow_up:h1-joystick-consent-round-trip, then StreamPixels S0/S1 (other sessions). Still open behind that: separate-account KLTST completion, refresh, logout, privacy, and stale-attempt canaries through the deployed Ghostlight Eve host; keep provider credential rotation on the operator list because prior tool output exposed OAuth secrets.
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
# Scratch
|
||||
|
||||
This file is disposable working memory for the current bounded subgoal.
|
||||
|
||||
## Current Subgoal
|
||||
|
||||
No active scratch subgoal.
|
||||
|
|
@ -1,328 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE_DIR = ROOT / "state"
|
||||
NOTES_DIR = ROOT / "notes"
|
||||
DOCS_DIR = ROOT / "docs"
|
||||
|
||||
MAP_PATH = STATE_DIR / "map.yaml"
|
||||
SCRATCH_PATH = STATE_DIR / "scratch.md"
|
||||
BRANCHES_PATH = STATE_DIR / "branches.json"
|
||||
EVIDENCE_PATH = STATE_DIR / "evidence.jsonl"
|
||||
HANDOFF_PATH = NOTES_DIR / "fresh-workspace-handoff.md"
|
||||
ARCH_PATH = DOCS_DIR / "architecture.md"
|
||||
PLAN_PATH = DOCS_DIR / "implementation-plan.md"
|
||||
AGENTS_PATH = ROOT / "AGENTS.md"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Finding:
|
||||
level: str
|
||||
message: str
|
||||
|
||||
|
||||
def read_text(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def run_git(args: list[str]) -> str:
|
||||
completed = subprocess.run(
|
||||
["git", *args],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
return completed.stdout.strip()
|
||||
|
||||
|
||||
def extract_map_field(name: str) -> str | None:
|
||||
prefix = f" {name}:"
|
||||
for line in read_text(MAP_PATH).splitlines():
|
||||
if line.startswith(prefix):
|
||||
return line.split(":", 1)[1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def extract_active_subgoals() -> list[str]:
|
||||
lines = read_text(MAP_PATH).splitlines()
|
||||
results: list[str] = []
|
||||
in_section = False
|
||||
for line in lines:
|
||||
if not in_section:
|
||||
if line.strip() == "active_subgoals:":
|
||||
in_section = True
|
||||
continue
|
||||
if line.startswith(" - "):
|
||||
results.append(line[4:].strip())
|
||||
continue
|
||||
if line and not line.startswith(" "):
|
||||
break
|
||||
return results
|
||||
|
||||
|
||||
def current_scratch_subgoal() -> str | None:
|
||||
lines = read_text(SCRATCH_PATH).splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
if line.strip() != "## Current Subgoal":
|
||||
continue
|
||||
for candidate in lines[index + 1 :]:
|
||||
stripped = candidate.strip()
|
||||
if stripped:
|
||||
return stripped
|
||||
return None
|
||||
|
||||
|
||||
def load_evidence() -> list[dict[str, Any]]:
|
||||
records: list[dict[str, Any]] = []
|
||||
for line_number, line in enumerate(read_text(EVIDENCE_PATH).splitlines(), start=1):
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
record = json.loads(line)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"evidence line {line_number} is invalid JSON: {exc}") from exc
|
||||
if not isinstance(record, dict):
|
||||
raise ValueError(f"evidence line {line_number} is not a JSON object")
|
||||
records.append(record)
|
||||
return records
|
||||
|
||||
|
||||
def load_branches() -> dict[str, Any]:
|
||||
data = json.loads(read_text(BRANCHES_PATH))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("branches.json must be a JSON object")
|
||||
branches = data.get("branches")
|
||||
if not isinstance(branches, list):
|
||||
raise ValueError("branches.json must contain a branches list")
|
||||
return data
|
||||
|
||||
|
||||
def add_required_file_checks(findings: list[Finding]) -> None:
|
||||
for path in [
|
||||
MAP_PATH,
|
||||
SCRATCH_PATH,
|
||||
BRANCHES_PATH,
|
||||
EVIDENCE_PATH,
|
||||
HANDOFF_PATH,
|
||||
ARCH_PATH,
|
||||
PLAN_PATH,
|
||||
AGENTS_PATH,
|
||||
]:
|
||||
if path.exists():
|
||||
findings.append(Finding("ok", f"found {path.relative_to(ROOT)}"))
|
||||
else:
|
||||
findings.append(Finding("error", f"missing {path.relative_to(ROOT)}"))
|
||||
|
||||
|
||||
def add_content_checks(findings: list[Finding]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
evidence: list[dict[str, Any]] = []
|
||||
branches: dict[str, Any] = {}
|
||||
|
||||
summary = extract_map_field("summary")
|
||||
next_action = extract_map_field("next_action")
|
||||
if summary:
|
||||
findings.append(Finding("ok", "state/map.yaml has current_status.summary"))
|
||||
else:
|
||||
findings.append(Finding("error", "state/map.yaml is missing current_status.summary"))
|
||||
if next_action:
|
||||
findings.append(Finding("ok", "state/map.yaml has current_status.next_action"))
|
||||
else:
|
||||
findings.append(Finding("error", "state/map.yaml is missing current_status.next_action"))
|
||||
|
||||
subgoals = extract_active_subgoals()
|
||||
if subgoals:
|
||||
findings.append(Finding("ok", f"state/map.yaml has {len(subgoals)} active subgoal(s)"))
|
||||
else:
|
||||
findings.append(Finding("warn", "state/map.yaml has no active_subgoals entries"))
|
||||
|
||||
scratch_subgoal = current_scratch_subgoal()
|
||||
if scratch_subgoal == "No active scratch subgoal.":
|
||||
findings.append(Finding("ok", "state/scratch.md has no stale active scratch subgoal"))
|
||||
elif scratch_subgoal:
|
||||
findings.append(Finding("warn", f"state/scratch.md has active scratch subgoal: {scratch_subgoal}"))
|
||||
else:
|
||||
findings.append(Finding("warn", "state/scratch.md has no Current Subgoal value"))
|
||||
|
||||
try:
|
||||
evidence = load_evidence()
|
||||
findings.append(Finding("ok", f"state/evidence.jsonl parses ({len(evidence)} record(s))"))
|
||||
except ValueError as exc:
|
||||
findings.append(Finding("error", str(exc)))
|
||||
|
||||
if EVIDENCE_PATH.exists() and EVIDENCE_PATH.stat().st_size > 25_000:
|
||||
findings.append(Finding("warn", "state/evidence.jsonl is larger than 25 KB; consider distillation"))
|
||||
|
||||
try:
|
||||
branches = load_branches()
|
||||
active = [
|
||||
branch
|
||||
for branch in branches.get("branches", [])
|
||||
if isinstance(branch, dict) and branch.get("status") == "active"
|
||||
]
|
||||
findings.append(Finding("ok", f"state/branches.json parses ({len(active)} active branch(es))"))
|
||||
except (json.JSONDecodeError, ValueError) as exc:
|
||||
findings.append(Finding("error", f"branches.json parse failed: {exc}"))
|
||||
|
||||
return evidence, branches
|
||||
|
||||
|
||||
def add_handoff_checks(findings: list[Finding]) -> None:
|
||||
text = read_text(HANDOFF_PATH)
|
||||
stale_branch = re.search(r"Current branch before .*ahead \d+", text)
|
||||
stale_head = re.search(r"Current HEAD before .*\b[0-9a-f]{7,40}\b", text)
|
||||
if stale_branch or stale_head:
|
||||
findings.append(Finding("error", "handoff embeds an exact branch or HEAD snapshot; use git commands instead"))
|
||||
else:
|
||||
findings.append(Finding("ok", "handoff avoids exact branch/HEAD snapshots"))
|
||||
|
||||
required_phrases = [
|
||||
"Do not continue implementation automatically from a rehydrate-only request.",
|
||||
"Do not trust this file for the exact live HEAD.",
|
||||
"Immediate Re-entry Instruction",
|
||||
]
|
||||
for phrase in required_phrases:
|
||||
if phrase in text:
|
||||
findings.append(Finding("ok", f"handoff contains: {phrase}"))
|
||||
else:
|
||||
findings.append(Finding("warn", f"handoff missing: {phrase}"))
|
||||
|
||||
|
||||
def add_agents_checks(findings: list[Finding]) -> None:
|
||||
text = read_text(AGENTS_PATH)
|
||||
if "heimdall_prepare_compaction.py" in text:
|
||||
findings.append(Finding("ok", "AGENTS.md tells agents to use the compaction helper"))
|
||||
else:
|
||||
findings.append(Finding("error", "AGENTS.md does not mention tools/heimdall_prepare_compaction.py"))
|
||||
if "prepare for imminent compaction" in text.lower():
|
||||
findings.append(Finding("ok", "AGENTS.md names the imminent-compaction trigger"))
|
||||
else:
|
||||
findings.append(Finding("warn", "AGENTS.md does not name the imminent-compaction trigger phrase"))
|
||||
|
||||
|
||||
def add_git_checks(findings: list[Finding]) -> tuple[str, str]:
|
||||
status = run_git(["status", "--short", "--branch"])
|
||||
log = run_git(["log", "--oneline", "-5"])
|
||||
dirty_lines = [line for line in status.splitlines()[1:] if line.strip()]
|
||||
if dirty_lines:
|
||||
findings.append(Finding("warn", "git worktree has uncommitted changes; commit or explain before compaction"))
|
||||
else:
|
||||
findings.append(Finding("ok", "git worktree is clean"))
|
||||
return status, log
|
||||
|
||||
|
||||
def render_report(findings: list[Finding], status: str, log: str, evidence: list[dict[str, Any]]) -> str:
|
||||
summary = extract_map_field("summary") or "(missing)"
|
||||
next_action = extract_map_field("next_action") or "(missing)"
|
||||
subgoals = extract_active_subgoals()
|
||||
|
||||
counts = {
|
||||
"ok": sum(1 for finding in findings if finding.level == "ok"),
|
||||
"warn": sum(1 for finding in findings if finding.level == "warn"),
|
||||
"error": sum(1 for finding in findings if finding.level == "error"),
|
||||
}
|
||||
|
||||
lines = [
|
||||
"Heimdall pre-compaction persistence check",
|
||||
f"Workspace: {ROOT}",
|
||||
f"Findings: {counts['ok']} ok, {counts['warn']} warn, {counts['error']} error",
|
||||
"",
|
||||
"Git status:",
|
||||
status,
|
||||
"",
|
||||
"Recent commits:",
|
||||
log,
|
||||
"",
|
||||
f"Summary: {summary}",
|
||||
f"Next action: {next_action}",
|
||||
]
|
||||
if subgoals:
|
||||
lines.append("Active subgoals:")
|
||||
lines.extend(f"- {item}" for item in subgoals)
|
||||
if evidence:
|
||||
latest = evidence[-1]
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
"Latest distilled evidence:",
|
||||
f"- {latest.get('ts', '(missing ts)')} {latest.get('type', '(missing type)')}/{latest.get('status', '(missing status)')}: {latest.get('note', '(missing note)')}",
|
||||
]
|
||||
)
|
||||
|
||||
lines.append("")
|
||||
lines.append("Findings:")
|
||||
for finding in findings:
|
||||
lines.append(f"[{finding.level.upper()}] {finding.message}")
|
||||
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
"Pre-compaction checklist:",
|
||||
"- Update state/map.yaml only if current understanding changed.",
|
||||
"- Refresh notes/fresh-workspace-handoff.md if re-entry instructions changed.",
|
||||
"- Add distilled evidence only for a belief-changing lesson, verification, rejected path, or scar.",
|
||||
"- Keep exact branch/HEAD out of handoff prose; git commands own volatile truth.",
|
||||
"- Commit completed persistence changes, or state why the worktree must stay dirty.",
|
||||
"- Re-run this helper after edits before yielding to compaction.",
|
||||
]
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Audit Heimdall persistent state before imminent compaction."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--strict",
|
||||
action="store_true",
|
||||
help="Exit nonzero on warnings as well as errors.",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = build_parser().parse_args()
|
||||
findings: list[Finding] = []
|
||||
evidence: list[dict[str, Any]] = []
|
||||
|
||||
add_required_file_checks(findings)
|
||||
try:
|
||||
evidence, _branches = add_content_checks(findings)
|
||||
except OSError as exc:
|
||||
findings.append(Finding("error", f"state content check failed: {exc}"))
|
||||
try:
|
||||
add_handoff_checks(findings)
|
||||
except OSError as exc:
|
||||
findings.append(Finding("error", f"handoff check failed: {exc}"))
|
||||
try:
|
||||
add_agents_checks(findings)
|
||||
except OSError as exc:
|
||||
findings.append(Finding("error", f"AGENTS check failed: {exc}"))
|
||||
try:
|
||||
status, log = add_git_checks(findings)
|
||||
except (OSError, subprocess.CalledProcessError) as exc:
|
||||
findings.append(Finding("error", f"git check failed: {exc}"))
|
||||
status = "(git status unavailable)"
|
||||
log = "(git log unavailable)"
|
||||
|
||||
print(render_report(findings, status, log, evidence))
|
||||
|
||||
has_error = any(finding.level == "error" for finding in findings)
|
||||
has_warning = any(finding.level == "warn" for finding in findings)
|
||||
if has_error or (args.strict and has_warning):
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -1,179 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE_DIR = ROOT / "state"
|
||||
MAP_PATH = STATE_DIR / "map.yaml"
|
||||
BRANCHES_PATH = STATE_DIR / "branches.json"
|
||||
EVIDENCE_PATH = STATE_DIR / "evidence.jsonl"
|
||||
|
||||
|
||||
def read_text(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def write_text(path: Path, content: str) -> None:
|
||||
path.write_text(content, encoding="utf-8")
|
||||
|
||||
|
||||
def load_branches() -> dict[str, Any]:
|
||||
return json.loads(read_text(BRANCHES_PATH))
|
||||
|
||||
|
||||
def save_branches(data: dict[str, Any]) -> None:
|
||||
write_text(BRANCHES_PATH, json.dumps(data, indent=2) + "\n")
|
||||
|
||||
|
||||
def append_evidence(record: dict[str, Any]) -> None:
|
||||
with EVIDENCE_PATH.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(record, ensure_ascii=True) + "\n")
|
||||
|
||||
|
||||
def utc_stamp() -> str:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
||||
|
||||
|
||||
def extract_map_field(name: str) -> str | None:
|
||||
prefix = f" {name}:"
|
||||
for line in read_text(MAP_PATH).splitlines():
|
||||
if line.startswith(prefix):
|
||||
return line.split(":", 1)[1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def extract_active_subgoals() -> list[str]:
|
||||
lines = read_text(MAP_PATH).splitlines()
|
||||
results: list[str] = []
|
||||
in_section = False
|
||||
for line in lines:
|
||||
if not in_section:
|
||||
if line.strip() == "active_subgoals:":
|
||||
in_section = True
|
||||
continue
|
||||
if line.startswith(" - "):
|
||||
results.append(line[4:].strip())
|
||||
continue
|
||||
if line and not line.startswith(" "):
|
||||
break
|
||||
return results
|
||||
|
||||
|
||||
def cmd_status(_: argparse.Namespace) -> int:
|
||||
branches = load_branches().get("branches", [])
|
||||
active = [branch for branch in branches if branch.get("status") == "active"]
|
||||
summary = extract_map_field("summary") or "(missing)"
|
||||
next_action = extract_map_field("next_action") or "(missing)"
|
||||
subgoals = extract_active_subgoals()
|
||||
|
||||
print(f"Workspace: {ROOT}")
|
||||
print(f"Summary: {summary}")
|
||||
print(f"Next action: {next_action}")
|
||||
print(f"Active branches: {len(active)} / {len(branches)}")
|
||||
if subgoals:
|
||||
print("Active subgoals:")
|
||||
for item in subgoals:
|
||||
print(f"- {item}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_add_evidence(args: argparse.Namespace) -> int:
|
||||
record: dict[str, Any] = {
|
||||
"ts": utc_stamp(),
|
||||
"type": args.type,
|
||||
"status": args.status,
|
||||
"note": args.note,
|
||||
}
|
||||
if args.branch:
|
||||
record["branch"] = args.branch
|
||||
append_evidence(record)
|
||||
print("Appended evidence record.")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_add_branch(args: argparse.Namespace) -> int:
|
||||
data = load_branches()
|
||||
branches = data.setdefault("branches", [])
|
||||
if any(branch.get("id") == args.id for branch in branches):
|
||||
raise SystemExit(f"Branch '{args.id}' already exists.")
|
||||
branches.append(
|
||||
{
|
||||
"id": args.id,
|
||||
"hypothesis": args.hypothesis,
|
||||
"status": "active",
|
||||
"artifacts": args.artifact or [],
|
||||
"notes": args.note or "",
|
||||
}
|
||||
)
|
||||
save_branches(data)
|
||||
print(f"Added branch '{args.id}'.")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_close_branch(args: argparse.Namespace) -> int:
|
||||
data = load_branches()
|
||||
for branch in data.get("branches", []):
|
||||
if branch.get("id") != args.id:
|
||||
continue
|
||||
branch["status"] = args.status
|
||||
if args.note:
|
||||
branch["notes"] = args.note
|
||||
save_branches(data)
|
||||
print(f"Updated branch '{args.id}' to status '{args.status}'.")
|
||||
return 0
|
||||
raise SystemExit(f"Branch '{args.id}' was not found.")
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Inspect and update Heimdall persistent state files."
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
status_parser = subparsers.add_parser("status", help="Show a compact state summary.")
|
||||
status_parser.set_defaults(func=cmd_status)
|
||||
|
||||
evidence_parser = subparsers.add_parser(
|
||||
"add-evidence", help="Append one distilled JSONL evidence record."
|
||||
)
|
||||
evidence_parser.add_argument("--type", required=True)
|
||||
evidence_parser.add_argument("--status", required=True)
|
||||
evidence_parser.add_argument("--note", required=True)
|
||||
evidence_parser.add_argument("--branch")
|
||||
evidence_parser.set_defaults(func=cmd_add_evidence)
|
||||
|
||||
add_branch_parser = subparsers.add_parser(
|
||||
"add-branch", help="Create a new active branch entry."
|
||||
)
|
||||
add_branch_parser.add_argument("--id", required=True)
|
||||
add_branch_parser.add_argument("--hypothesis", required=True)
|
||||
add_branch_parser.add_argument("--artifact", action="append")
|
||||
add_branch_parser.add_argument("--note")
|
||||
add_branch_parser.set_defaults(func=cmd_add_branch)
|
||||
|
||||
close_branch_parser = subparsers.add_parser(
|
||||
"close-branch", help="Close an existing branch."
|
||||
)
|
||||
close_branch_parser.add_argument("--id", required=True)
|
||||
close_branch_parser.add_argument(
|
||||
"--status", required=True, choices=["accepted", "rejected", "archived"]
|
||||
)
|
||||
close_branch_parser.add_argument("--note")
|
||||
close_branch_parser.set_defaults(func=cmd_close_branch)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args()
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Loading…
Reference in a new issue