@vgai/engine 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +35 -0
  3. package/package.json +55 -0
  4. package/src/adapter/authoring.ts +402 -0
  5. package/src/adapter/colyseus-networking-adapter.ts +72 -0
  6. package/src/adapter/first-party-systems.ts +103 -0
  7. package/src/adapter/game-adapter.ts +151 -0
  8. package/src/adapter/host-context.ts +77 -0
  9. package/src/adapter/index.ts +85 -0
  10. package/src/adapter/ingest/game-contract.ts +59 -0
  11. package/src/adapter/ingest/overlay-applier.ts +207 -0
  12. package/src/adapter/ingest/overlay-apply.ts +124 -0
  13. package/src/adapter/ingest/overlay-file.ts +126 -0
  14. package/src/adapter/ingest/overlay-report.ts +176 -0
  15. package/src/adapter/ingest/scene-capture.ts +307 -0
  16. package/src/adapter/ingest/upstream-pin.ts +52 -0
  17. package/src/adapter/loop-gate-report.ts +54 -0
  18. package/src/adapter/rapier-physics-adapter.ts +56 -0
  19. package/src/adapter/system-adapter.ts +154 -0
  20. package/src/adapter/transform.ts +18 -0
  21. package/src/adapter/vgai-scene-game-adapter.ts +886 -0
  22. package/src/adapter/world-kind.ts +34 -0
  23. package/src/ai/navigation.ts +164 -0
  24. package/src/animation/anim-graph-types.ts +56 -0
  25. package/src/animation/anim-graph.ts +406 -0
  26. package/src/animation/anim-system.ts +28 -0
  27. package/src/animation/blend-node.ts +119 -0
  28. package/src/animation/property-track.ts +178 -0
  29. package/src/animation/schema.ts +204 -0
  30. package/src/assets.ts +80 -0
  31. package/src/audio/ambient.ts +300 -0
  32. package/src/audio/impacts.ts +212 -0
  33. package/src/audio/index.ts +7 -0
  34. package/src/audio/movement.ts +140 -0
  35. package/src/audio/musical.ts +200 -0
  36. package/src/audio/ui-sounds.ts +171 -0
  37. package/src/audio/vehicle.ts +235 -0
  38. package/src/audio/weapons.ts +152 -0
  39. package/src/core/game-loop.ts +127 -0
  40. package/src/core/system-runner.ts +298 -0
  41. package/src/core/types.ts +58 -0
  42. package/src/dev/console-bridge.ts +83 -0
  43. package/src/dev/debug-draw.ts +80 -0
  44. package/src/dev/logger.ts +119 -0
  45. package/src/ecs/component-manager.ts +748 -0
  46. package/src/ecs/game-component.ts +147 -0
  47. package/src/ecs/hmr-swap-report.ts +65 -0
  48. package/src/input/input-manager.ts +439 -0
  49. package/src/input/input-types.ts +19 -0
  50. package/src/input/schema.ts +129 -0
  51. package/src/loader.ts +70 -0
  52. package/src/manifest/index.ts +24 -0
  53. package/src/manifest/load-file.ts +16 -0
  54. package/src/manifest/load.ts +378 -0
  55. package/src/manifest/schema.ts +375 -0
  56. package/src/physics/collision-system.ts +76 -0
  57. package/src/physics/physics-registry.ts +83 -0
  58. package/src/physics/transform-writer.ts +41 -0
  59. package/src/physics/trigger-dispatch.ts +97 -0
  60. package/src/react/game-state.tsx +172 -0
  61. package/src/render/auto-batcher.ts +169 -0
  62. package/src/render/render-batch-system.ts +268 -0
  63. package/src/render/render-features.ts +146 -0
  64. package/src/render/render-settings.ts +72 -0
  65. package/src/runtime/create-runtime.ts +1152 -0
  66. package/src/runtime/frame-selector-cache.ts +81 -0
  67. package/src/runtime/game.ts +1003 -0
  68. package/src/runtime/input-router.ts +213 -0
  69. package/src/runtime/mount-game.ts +269 -0
  70. package/src/runtime/mount-manifest.ts +361 -0
  71. package/src/runtime/scene-ui-bridge.ts +86 -0
  72. package/src/runtime/scene-ui-data.ts +119 -0
  73. package/src/runtime/state-bridge.ts +79 -0
  74. package/src/runtime/types.ts +196 -0
  75. package/src/scene/asset-loaders.ts +195 -0
  76. package/src/scene/asset-paths.ts +123 -0
  77. package/src/scene/asset-registry.ts +67 -0
  78. package/src/scene/collider-dimensions.ts +125 -0
  79. package/src/scene/component-registry.ts +40 -0
  80. package/src/scene/defaults.ts +164 -0
  81. package/src/scene/geometries/index.ts +7 -0
  82. package/src/scene/geometries/terrain.ts +42 -0
  83. package/src/scene/geometry-registry.ts +42 -0
  84. package/src/scene/instance-registry.ts +84 -0
  85. package/src/scene/instancers/grid.ts +38 -0
  86. package/src/scene/instancers/index.ts +7 -0
  87. package/src/scene/light-camera-factory.ts +97 -0
  88. package/src/scene/material-factory.ts +211 -0
  89. package/src/scene/material-registry.ts +73 -0
  90. package/src/scene/materials/index.ts +7 -0
  91. package/src/scene/materials/water.ts +56 -0
  92. package/src/scene/parse.ts +71 -0
  93. package/src/scene/particles-factory.ts +383 -0
  94. package/src/scene/scene-apply.ts +356 -0
  95. package/src/scene/scene-diff-schema.ts +115 -0
  96. package/src/scene/scene-diff-types.ts +29 -0
  97. package/src/scene/scene-loader.ts +1533 -0
  98. package/src/scene/scene-query.ts +63 -0
  99. package/src/scene/scene-types.ts +34 -0
  100. package/src/scene/scene-version.ts +40 -0
  101. package/src/scene/schema/animation.ts +95 -0
  102. package/src/scene/schema/audio.ts +25 -0
  103. package/src/scene/schema/camera.ts +21 -0
  104. package/src/scene/schema/collider.ts +69 -0
  105. package/src/scene/schema/entity-ref.ts +78 -0
  106. package/src/scene/schema/entity.ts +169 -0
  107. package/src/scene/schema/environment.ts +384 -0
  108. package/src/scene/schema/index.ts +95 -0
  109. package/src/scene/schema/instances.ts +35 -0
  110. package/src/scene/schema/joint.ts +26 -0
  111. package/src/scene/schema/light.ts +38 -0
  112. package/src/scene/schema/material.ts +113 -0
  113. package/src/scene/schema/mesh.ts +108 -0
  114. package/src/scene/schema/particles.ts +398 -0
  115. package/src/scene/schema/physics.ts +49 -0
  116. package/src/scene/schema/scene-file.ts +299 -0
  117. package/src/scene/schema/shadow.ts +24 -0
  118. package/src/scene/schema/spline.ts +21 -0
  119. package/src/scene/schema/tuples.ts +21 -0
  120. package/src/scene/schema/ui.ts +602 -0
  121. package/src/scene/user-data.ts +203 -0
  122. package/src/setup/setup-audio.ts +60 -0
  123. package/src/setup/setup-particles.ts +23 -0
  124. package/src/setup/setup-physics.ts +67 -0
  125. package/src/setup/setup-renderer.ts +529 -0
  126. package/src/types-n8ao.d.ts +37 -0
  127. package/src/types-realism-effects.d.ts +61 -0
  128. package/src/world2d/authoring-2d.ts +208 -0
  129. package/src/world2d/capture-to-scene2d.ts +52 -0
  130. package/src/world2d/collision-2d.ts +106 -0
  131. package/src/world2d/components-2d.ts +86 -0
  132. package/src/world2d/index.ts +66 -0
  133. package/src/world2d/ingest-iframe-2d.ts +255 -0
  134. package/src/world2d/ingest2d.ts +131 -0
  135. package/src/world2d/physics2d-registry.ts +49 -0
  136. package/src/world2d/pixi-game-adapter.ts +325 -0
  137. package/src/world2d/pixi-surface.ts +78 -0
  138. package/src/world2d/scene-capture-2d.ts +117 -0
  139. package/src/world2d/scene2d-loader.ts +308 -0
  140. package/src/world2d/schema/entity2d.ts +145 -0
  141. package/src/world2d/schema/physics2d.ts +53 -0
  142. package/src/world2d/schema/sprite.ts +71 -0
  143. package/src/world2d/schema/tilemap.ts +22 -0
  144. package/src/world2d/schema/tuples2d.ts +25 -0
  145. package/src/world2d/system-adapters-2d.ts +49 -0
  146. package/src/world2d/transform-writer-2d.ts +24 -0
  147. package/src/world2d/types.ts +55 -0
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Ingest overlay application core — the structural-path identity scheme and
3
+ * override-application loop shared by the EDITOR's `IngestAuthoringAdapter`
4
+ * (`packages/editor/src/authoring/ingest-authoring-adapter.ts`, which layers
5
+ * hierarchy/selection/undo bookkeeping over it) and the T3.8 runtime ship-path
6
+ * applier (`./overlay-applier.ts`, which uses it directly with none of that
7
+ * editor bookkeeping). Extracted here (rather than duplicated) per D9's task
8
+ * split (docs/DECISIONS-PENDING.md §D9) — the editor re-exports/reuses this
9
+ * module so its behavior (and the ids it mints) stay byte-for-byte identical
10
+ * between "authored in the editor" and "reapplied at ship time".
11
+ *
12
+ * Identity: each object gets a deterministic **structural-path id** — stable
13
+ * for a given scene shape (position in the tree + three.js type + name), so
14
+ * the SAME id re-binds to the SAME object after an independent fresh walk of
15
+ * an unmodified game's rebuilt scene (a reload, or a separate page entirely —
16
+ * this is what lets an overlay authored in the editor apply cleanly in a
17
+ * shipped build that never ran the editor). It is also written to
18
+ * `userData.entityId` so the editor's object map / gizmo / selection (which
19
+ * key on `entityId`) bind to foreign objects with no further shim.
20
+ */
21
+
22
+ import type * as THREE from 'three';
23
+ import { setUserData } from '../../scene/user-data';
24
+ import type { IngestOverlay } from './overlay-file';
25
+
26
+ /** Fixed id for the captured render camera (not a scene child, so no structural path). */
27
+ export const CAMERA_ID = 'ingest:camera';
28
+
29
+ /** The single (non-array) standard-ish material of a mesh, if it has a color. */
30
+ export function colorMaterialOf(o: THREE.Object3D): THREE.MeshStandardMaterial | null {
31
+ const mat = (o as THREE.Mesh).material;
32
+ if (!mat || Array.isArray(mat)) return null;
33
+ const m = mat as THREE.MeshStandardMaterial;
34
+ return m.color ? m : null;
35
+ }
36
+
37
+ /** Result of a structural-path walk: the id→object map plus a few reflection stats. */
38
+ export interface StructuralIdWalk {
39
+ byId: Map<string, THREE.Object3D>;
40
+ count: number;
41
+ meshes: number;
42
+ lights: number;
43
+ }
44
+
45
+ /**
46
+ * (Re)assign structural-path ids to every object under `scene` (and, if
47
+ * given, the separately-captured render `camera`, under the fixed
48
+ * {@link CAMERA_ID}). Idempotent and deterministic from scene structure
49
+ * (position + type + name) — the prerequisite for overlay reapplication
50
+ * across an independent fresh walk (editor reload, or a shipped build that
51
+ * never ran the editor at all).
52
+ */
53
+ export function assignStructuralIds(
54
+ scene: THREE.Object3D,
55
+ camera?: THREE.Object3D | undefined,
56
+ ): StructuralIdWalk {
57
+ const byId = new Map<string, THREE.Object3D>();
58
+ let count = 0;
59
+ let meshes = 0;
60
+ let lights = 0;
61
+ const visit = (
62
+ o: THREE.Object3D & { isMesh?: boolean; isLight?: boolean },
63
+ path: string,
64
+ ): void => {
65
+ const id = `ingest:${path}:${o.type}:${o.name || ''}`;
66
+ setUserData(o, 'entityId', id);
67
+ byId.set(id, o);
68
+ count++;
69
+ if (o.isLight) lights++;
70
+ else if (o.isMesh) meshes++;
71
+ o.children.forEach((c, i) => {
72
+ visit(c, `${path}/${i}`);
73
+ });
74
+ };
75
+ scene.children.forEach((c, i) => {
76
+ visit(c, `${i}`);
77
+ });
78
+ if (camera) {
79
+ setUserData(camera, 'entityId', CAMERA_ID);
80
+ byId.set(CAMERA_ID, camera);
81
+ count++;
82
+ }
83
+ return { byId, count, meshes, lights };
84
+ }
85
+
86
+ /** Result of applying a saved overlay onto a structural-id-walked scene. */
87
+ export interface OverlayApplyOutcome {
88
+ applied: number;
89
+ orphanedIds: string[];
90
+ }
91
+
92
+ /**
93
+ * Apply a saved overlay's overrides onto the live objects in `byId` (from
94
+ * {@link assignStructuralIds}). Ids absent from the map are "orphaned" — e.g. a
95
+ * dynamic child that didn't respawn, or the vendored game was bumped and
96
+ * restructured — never an error; the caller reports them (never silently) via
97
+ * `./overlay-report.ts`. Mutates matched objects in place; does not mutate
98
+ * `overlay` itself or track dirty/undo state — that bookkeeping is the
99
+ * editor-side `IngestAuthoringAdapter`'s job (persistable-edit tracking, so
100
+ * orphans round-trip on the next save) and is irrelevant to the ship-path
101
+ * applier (which never saves).
102
+ */
103
+ export function applyOverlayToObjects(
104
+ byId: Map<string, THREE.Object3D>,
105
+ overlay: IngestOverlay,
106
+ ): OverlayApplyOutcome {
107
+ let applied = 0;
108
+ const orphanedIds: string[] = [];
109
+ for (const [id, ov] of Object.entries(overlay)) {
110
+ const o = byId.get(id);
111
+ if (!o) {
112
+ orphanedIds.push(id);
113
+ continue;
114
+ }
115
+ if (ov.position) o.position.set(ov.position[0], ov.position[1], ov.position[2]);
116
+ if (ov.rotation)
117
+ o.quaternion.set(ov.rotation[0], ov.rotation[1], ov.rotation[2], ov.rotation[3]);
118
+ if (ov.scale) o.scale.set(ov.scale[0], ov.scale[1], ov.scale[2]);
119
+ if (ov.color) colorMaterialOf(o)?.color.set(ov.color);
120
+ if (ov.visible !== undefined) o.visible = ov.visible;
121
+ applied++;
122
+ }
123
+ return { applied, orphanedIds };
124
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Ingest overlay envelope — the on-disk shape shared by every consumer of a
3
+ * saved ingest overlay: the editor (`packages/editor/src/authoring/ingest-overlay.ts`,
4
+ * which persists it through the storage-backend seam) AND the T3.8 runtime ship-path
5
+ * applier (`./overlay-applier.ts`, which fetches it over plain HTTP in a deployed
6
+ * game with no editor/storage-backend dependency at all).
7
+ *
8
+ * This module is the dependency-free core (types + pure parsing) both share — moved
9
+ * here (from the editor-only module that used to own it) per D9's task split
10
+ * (docs/DECISIONS-PENDING.md §D9): the editor keeps the storage-backend-aware
11
+ * `loadOverlay`/`saveOverlay` and re-exports everything below unchanged so its
12
+ * existing import sites don't churn.
13
+ */
14
+
15
+ /** A single object's persisted overrides (only the fields the user changed). */
16
+ export interface IngestOverride {
17
+ position?: [number, number, number];
18
+ rotation?: [number, number, number, number];
19
+ scale?: [number, number, number];
20
+ color?: string;
21
+ visible?: boolean;
22
+ }
23
+
24
+ /** id (structural-path) → overrides. */
25
+ export type IngestOverlay = Record<string, IngestOverride>;
26
+
27
+ /** Current on-disk envelope format version (D9, docs/DECISIONS-PENDING.md §D9). */
28
+ export const OVERLAY_FORMAT_VERSION = 1;
29
+
30
+ /**
31
+ * The on-disk overlay envelope (D9 — overlay versioning + orphan reporting).
32
+ * Wraps the flat `IngestOverlay` (id → overrides) with save-time provenance:
33
+ * which game version the edits were authored against, so a later mount (editor
34
+ * OR shipped runtime) can detect drift and report it (`./overlay-report.ts`'s
35
+ * `OverlayApplyReport`).
36
+ *
37
+ * `formatVersion` distinguishes this from the PRE-D9 flat file (the whole JSON
38
+ * file WAS the `IngestOverlay`): {@link parseOverlayFile} recognizes both. An
39
+ * object with `formatVersion` + `overrides` parses as the real envelope; any
40
+ * other shape (or unparseable content) parses as a legacy flat file, wrapped as
41
+ * `{ formatVersion: 0, authoredAgainst: { gameVersion: null }, overrides: <the flat object> }`
42
+ * — never rejected, never warned about by itself.
43
+ *
44
+ * `authoredAgainst.upstreamPin` (R5, docs/MASTER-ARCHITECTURE-REVIEW.md
45
+ * §4(c)/§7.1 item 9 — the overlay-identity gap `gameVersion` alone doesn't
46
+ * close: `gameVersion` is the manifest's own `version` field, which a
47
+ * re-vendor of the upstream game need not bump — see every `public/ingest/*`
48
+ * game's `vgai.game.json`, all pinned at `"version": "0.1.0"` regardless of
49
+ * upstream commit) is an OPTIONAL sibling key, deliberately absent from this
50
+ * type's older call sites' literal shape: its ABSENCE (the key missing from
51
+ * `authoredAgainst` entirely) is the "legacy overlay" signal — saved by code
52
+ * that predates this field, so the pin concept never existed for it, and
53
+ * `./overlay-report.ts`'s apply-time check must skip it (not treat it as a
54
+ * guaranteed mismatch OR a guaranteed match — anti-shim, no guessing). A
55
+ * `null` VALUE (key present, value `null`) means R5-aware save-time code DID
56
+ * look for a pin and honestly found none (e.g. an externally-authored,
57
+ * non-vendored project opened via the CLI-on-folder route, which has no
58
+ * `UPSTREAM.md` at all). See `./upstream-pin.ts` for the pure extraction, and
59
+ * `packages/editor/src/ingest-mode.ts` for where it's read at save/apply
60
+ * time. This is purely additive — {@link parseOverlayFile} never invents the
61
+ * key for an envelope that didn't have it.
62
+ */
63
+ export interface OverlayFile {
64
+ formatVersion: number;
65
+ authoredAgainst: { gameVersion: string | null; upstreamPin?: string | null };
66
+ overrides: IngestOverlay;
67
+ }
68
+
69
+ /** Where a game's overlay lives, project-root-relative (also the ship path's default fetch URL). */
70
+ export function overlayPath(gameId: string): string {
71
+ return `.vgai/overlays/${gameId}.json`;
72
+ }
73
+
74
+ /** The empty envelope — no overlay found / nothing authored yet. */
75
+ export function emptyOverlayFile(): OverlayFile {
76
+ return {
77
+ formatVersion: OVERLAY_FORMAT_VERSION,
78
+ authoredAgainst: { gameVersion: null },
79
+ overrides: {},
80
+ };
81
+ }
82
+
83
+ /** An envelope has both its distinguishing keys — anything else is a legacy flat file. */
84
+ function isEnvelope(raw: unknown): raw is OverlayFile {
85
+ return (
86
+ !!raw &&
87
+ typeof raw === 'object' &&
88
+ 'formatVersion' in (raw as Record<string, unknown>) &&
89
+ 'overrides' in (raw as Record<string, unknown>)
90
+ );
91
+ }
92
+
93
+ /**
94
+ * Parse a loaded/fetched overlay's raw JSON into the {@link OverlayFile} shape,
95
+ * transparently upgrading a legacy (pre-D9) flat file — the whole parsed value
96
+ * IS the `IngestOverlay` in that case. Pure — no I/O, no storage backend, so
97
+ * it's usable from any context (editor `loadOverlay`, the ship-path applier's
98
+ * `fetch().then(r => r.json())`).
99
+ */
100
+ export function parseOverlayFile(raw: unknown): OverlayFile {
101
+ if (isEnvelope(raw)) {
102
+ const rawAuthored = (raw.authoredAgainst ?? { gameVersion: null }) as {
103
+ gameVersion?: string | null;
104
+ upstreamPin?: string | null;
105
+ };
106
+ const authoredAgainst: OverlayFile['authoredAgainst'] = {
107
+ gameVersion: rawAuthored.gameVersion ?? null,
108
+ };
109
+ // Preserve ABSENCE vs. explicit `null` (see this field's doc comment
110
+ // above) — only copy the key over if the raw JSON actually had it, rather
111
+ // than defaulting it in (which would make every pre-R5 saved overlay look
112
+ // like a "checked, found nothing" R5 save instead of "never checked").
113
+ if ('upstreamPin' in rawAuthored) authoredAgainst.upstreamPin = rawAuthored.upstreamPin ?? null;
114
+ return {
115
+ formatVersion: raw.formatVersion,
116
+ authoredAgainst,
117
+ overrides: raw.overrides ?? {},
118
+ };
119
+ }
120
+ // Legacy flat file (pre-D9): the whole parsed object IS the overrides map.
121
+ return {
122
+ formatVersion: 0,
123
+ authoredAgainst: { gameVersion: null },
124
+ overrides: (raw ?? {}) as IngestOverlay,
125
+ };
126
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Overlay apply report — D9 (docs/DECISIONS-PENDING.md §D9): decide + surface
3
+ * what happens when a saved ingest overlay is reapplied onto a scene that may
4
+ * have moved on since the overlay was authored (a vendored game bump, or a
5
+ * dynamic subtree that never respawned). Two independent signals, either of
6
+ * which is worth a loud (never silent) structured warning:
7
+ * - a GAME-VERSION mismatch: the overlay's `authoredAgainst.gameVersion`
8
+ * (`./overlay-file.ts`'s envelope, stamped from the manifest's `version`
9
+ * at save time) disagrees with the currently-mounted game's version;
10
+ * - ORPHANED ids: structural-path ids in the overlay that resolved to
11
+ * nothing on the current scene walk (`./overlay-apply.ts`'s
12
+ * `applyOverlayToObjects`).
13
+ *
14
+ * Neither condition blocks mounting — the overlay still applies everything it
15
+ * CAN; this module only decides whether/how to report what it couldn't.
16
+ *
17
+ * This is the SEAM T3.8 (the runtime overlay applier, i.e. reapplying an
18
+ * ingest overlay against a shipped/played build rather than the editor)
19
+ * reuses: `./overlay-applier.ts`'s `applyVgaiOverlay` builds + logs this EXACT
20
+ * report shape, same as the editor does. Moved here from the editor-only
21
+ * module that used to own it (`packages/editor/src/authoring/overlay-report.ts`,
22
+ * which now re-exports everything below unchanged plus the editor-only
23
+ * "active report" banner slot) — kept dependency-free (no `editor-console`/
24
+ * `window` import) so it stays importable from a headless runtime context —
25
+ * same discipline as `../achieved-tier.ts`.
26
+ *
27
+ * R5 (docs/MASTER-ARCHITECTURE-REVIEW.md §4(c)/§7.1 item 9) adds a THIRD
28
+ * independent signal alongside version-mismatch/orphans: an UPSTREAM-PIN
29
+ * mismatch. `gameVersion` alone cannot catch a same-slot substitution after a
30
+ * re-vendor (structural ids are position+type+name; a re-vendor that keeps a
31
+ * slot's shape reapplies the overlay onto a semantically different object
32
+ * with `applied:1, orphanedIds:[]`, and every vendored game's manifest
33
+ * `version` is hand-set and need not change on a re-vendor). The upstream pin
34
+ * (`./upstream-pin.ts`, read from the vendored game's `UPSTREAM.md`) is bound
35
+ * to the thing that actually changes. Like the other two signals, a mismatch
36
+ * never blocks application — it's a report, not a block (matching orphan
37
+ * semantics) — so a re-vendor surfaces as an explicit "authored against pin
38
+ * X, applying onto pin Y" instead of silent success.
39
+ */
40
+
41
+ /** One mount's version + orphan findings — the D9 acceptance-criteria shape. */
42
+ export interface OverlayApplyReport {
43
+ gameId: string;
44
+ /** `authoredAgainst.gameVersion` from the loaded overlay envelope, or `null` if never stamped. */
45
+ authoredAgainst: string | null;
46
+ /** The currently-mounted game's manifest `version`, or `null` if unknown at this call site. */
47
+ currentVersion: string | null;
48
+ /** Both sides known AND different — never true if either side is `null` (anti-shim: no guessing). */
49
+ versionMismatch: boolean;
50
+ applied: number;
51
+ /** Structural-path ids present in the overlay that resolved to nothing on this scene walk. */
52
+ orphanedIds: string[];
53
+ /**
54
+ * R5 — upstream-pin identity check (see this module's header). Distinct
55
+ * from `versionMismatch`/`orphanedIds`: it catches a same-slot
56
+ * SUBSTITUTION (id persists, meaning changed) that those two cannot.
57
+ */
58
+ upstreamPin: {
59
+ /** The pin the overlay was authored against, or `null` if never recorded/discoverable. */
60
+ authored: string | null;
61
+ /** The currently-mounted game's own discoverable pin, or `null` if undiscoverable here
62
+ * (e.g. the runtime ship-path applier, which has no `UPSTREAM.md` access at all — a
63
+ * documented no-op there — or an externally-authored, non-vendored project). */
64
+ current: string | null;
65
+ /**
66
+ * Whether the SAVED overlay envelope recorded the upstream-pin concept at
67
+ * all (i.e. `authoredAgainst.upstreamPin` was a present key, even if its
68
+ * value was `null`). `false` means a legacy overlay — saved by pre-R5
69
+ * code (or the pre-D9 flat-file shape) — for which the pin check is
70
+ * skipped entirely, not silently treated as a match. This is the
71
+ * "explicit legacy indication" the report surfaces so a legacy overlay's
72
+ * clean apply doesn't read as "verified" when it was never checked.
73
+ */
74
+ recorded: boolean;
75
+ /** `recorded` AND both sides known AND different — never true otherwise (anti-shim). */
76
+ mismatch: boolean;
77
+ };
78
+ }
79
+
80
+ /** Greppable prefix shared by every overlay-related log line (mirrors `achieved-tier.ts`'s `TIER_SHORTFALL_PREFIX`). */
81
+ export const OVERLAY_REPORT_PREFIX = 'overlay-report';
82
+
83
+ /** Build the report from a mount's raw findings — pure, no logging. */
84
+ export function buildOverlayApplyReport(args: {
85
+ gameId: string;
86
+ authoredAgainst: string | null;
87
+ currentVersion: string | null;
88
+ applied: number;
89
+ orphanedIds: string[];
90
+ /**
91
+ * R5: the loaded overlay's `authoredAgainst.upstreamPin`. Pass `undefined`
92
+ * (or omit) when the saved envelope never had the key at all (legacy
93
+ * overlay — `upstreamPin.recorded` becomes `false`); pass `null` when the
94
+ * envelope DID have the key but its value was `null` (R5-aware code
95
+ * looked, found nothing — `recorded` is `true`, `authored` is `null`); pass
96
+ * the pin string otherwise.
97
+ */
98
+ authoredUpstreamPin?: string | null | undefined;
99
+ /**
100
+ * R5: the currently-mounted game's own discoverable pin, or `null`/omitted
101
+ * when undiscoverable at this call site (anti-shim: never fabricated).
102
+ */
103
+ currentUpstreamPin?: string | null | undefined;
104
+ }): OverlayApplyReport {
105
+ const versionMismatch =
106
+ args.authoredAgainst !== null &&
107
+ args.currentVersion !== null &&
108
+ args.authoredAgainst !== args.currentVersion;
109
+ const recorded = args.authoredUpstreamPin !== undefined;
110
+ const authoredPin = args.authoredUpstreamPin ?? null;
111
+ const currentPin = args.currentUpstreamPin ?? null;
112
+ const upstreamPinMismatch =
113
+ recorded && authoredPin !== null && currentPin !== null && authoredPin !== currentPin;
114
+ return {
115
+ gameId: args.gameId,
116
+ authoredAgainst: args.authoredAgainst,
117
+ currentVersion: args.currentVersion,
118
+ applied: args.applied,
119
+ orphanedIds: args.orphanedIds,
120
+ versionMismatch,
121
+ upstreamPin: {
122
+ authored: authoredPin,
123
+ current: currentPin,
124
+ recorded,
125
+ mismatch: upstreamPinMismatch,
126
+ },
127
+ };
128
+ }
129
+
130
+ /** Whether this report is worth surfacing (mismatch OR any orphan) — pure, no logging. */
131
+ export function overlayReportWarrants(report: OverlayApplyReport): boolean {
132
+ return report.versionMismatch || report.orphanedIds.length > 0 || report.upstreamPin.mismatch;
133
+ }
134
+
135
+ /** The one shared message shape — greppable on the prefix, JSON-parseable on the trailing payload. */
136
+ export function formatOverlayApplyReportMessage(report: OverlayApplyReport): string {
137
+ const parts: string[] = [];
138
+ if (report.versionMismatch) {
139
+ parts.push(
140
+ `overlay authored against v${report.authoredAgainst}, game is v${report.currentVersion}`,
141
+ );
142
+ }
143
+ if (report.upstreamPin.mismatch) {
144
+ parts.push(
145
+ `overlay authored against upstream pin ${report.upstreamPin.authored}, ` +
146
+ `game is vendored at pin ${report.upstreamPin.current}`,
147
+ );
148
+ }
149
+ if (report.orphanedIds.length > 0) {
150
+ parts.push(
151
+ `${report.orphanedIds.length} orphaned overlay entr${report.orphanedIds.length === 1 ? 'y' : 'ies'}`,
152
+ );
153
+ }
154
+ return (
155
+ `${OVERLAY_REPORT_PREFIX} game "${report.gameId}": ${parts.join('; ')} ` +
156
+ `(D9, docs/DECISIONS-PENDING.md §D9; upstream-pin check R5, ` +
157
+ `docs/MASTER-ARCHITECTURE-REVIEW.md §4(c)). ${OVERLAY_REPORT_PREFIX} ${JSON.stringify(report)}`
158
+ );
159
+ }
160
+
161
+ /**
162
+ * Emit the ONE structured `console.warn` this report warrants (mirroring the
163
+ * tier-shortfall pattern), or do nothing when neither signal fires. Returns
164
+ * whether it warned (callers that also want the panel-visible `editorConsole`
165
+ * echo, or the inline banner, use the return value / the report itself).
166
+ */
167
+ export function logOverlayApplyReport(report: OverlayApplyReport): boolean {
168
+ if (!overlayReportWarrants(report)) return false;
169
+ // The D9 AC requires this EXACT native console.warn (spied on directly in
170
+ // overlay-versioning.test.ts) — other deliberate native console.warn call sites in
171
+ // this codebase (e.g. editor-store.ts) are unsuppressed and already counted in the
172
+ // lint baseline; this one is suppressed to keep this task's diff at zero NEW warnings.
173
+ // biome-ignore lint/suspicious/noConsole: see comment above
174
+ console.warn(formatOverlayApplyReportMessage(report));
175
+ return true;
176
+ }