Skip to content

Commit 6f16513

Browse files
SashaMITcursoragent
andcommitted
refactor(phase-2-d-helpers): thread wasmRuntime through route-chain helpers
Phase 2-C deferred 10 (originally counted as 8) getWASMRuntime() call sites with "Phase 2-D (deferred)" comments. Call-graph mapping during this ticket split them into three categories: 1. Route-chain helpers (7 sites in api/storage.ts + api/media.ts): convert to threaded wasmRuntime: WASMRuntime parameter. 2. Service-layer helpers (2 sites in services/media/): document as intentional architectural-boundary ambient. 3. Class-method on bootstrap-constructed service (1 site in IPFSStorage): same documentation pattern. 4. Module-level eager preloads (2 sites in api/media.ts): turned out not to use the WASM runtime at all (pure file reads); the getWASMRuntime value-import was unused at module-level once route-chain helpers were threaded — dropped entirely. Function signatures changed for 7 helpers across 3 files (api/storage.ts: loadRendererBinary, decryptAssetTwoLayer, renderViaWASM; api/media.ts: splitInitForTrackWithFallback, stripInitViaWASM, decryptSegmentViaWASM). All callers updated: 4 in storage.ts, 3 in media.ts /segment route, 1 in gateway.ts (skills-install handler). Notable difference from Phase 2-D: compiled JS is NOT byte-identical (function signatures changed). Behavior equivalence preserved by passing the exact same singleton that ambient access would have returned — verified via bootstrap-time app.locals.wasmRuntime assignment using the same getWASMRuntime() singleton. Discovery during execution: recoverCEKAndFetchData doesn't actually need threading — the runtime usage at the deferral-comment site was inside decryptAssetTwoLayer's scope (after the recoverCEKAndFetchData call returned), not inside recoverCEKAndFetchData's body. Spotted by tsc when I prematurely added a 3rd arg; reverted in <1 minute. Made ipfsService required in decryptAssetTwoLayer (was optional; both callers always pass it). 3 service-internal sites + 2 module-level preloads documented with explicit "intentional architectural-boundary ambient" classification comments pointing at PHASE-2-D-HELPERS-CLEANUP.md ticket. Future audits should not flag these; they're tracked as candidates for the eventual capsule-boundary refactor (constructor injection, pipeline context objects, capability tokens). Validation: - tsc --noEmit clean on FIRST attempt (no compiler bugs surfaced; unlike 2-C/2-Globals, route-chain sites were already properly typed under the getWASMRuntime() return type) - npm run build:backend clean - npm run test:unit 7/7 in 52.2 ms - ReadLints zero on 6 modified files - Live /api/health smoke: HTTP 200, db=connected, ipfs=available; Sasha's dev session continues operating normally through hot-reload After this commit, every route-chain consumer site for WASMRuntime in pc2-node/src now uses explicit dependency injection. Combined with Phases 2-A/2-B/2-C/2-D/2-Globals, all mechanical-pattern blockers (#1 + #2) are now functionally exhausted at the Express request boundary. Remaining audit work is exclusively architectural. Held behind Mac launcher 48-72h soak gate before release-branch merge. See PHASE-2-D-HELPERS-CLEANUP.md for the full execution log and CAPSULE_READINESS_REPORT.md §5.10 for audit-score impact. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 8f7698e commit 6f16513

10 files changed

Lines changed: 374 additions & 37 deletions

File tree

.cursor/tasks/OPTIMISATION-AND-REFACTORING-2026-05/AUDIT_EXECUTIVE_SUMMARY.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@
1212
>
1313
> **Phase 2-D executed (2026-05-18 morning)**: sibling-orchestrator type-only conversions landed on feature branch. Original audit framing predicted a 3-hour "extract interfaces" structural job; post-2-C survey found that **most consumer sites already use the orchestrator class only as a type annotation** — TypeScript's structural typing means `import type { AIChatService }` IS the interface, no nominal `IAIChatService` extraction needed. Scope shrunk to **6 mechanical keyword changes across 6 files** (`server.ts`, `api/ai.ts`, `api/other.ts`, `gateway/ChannelBridge.ts`, `ContentIntelligenceService.ts`, `api/boson.ts`). **Result**: every modified file's compiled JS is **literally byte-identical** pre vs post (strongest validation outcome — stronger than 2-B's spot-check proof because every modified file matched, not just spot-checks). All gates green: `tsc` clean, `build:backend` clean, `test:unit` 7/7, ReadLints zero errors. See `PHASE-2-D-SIBLING-ORCHESTRATOR-TYPE-ONLY.md` "Execution log" + audit report §5.8.
1414
>
15+
> **Phase 2-D-helpers executed (2026-05-18 afternoon)**: 7 route-chain `getWASMRuntime()` call sites in `api/storage.ts` (4) and `api/media.ts` (3) converted to threaded `wasmRuntime: WASMRuntime` parameters. 3 service-internal/class-method sites (`dashPackager`, `mp4split`, `IPFSStorage.getFile`) and 2 module-level preloads classified as intentional architectural-boundary ambient with explicit comments. 6 source files + 1 caller in `api/gateway.ts` updated. Compiled JS is NOT byte-identical (function signatures changed) — behavior equivalence preserved by threading the exact same singleton that ambient access returned. All gates green first try: `tsc` clean, `build:backend` clean, `test:unit` 7/7 in 52.2ms, ReadLints zero on 6 files, live `/api/health` ✅. **This completes route-chain consumer cleanup for the WASM runtime** — every Express request path now uses explicit dependency injection. Remaining ambient sites are service-construction-time or bootstrap-time only, audit-permitted. See `PHASE-2-D-HELPERS-CLEANUP.md` "Execution log" + audit report §5.10.
16+
>
1517
> **Phase 2-Globals executed (2026-05-18 midday)**: ambient `(global as any).X` cleanup landed on feature branch. Cleaned up 4 distinct patterns in pc2-node: (1) `pc2Config` deleted entirely as vestigial cache (db is real source of truth), (2) `global.db` latent bug fixed — was never set anywhere, so all `db?.getSetting()` calls in resources/supernode silently failed; now reads use `req.app.locals.db`, (3) `__filesystem` defensive-fallback documented with explanatory comments at producer + consumer (legitimate intentional global), (4) `ipfsStorage` consumer purged from supernode (bootstrap write at index.ts preserved as audit-permitted single-write). Pre-flight db survey of local install confirmed **zero existing user resource-settings** — bug-fix has forward-looking blast radius only. **TypeScript caught 4 more pre-existing type bugs during execution** (db.getSetting returns `string | undefined`, db.setSetting accepts `string` not `number`) — these were silent under `any` typing and would have caused NaN propagation once the read path started working. Fixed via explicit `parseInt()` / `String()` conversions. All gates green: `tsc` clean, `build:backend` clean, `test:unit` 7/7 in 52.6ms, ReadLints zero on 7 modified files. **The audit's mechanical-pattern blockers (#1 concrete-class consumer imports + #2 ambient global singletons) are now functionally exhausted for consumer modules in `pc2-node/src`** — remaining work is architectural (mega-orchestrator splits, deep-helper threading, ProposalStore extraction), not mechanical. See `PHASE-2-GLOBALS-CLEANUP.md` "Execution log" + audit report §5.9.
16-
> **Updated**: 2026-05-18 midday.
18+
> **Updated**: 2026-05-18 afternoon.
1719
1820
---
1921

.cursor/tasks/OPTIMISATION-AND-REFACTORING-2026-05/CAPSULE_READINESS_REPORT.md

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1109,6 +1109,107 @@ After Phase 2-E and the structural tickets above, any remaining work moves into
11091109

11101110
**Shipping**: held behind Mac-launcher 48-72h soak per `PHASE-2-PLAN.md` shipping gate.
11111111

1112+
### 5.10 Phase 2-D-helpers executed (2026-05-18 afternoon) — deep WASMRuntime consumer-site thread (completes route-chain consumer cleanup)
1113+
1114+
**Status**: shipped to feature branch `feat/t-1-telemetry-and-support`, awaiting CI green + review + Mac soak before release-branch merge.
1115+
1116+
**Resolves the 7-of-10 "Phase 2-D (deferred)" markers Phase 2-C left behind**
1117+
1118+
Phase 2-C deferred 8 (actually 10 — Phase 2-C's count was approximate) `getWASMRuntime()` call sites with `Phase 2-D (deferred): deep helper, ambient pull preserved` comments. Without further analysis these all looked equivalent. Call-graph mapping during this ticket showed they actually split into three distinct categories:
1119+
1120+
| Category | Sites | Action | Rationale |
1121+
|---|---|---|---|
1122+
| Route-chain helpers (1-2 layers from a route handler) | 7 | **Thread `wasmRuntime: WASMRuntime` parameter** | Clean Express context available; same pattern as Phase 2-C did at the route boundary. |
1123+
| Service-layer helpers (3+ layers deep in services/media/) | 2 | **Document as intentional service-internal ambient** | Threading would require modifying 3+ service module signatures with negligible audit benefit; future ProposalStore-style extraction is the right fix. |
1124+
| Class-method on bootstrap-constructed service | 1 | **Document as bootstrap-time class-method ambient** | `IPFSStorage` is built once at bootstrap; cleanest future fix is constructor injection. |
1125+
| Module-level eager preloads | 2 | **No fix needed** — they don't actually use the WASM runtime (pure `readFileSync`); the `getWASMRuntime` import was unused at module-level once route-chain helpers were threaded. |
1126+
1127+
### 7 conversions across 3 files
1128+
1129+
**`api/storage.ts`**:
1130+
- `loadRendererBinary(wasmRuntime: WASMRuntime)` — new param
1131+
- `decryptAssetTwoLayer(params, ipfsService, wasmRuntime: WASMRuntime)` — new param (also made `ipfsService` required since both callers always pass it)
1132+
- `renderViaWASM(params, mime, maxWidth, wasmRuntime: WASMRuntime, ...)` — new param
1133+
- 2 route handlers (`/lit/encrypt`, `/lit/secure-view`) updated to read `wasmRuntime` from `req.app.locals` and pass down
1134+
- Import converted: `import { getWASMRuntime, type RendererCommand }``import type { WASMRuntime, RendererCommand }`
1135+
1136+
**`api/media.ts`**:
1137+
- `splitInitForTrackWithFallback(initSegment, trackType, wasmRuntime: WASMRuntime)` — new param
1138+
- `stripInitViaWASM(initSegment, wasmRuntime: WASMRuntime)` — new param
1139+
- `decryptSegmentViaWASM(encryptedSegment, cekBase64, wasmRuntime: WASMRuntime, initSegment?)` — new param (positioned before optional)
1140+
- `/segment` route handler updated to read `wasmRuntime` from `req.app.locals` and thread it through all 3 helper calls (2 declarations in 2 different lexical scopes within the same handler)
1141+
- Import dropped entirely: `import { getWASMRuntime } from ...``import type { WASMRuntime } from ...` (no more value-import in this file)
1142+
1143+
**`api/gateway.ts`**:
1144+
- 1 caller of `decryptAssetTwoLayer` (in the skills-install handler) updated to pass `wasmRuntime`
1145+
- New `import type { WASMRuntime }` added
1146+
1147+
### 3 sites + 2 preloads documented as intentional architectural-boundary ambient
1148+
1149+
These sites keep `getWASMRuntime()` ambient access with explicit classification comments pointing at this ticket for the audit rationale:
1150+
1151+
- `services/media/dashPackager.ts:273``packageDASH()` exported service function
1152+
- `services/media/mp4split.ts:458``splitFragmentedMP4WASM()` exported service function
1153+
- `storage/ipfs.ts:918``IPFSStorage.getFile()` class method
1154+
- `api/media.ts:1098, 1117` — module-level eager preloads (don't actually use runtime; just file reads)
1155+
1156+
The pattern is the same as `__filesystem` was treated in Phase 2-Globals: **explicit, audit-permitted, with a documented future-fix path**.
1157+
1158+
### Validation outcome (every gate green first try)
1159+
1160+
| Gate | Result |
1161+
|---|---|
1162+
| `tsc --noEmit` | ✅ clean on FIRST attempt (no compiler bugs surfaced this round — expected, since route-chain sites were already properly typed) |
1163+
| `npm run build:backend` | ✅ clean |
1164+
| `npm run test:unit` | ✅ 7/7 in 52.2 ms |
1165+
| `ReadLints` on 6 modified files | ✅ 0 errors |
1166+
| Live `/api/health` smoke (dev server hot-reloaded all edits via `tsx watch`) | ✅ HTTP 200, db=connected, ipfs=available, user session continues normally |
1167+
1168+
Notable difference from Phase 2-D: **compiled JS is NOT byte-identical** (function signatures changed). Behavior equivalence is preserved by passing the exact same singleton that ambient access would have returned (verified at bootstrap: `app.locals.wasmRuntime = wasmRuntime` writes the same instance `getWASMRuntime()` lazily constructs).
1169+
1170+
### Strategic note on what this completes
1171+
1172+
After Phase 2-D-helpers:
1173+
1174+
- **Every route-chain consumer site for WASMRuntime in `pc2-node/src` now uses explicit dependency injection.**
1175+
- The only remaining `getWASMRuntime()` calls are at the service-construction layer (class methods, module-level preloads, deep service-internal helpers), which are architectural concerns — not mechanical.
1176+
- Combined with Phases 2-A/2-B/2-C/2-D/2-Globals, **all mechanical-pattern blockers (#1 + #2) are now functionally exhausted at the Express request boundary**.
1177+
1178+
**Combined progress since 2026-05-17**:
1179+
- Phase 2-A (types extraction): 10 files
1180+
- Phase 2-B (concrete-class → type-only imports for storage classes): 29 files, 40 sites
1181+
- Phase 2-C (ambient module-singleton purge): 14 files, 27 sites
1182+
- Phase 2-D (sibling-orchestrator type-only conversions): 6 files
1183+
- Phase 2-Globals (4-pattern ambient global cleanup + latent bug fix): 7 files
1184+
- **Phase 2-D-helpers (deep WASMRuntime route-chain thread): 6 files, 7 sites converted + 3 sites + 2 preloads classified**
1185+
- **Total: 72 file-touches, 80+ specific call-site changes, in ~7.5 hours of focused mechanical refactoring**
1186+
1187+
The remaining audit-derived work is now exclusively architectural:
1188+
1189+
| Future ticket | Type | Estimated effort |
1190+
|---|---|---|
1191+
| Phase 2-E — split 3 C-class mega-orchestrators (`ConnectivityService`, `api/index.ts`, `api/storage.ts`) | Structural refactor with real design decisions | ~1-2 days |
1192+
| AgentKitExecutor ProposalStore extraction (static-method consumers in `api/wallet.ts`) | Structural | ~2-3 hours |
1193+
| Optional WASMRuntime config-injection refactor | Lifecycle (make compute settings injectable at startup; opens path to runtime-mutable limits) | ~1 hour |
1194+
| Optional IPFSStorage constructor injection for wasmRuntime | Class-construction refactor | ~1-2 hours |
1195+
| Optional service-pipeline runtime-context object for `services/media/` | Architectural | Part of Phase 2-E or later |
1196+
1197+
After these structural items land, any remaining work moves into capsule-boundary definition and runtime capability tokens — i.e., the AGENTIC-PC2-MONETISATION migration design itself.
1198+
1199+
### Score impact
1200+
1201+
Estimated band shifts:
1202+
- `api/storage.ts`: B+ → A- (4 audit blockers resolved + clean import pattern)
1203+
- `api/media.ts`: B → A- (3 audit blockers resolved + dropped value-import entirely)
1204+
- `api/gateway.ts`: A- → A (added explicit type-only import; cleaner contract)
1205+
- `services/media/dashPackager.ts`, `services/media/mp4split.ts`, `storage/ipfs.ts`: bands unchanged but intent now documented for future audits
1206+
1207+
Net: ~5-7 score points across 6 modules + the audit's mechanical-pattern blocker for route-chain WASMRuntime consumers is now functionally closed.
1208+
1209+
### Shipping
1210+
1211+
Held behind Mac launcher 48-72h soak gate per `PHASE-2-PLAN.md`. After the Mac release stabilizes, this can be merged to release alongside Phase 2-A/2-B/2-C/2-D/2-Globals.
1212+
11121213
### 5.9 Phase 2-Globals executed (2026-05-18 midday) — ambient `(global as any).X` cleanup (completes audit blocker #2 for consumer modules)
11131214

11141215
**Status**: shipped to feature branch `feat/t-1-telemetry-and-support`, awaiting CI green + review + Mac soak before release-branch merge.

0 commit comments

Comments
 (0)