# Fresh-context audit of the Nous Portal provider: five rounds to a clean round > **Date:** 2026-11-25 > **Type:** generic > **Reference:** procedure in `~/.pi/agent/prompts/finish_audit.md`; commits `00d50e1`, `b9065d4`, `8d91094`, `78e8924`, `04fa08f` ## Goal Audit the session's changes to `index.ts` (and its tests and docs) with the fresh-context reviewer fanout from `finish_audit.md`: three reviewers per round (`ponytail-review`, `security-review`, `review`), each with a fresh context and read-only access to a materialized diff; fix the accepted findings; repeat until one full round produces zero accepted production-code findings after the last code-change round. ## What Was Done - **Round 1 → `00d50e1`** (tests 4 → 8): `slow_down` now sleeps longer instead of re-polling at once and the interval cap that could lower a server interval is gone; non-JSON token errors keep the HTTP status instead of surfacing as `SyntaxError`; dead `process.env.NOUS_API_KEY` fallback removed from `fetchModels`; `apply()` persists the catalog flag before mutating memory; `sleep` moved to `node:timers/promises`; three unused exports removed; `t.mock.method` replaces hand-rolled fetch swaps; stub gained `getAgentDir`. - **Round 2 → `b9065d4`** (tests 8 → 14): `apply()` swaps the current model only when a Nous model was filtered out and names the model actually in use; poll interval floored at 1 s; the provider's own `context.publish` removed (`createProvider` already publishes the `fetchModels` return value with `checkedAt`); `tokenRequest` tolerates a literal `null` error body; tsconfig and `.editorconfig` trimmed; slash commands driven through a recording `pi`. - **Round 3 → `8d91094`** (tests 14 → 17): the catalog-tier header is stripped from request **options** too, on both `stream` and `streamSimple`; the "Press Enter" prompt in OAuth login removed; non-finite poll intervals rejected and every sleep capped at the deadline; `/nous-free` back to full, `/nous-catalog` cycling, and startup restore of a saved catalog are covered. - **Round 4 → `78e8924`** (tests 17 → 18): `apply()` exits silently when a newer invocation changed the catalog while it awaited the model refresh (pinned with a deferred-refresh test); `CITATION.cff` no longer claims a release date while the CHANGELOG is `[Unreleased]` and no tag exists. - **Round 5 → `04fa08f`** (tests 18 → 20, no production change): pins the provider-level `fetchModels` last-good retention, the `tokenRequest` OAuth error mapping, and a real `setModel` assertion in the overlap test; README drops the hard-coded live catalog counts (409 / 3 / 42). - Each round: five patch files re-materialized into `_code_review/` by explicit path list (production / tests / config / docs / meta), verified byte-identical to HEAD and free of secrets; a cumulative ledger of 36 "already fixed — do NOT re-report" items grew in `_code_review/BRIEF.md` and was inlined into every reviewer task. Round 5 verdicts: security and ponytail clean, general docs-only/tests-only — zero code-change findings, stopping rule met. - Every production fix was mutation-checked after its commit: reverting it fails exactly its own test. Closing gate `npm run check`: `tsc` clean, 20/20. - Live smoke tests during the session (from `/tmp`, temporary `~/.pi/agent/nous-portal-catalog` flag, removed afterward): OAuth login and token refresh, subscription-billed inference, and paid / free / promo model calls answered. The network-refresh path of OAuth was not exercised live. ## Decisions & Rationale | Decision | Rationale | |----------|-----------| | Native pi-ai `Provider` via `createProvider`; OAuth access token used directly as the inference bearer | Nous retired agent-key minting (`410 session_key_minting_retired`), which is where both community extensions end their login. Recorded in `docs/adr/0001-stack.md`. | | Catalog tier rides on `Model.headers["x-nous-catalog-tier"]` and is stripped from **both** the model and the request options | pi persists and restores model objects across runs, so a side table misses restored entries; pi copies `model.headers` into `options.headers` before calling the provider and the client applies `options.headers` last. | | `withoutTierHeader` wraps both `stream` and `streamSimple` | They are separate implementations in pi-ai and `streamSimple` calls the module-local `stream`, so a `stream`-only wrapper is bypassed. | | No request-body rewriting (`tags.user`) | Nous free and discounted models return HTTP 500 when it is injected; `upstage/solar-mini4:free` is left out of `BASELINE` instead. | | `login()` is `notify(code)` then poll, with no prompt | pi's login dialog `showPrompt` clears the device-code confirm action, so a prompt leaves Enter opening nothing; pi's dialog already shows the code and opens the browser. | | Hand-rolled poll loop with interval `Number.isFinite && > 0 ? max(…, 1) : 5`, sleeps `min(interval·1000, deadline − now)` | pi-ai's `pollOAuthDeviceCodeFlow` is not exported; `interval: 0` and an overflowing JSON number (`Infinity`, clamped by Node to 1 ms) both become tight loops. Mirrors pi-ai's poller. | | `apply()` uses a supersede guard (`if (catalog !== next) return;`) rather than filtering by `next` | The guard removes both the mislabeled notice and the extra `setModel`; the surviving invocation reports the final state. A stale notice in the later `setModel` await is not humanly reachable and state stays correct. | | `models = fetched` kept; no provider-level `context.publish` | `createProvider` persists and publishes whatever `fetchModels` returns; a second publish was a timestamp-less write. An empty live result keeps the last good list. | | Rejected: `verification_uri` origin check | The attacker who could point it elsewhere is Nous itself. | | Withdrawn: "LICENSE link is dead" | The license is tracked; evidence in `LICENSE-head.txt`. | | Not added: a unit test for the poll loop | It would need extraction and timer control; the loop is verified live and its error paths are unit-tested through `tokenRequest`. | | Not fixed (fail closed, server-controlled input): 2xx token body without `access_token`; `fetchModels` 2xx body `null`; a malformed catalog row aborts the list | No exploit path; re-login or a surfaced `TypeError` follows. | | Mutation checks run only after the fix is committed | `git checkout -- ` restores HEAD; before the commit that is the pre-fix state (see gotchas). | | Round-5 tests/docs fixes applied without a sixth round | The procedure counts only accepted production-code findings; test-only and docs-only findings do not reset the loop. | | README carries no live catalog counts; `CITATION.cff` has no `date-released` | DOX style: document stable contracts, not diary entries; a date before a tag exists contradicts the CHANGELOG. | ## Gotchas & Fixes | Problem | Root Cause | Fix | |---------|------------|-----| | The catalog-tier header still reached Nous after the round-1 "fix"; the old test pinned the leak as expected | pi copies `model.headers` into `options.headers` (`pi-ai dist/models.js:361`, `model-runtime.js:476,488`) and the client applies `options.headers` last (`openai-completions.js:539-540`); `streamSimple` calls the module-local `stream` | `untier(model)` and `untier(options)` on both entry points; test asserts the header is absent while a sibling header survives (`8d91094`) | | "Press Enter" in login made Enter open nothing, silently | `showPrompt` in `login-dialog.js:189` calls `clearDeviceCodeAction()` | Prompt removed with a comment explaining why (`8d91094`) | | An overflowing `interval` became a tight loop | JSON number → `Infinity`; Node clamps `setTimeout` to 1 ms | `Number.isFinite` check, 1 s floor, sleeps capped at the deadline (`8d91094`) | | Two quick `/nous-*` invocations: the first notice mislabelled the catalog and could fire one extra `setModel` | `apply()` read the shared mutable `catalog` after `await refresh` | Supersede guard + deferred-refresh test (`78e8924`); the test's `setModel` half was vacuous until `04fa08f` gave the session a Nous model | | Mutation cleanup `git checkout -q -- index.ts` reverted the uncommitted round-3 production fixes | Mutation checks ran before committing | Re-applied (stale edit anchors first, then a fresh read); from round 4 on: commit → mutate → checkout | | A `node -e` mutation with `\\n` inside bash single quotes matched nothing and the chain continued | Over-escaped regex in the shell quoting | Plain string replace that exits non-zero when the content is unchanged | | New `tokenRequest` test failed on `error.message` | The local `OAuthError` prefixes messages with `${code}: ` | Assert on the prefixed form (`slow_down: 400 SLOW DOWN`) | | `goal_complete` rejected with "summary says the goal is not complete" | Text heuristic tripped on negated ledger phrases ("NOT DONE", "not a goal requirement") | Same facts rephrased affirmatively; accepted | | README live counts (409 / 3 / 42) drift; `CITATION.cff` `date-released` predates any release | Point-in-time snapshot presented as a contract; project tooling stamped a date | Counts dropped (`04fa08f`); `date-released` dropped (`78e8924`) | ## Files Changed | File | Change Summary | |------|----------------| | `index.ts` | Device-code poll bounded (finite interval, floor, deadline cap); tier header stripped from model and options on both stream entry points; login prompt removed; `apply()` persist-before-mutate and supersede guard; dead env fallback, interval cap, and a redundant `context.publish` removed; `tokenRequest` tolerates `null` bodies | | `tests/index.test.mjs` | 4 → 20 tests: tier header on both sides, `tokenRequest` error paths (HTML, `null`, JSON mapping), bearer credentials, slash commands via `drive()` with a deferred `refresh`, provider `fetchModels` last-good retention | | `tests/stubs/pi-ai.mjs` | `getAgentDir` returning a private `mkdtemp` dir shared via `globalThis`; `agentDir` export | | `README.md` | Overlay semantics, install lockfile flag, browser-UA posture, hermes row, typecheck pin; live counts removed | | `AGENTS.md`, `tests/AGENTS.md`, `docs/AGENTS.md` | Both header strips documented; allowlist includes `pi-coding-agent`; test contracts updated; session-log ownership added | | `CITATION.cff`, `CHANGELOG.md` | `date-released` dropped while unreleased; `/nous-catalog` switch semantics stated | | `tsconfig.json`, `.editorconfig`, `.gitignore` | Inert options removed; `.mjs` covered; `_code_review/` ignored | | `docs/devlog/20261125-fresh-context-audit-rounds-1-5_log.md`, `docs/devlog/INDEX.md` | This log and the index | ## Open Items & Next Steps - [ ] Rotate the API keys that were printed into the session log during the earlier investigation, if that log is not private. - [ ] At release: rename `## [Unreleased]` to `## [0.1.0] - ` and add `date-released` to `CITATION.cff` in the same commit, then tag `v0.1.0`. - [ ] `SCOPE = "inference:mint_agent_key"` is legacy (the mint endpoint returns 410) and grants nothing reachable; revisit if Nous publishes a replacement scope. - [ ] `upstage/solar-mini4:free` stays out of `BASELINE` while Nous returns 500 on an injected `tags.user`; re-check periodically. - [ ] The OAuth network-refresh path has not been exercised by a live smoke test. - [ ] `_code_review/` is gitignored; the 36-item ledger lives only on this machine. --- *Log written by write-log skill*