@air-jam/devtools 0.0.0-stage → 0.9.3

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 (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/dist/agent.d.ts +15 -0
  4. package/dist/agent.js +19 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/chunk-5YAARMW5.js +36 -0
  7. package/dist/chunk-5YAARMW5.js.map +1 -0
  8. package/dist/chunk-6WQODT37.js +1019 -0
  9. package/dist/chunk-6WQODT37.js.map +1 -0
  10. package/dist/chunk-CKFT2ZJE.js +801 -0
  11. package/dist/chunk-CKFT2ZJE.js.map +1 -0
  12. package/dist/chunk-ER3Q2C4G.js +358 -0
  13. package/dist/chunk-ER3Q2C4G.js.map +1 -0
  14. package/dist/chunk-GUEZP773.js +851 -0
  15. package/dist/chunk-GUEZP773.js.map +1 -0
  16. package/dist/chunk-HIDNI56E.js +33 -0
  17. package/dist/chunk-HIDNI56E.js.map +1 -0
  18. package/dist/chunk-QKXS5D35.js +43 -0
  19. package/dist/chunk-QKXS5D35.js.map +1 -0
  20. package/dist/chunk-S4LSCEVE.js +261 -0
  21. package/dist/chunk-S4LSCEVE.js.map +1 -0
  22. package/dist/chunk-VKMJO6VN.js +360 -0
  23. package/dist/chunk-VKMJO6VN.js.map +1 -0
  24. package/dist/chunk-WFUR3MXY.js +67 -0
  25. package/dist/chunk-WFUR3MXY.js.map +1 -0
  26. package/dist/chunk-XEMR7KUE.js +361 -0
  27. package/dist/chunk-XEMR7KUE.js.map +1 -0
  28. package/dist/chunk-ZLPD7FY5.js +191 -0
  29. package/dist/chunk-ZLPD7FY5.js.map +1 -0
  30. package/dist/context.d.ts +13 -0
  31. package/dist/context.js +9 -0
  32. package/dist/context.js.map +1 -0
  33. package/dist/controller.d.ts +41 -0
  34. package/dist/controller.js +30 -0
  35. package/dist/controller.js.map +1 -0
  36. package/dist/dev.d.ts +15 -0
  37. package/dist/dev.js +20 -0
  38. package/dist/dev.js.map +1 -0
  39. package/dist/game-session-broker.d.ts +57 -0
  40. package/dist/game-session-broker.js +235 -0
  41. package/dist/game-session-broker.js.map +1 -0
  42. package/dist/game-session.d.ts +13 -0
  43. package/dist/game-session.js +24 -0
  44. package/dist/game-session.js.map +1 -0
  45. package/dist/games.d.ts +21 -0
  46. package/dist/games.js +14 -0
  47. package/dist/games.js.map +1 -0
  48. package/dist/harness/visual.d.ts +321 -0
  49. package/dist/harness/visual.js +41 -0
  50. package/dist/harness/visual.js.map +1 -0
  51. package/dist/logs.d.ts +9 -0
  52. package/dist/logs.js +58 -0
  53. package/dist/logs.js.map +1 -0
  54. package/dist/mcp-config.d.ts +63 -0
  55. package/dist/mcp-config.js +190 -0
  56. package/dist/mcp-config.js.map +1 -0
  57. package/dist/platform-auth.d.ts +112 -0
  58. package/dist/platform-auth.js +37 -0
  59. package/dist/platform-auth.js.map +1 -0
  60. package/dist/platform-game-media.d.ts +309 -0
  61. package/dist/platform-game-media.js +168 -0
  62. package/dist/platform-game-media.js.map +1 -0
  63. package/dist/platform-games.d.ts +65 -0
  64. package/dist/platform-games.js +251 -0
  65. package/dist/platform-games.js.map +1 -0
  66. package/dist/quality.d.ts +10 -0
  67. package/dist/quality.js +63 -0
  68. package/dist/quality.js.map +1 -0
  69. package/dist/release.d.ts +1094 -0
  70. package/dist/release.js +1347 -0
  71. package/dist/release.js.map +1 -0
  72. package/dist/tooling/agent-contract.d.ts +2 -0
  73. package/dist/tooling/agent-contract.js +193 -0
  74. package/dist/tooling/agent-contract.js.map +1 -0
  75. package/dist/tooling/hold-runtime-host.d.ts +2 -0
  76. package/dist/tooling/hold-runtime-host.js +229 -0
  77. package/dist/tooling/hold-runtime-host.js.map +1 -0
  78. package/dist/tooling/inspect-airjam-agent.d.ts +2 -0
  79. package/dist/tooling/inspect-airjam-agent.js +37 -0
  80. package/dist/tooling/inspect-airjam-agent.js.map +1 -0
  81. package/dist/tooling/list-visual-scenarios.d.ts +2 -0
  82. package/dist/tooling/list-visual-scenarios.js +62 -0
  83. package/dist/tooling/list-visual-scenarios.js.map +1 -0
  84. package/dist/tooling/managed-dev-supervisor.d.ts +2 -0
  85. package/dist/tooling/managed-dev-supervisor.js +51 -0
  86. package/dist/tooling/managed-dev-supervisor.js.map +1 -0
  87. package/dist/tooling/run-visual-capture.d.ts +2 -0
  88. package/dist/tooling/run-visual-capture.js +167 -0
  89. package/dist/tooling/run-visual-capture.js.map +1 -0
  90. package/dist/types-C6NrHt88.d.ts +775 -0
  91. package/dist/visual.d.ts +15 -0
  92. package/dist/visual.js +263 -0
  93. package/dist/visual.js.map +1 -0
  94. package/package.json +113 -3
  95. package/src/agent.ts +380 -0
  96. package/src/commands.ts +40 -0
  97. package/src/context.ts +229 -0
  98. package/src/controller.ts +1376 -0
  99. package/src/dev.ts +999 -0
  100. package/src/fs-utils.ts +93 -0
  101. package/src/game-action-observation.ts +96 -0
  102. package/src/game-session-broker.ts +301 -0
  103. package/src/game-session.ts +459 -0
  104. package/src/games.ts +266 -0
  105. package/src/harness/visual/prefab-contract.ts +29 -0
  106. package/src/harness/visual/prefab-runner.ts +178 -0
  107. package/src/harness/visual/runner.ts +546 -0
  108. package/src/harness/visual/scenario-contract.ts +9 -0
  109. package/src/harness/visual/scenario-helpers.ts +63 -0
  110. package/src/harness/visual/session.ts +369 -0
  111. package/src/harness/visual/types.ts +181 -0
  112. package/src/harness/visual.ts +7 -0
  113. package/src/helper-scripts.ts +49 -0
  114. package/src/logs.ts +67 -0
  115. package/src/mcp-config.ts +262 -0
  116. package/src/platform-auth.ts +455 -0
  117. package/src/platform-game-media.ts +209 -0
  118. package/src/platform-games.ts +315 -0
  119. package/src/quality.ts +82 -0
  120. package/src/release.ts +1697 -0
  121. package/src/runtime-owner-protocol.ts +130 -0
  122. package/src/tooling/agent-contract.ts +232 -0
  123. package/src/tooling/agent-declaration.ts +36 -0
  124. package/src/tooling/airjam-agent-inspection.ts +45 -0
  125. package/src/tooling/airjam-agent.ts +118 -0
  126. package/src/tooling/hold-runtime-host.ts +224 -0
  127. package/src/tooling/inspect-airjam-agent.ts +20 -0
  128. package/src/tooling/list-visual-scenarios.ts +64 -0
  129. package/src/tooling/managed-dev-supervisor.ts +71 -0
  130. package/src/tooling/run-visual-capture.ts +217 -0
  131. package/src/tooling/runtime-owner-actions.ts +42 -0
  132. package/src/tooling/visual-pack.ts +46 -0
  133. package/src/types.ts +951 -0
  134. package/src/visual.ts +304 -0
  135. package/src/workspace-contract.ts +32 -0
package/src/agent.ts ADDED
@@ -0,0 +1,380 @@
1
+ import path from "node:path";
2
+ import { runCommandResult } from "./commands.js";
3
+ import {
4
+ inspectControllerSessionContext,
5
+ invokeControllerAction,
6
+ readRuntimeSnapshot,
7
+ resolveControllerSessionGameRuntime,
8
+ } from "./controller.js";
9
+ import {
10
+ classifyGameActionOutcome,
11
+ computeGameSnapshotObservation,
12
+ } from "./game-action-observation.js";
13
+ import { inspectGame } from "./games.js";
14
+ import {
15
+ resolveDevtoolsHelperArgs,
16
+ resolveDevtoolsHelperScript,
17
+ } from "./helper-scripts.js";
18
+ import type {
19
+ AirJamAgentContractInspection,
20
+ AirJamGameSnapshotInspection,
21
+ InspectGameAgentContractOptions,
22
+ InvokeGameActionOptions,
23
+ InvokeGameActionResult,
24
+ JsonObject,
25
+ ReadGameSnapshotOptions,
26
+ } from "./types.js";
27
+
28
+ export type {
29
+ AirJamAgentContractInspection,
30
+ AirJamGameSnapshotInspection,
31
+ InspectGameAgentContractOptions,
32
+ InvokeGameActionOptions,
33
+ InvokeGameActionResult,
34
+ ReadGameSnapshotOptions,
35
+ } from "./types.js";
36
+
37
+ const DEFAULT_TIMEOUT_MS = 5_000;
38
+
39
+ const parseHelperJson = <T>(output: string): T => {
40
+ const startIndex = output.indexOf("{");
41
+ const endIndex = output.lastIndexOf("}");
42
+ if (startIndex === -1 || endIndex === -1 || endIndex < startIndex) {
43
+ throw new Error(`Expected JSON helper output but received:\n${output}`);
44
+ }
45
+
46
+ return JSON.parse(output.slice(startIndex, endIndex + 1)) as T;
47
+ };
48
+
49
+ type ResolvedGameAgentSource = {
50
+ configPath: string;
51
+ };
52
+
53
+ const runGameAgentHelper = <T>({
54
+ cwd,
55
+ configPath,
56
+ contractPath,
57
+ operation,
58
+ args = [],
59
+ }: {
60
+ cwd: string;
61
+ configPath?: string | null;
62
+ contractPath?: string | null;
63
+ operation: "inspect" | "project" | "read-action" | "resolve-input";
64
+ args?: string[];
65
+ }): T => {
66
+ const result = runCommandResult({
67
+ command: process.execPath,
68
+ args: [
69
+ ...resolveDevtoolsHelperArgs(
70
+ resolveDevtoolsHelperScript("agent-contract.ts"),
71
+ ),
72
+ "--operation",
73
+ operation,
74
+ ...(configPath ? ["--config", configPath] : []),
75
+ ...(contractPath ? ["--contract", contractPath] : []),
76
+ ...args,
77
+ ],
78
+ // tsx discovers the nearest tsconfig from cwd. Resolve authored imports
79
+ // beside their config, not from the caller's monorepo/session directory.
80
+ cwd: configPath ? path.dirname(configPath) : cwd,
81
+ });
82
+
83
+ if (!result.ok) {
84
+ throw new Error(
85
+ `Air Jam agent helper failed.\n\n${result.stderr || result.stdout}`,
86
+ );
87
+ }
88
+
89
+ return parseHelperJson<T>(result.stdout);
90
+ };
91
+
92
+ const resolveGameAgentSource = async ({
93
+ configPath,
94
+ }: {
95
+ configPath: string | null;
96
+ }): Promise<ResolvedGameAgentSource | null> => {
97
+ if (configPath) {
98
+ const helperResult = runGameAgentHelper<{ hasContract: boolean }>({
99
+ cwd: path.dirname(configPath),
100
+ configPath,
101
+ operation: "inspect",
102
+ });
103
+ if (helperResult.hasContract) {
104
+ return {
105
+ configPath,
106
+ };
107
+ }
108
+ }
109
+
110
+ return null;
111
+ };
112
+
113
+ export const inspectGameAgentContract = async ({
114
+ cwd = process.cwd(),
115
+ gameId,
116
+ }: InspectGameAgentContractOptions = {}): Promise<AirJamAgentContractInspection> => {
117
+ const game = await inspectGame({ cwd, gameId });
118
+ const source = await resolveGameAgentSource({ configPath: game.configPath });
119
+
120
+ if (!source) {
121
+ return {
122
+ gameId: game.id,
123
+ rootDir: game.rootDir,
124
+ hasContract: false,
125
+ snapshotStoreDomains: [],
126
+ snapshotDescription: null,
127
+ actions: [],
128
+ };
129
+ }
130
+
131
+ const helperResult = runGameAgentHelper<{
132
+ snapshotStoreDomains: string[];
133
+ snapshotDescription: string | null;
134
+ actions: AirJamAgentContractInspection["actions"];
135
+ }>({
136
+ cwd: game.rootDir,
137
+ configPath: source.configPath,
138
+ operation: "inspect",
139
+ });
140
+
141
+ return {
142
+ gameId: game.id,
143
+ rootDir: game.rootDir,
144
+ hasContract: true,
145
+ snapshotStoreDomains: helperResult.snapshotStoreDomains,
146
+ snapshotDescription: helperResult.snapshotDescription,
147
+ actions: helperResult.actions,
148
+ };
149
+ };
150
+
151
+ export const readGameSnapshot = async ({
152
+ controllerSessionId,
153
+ requestSync = true,
154
+ timeoutMs = DEFAULT_TIMEOUT_MS,
155
+ }: ReadGameSnapshotOptions): Promise<AirJamGameSnapshotInspection> => {
156
+ const session = inspectControllerSessionContext(controllerSessionId);
157
+ const runtime = await resolveControllerSessionGameRuntime({
158
+ controllerSessionId,
159
+ timeoutMs,
160
+ });
161
+ if (!runtime.gameId) {
162
+ throw new Error(
163
+ `Controller session "${controllerSessionId}" is not associated with an Air Jam game.`,
164
+ );
165
+ }
166
+
167
+ const contract = await inspectGameAgentContract({
168
+ cwd: session.cwd,
169
+ gameId: runtime.gameId,
170
+ });
171
+ if (!contract.hasContract) {
172
+ throw new Error(
173
+ `Game "${runtime.gameId}" does not publish an agent contract yet.`,
174
+ );
175
+ }
176
+
177
+ const storeDomainBindings = contract.snapshotStoreDomains.map(
178
+ (contractStoreDomain) => ({
179
+ contractStoreDomain,
180
+ runtimeStoreDomain:
181
+ contractStoreDomain === "default"
182
+ ? runtime.defaultStoreDomain
183
+ : contractStoreDomain,
184
+ }),
185
+ );
186
+ const runtimeStoreDomains = storeDomainBindings.map(
187
+ (binding) => binding.runtimeStoreDomain,
188
+ );
189
+ const runtimeSnapshot = await readRuntimeSnapshot({
190
+ controllerSessionId,
191
+ storeDomains: runtimeStoreDomains,
192
+ requestSync,
193
+ timeoutMs,
194
+ });
195
+ const rawStores = runtimeSnapshot.storeSnapshots.filter((snapshot) =>
196
+ runtimeStoreDomains.includes(snapshot.storeDomain),
197
+ );
198
+ const storesPayload = storeDomainBindings.reduce<Record<string, JsonObject>>(
199
+ (nextStores, binding) => {
200
+ const snapshot = rawStores.find(
201
+ (candidate) => candidate.storeDomain === binding.runtimeStoreDomain,
202
+ );
203
+ if (snapshot) {
204
+ nextStores[binding.contractStoreDomain] = snapshot.data;
205
+ }
206
+ return nextStores;
207
+ },
208
+ {},
209
+ );
210
+
211
+ const helperResult = runGameAgentHelper<{
212
+ snapshot: JsonObject;
213
+ }>({
214
+ cwd: session.cwd,
215
+ configPath: (
216
+ await inspectGame({ cwd: session.cwd, gameId: runtime.gameId })
217
+ ).configPath,
218
+ operation: "project",
219
+ args: [
220
+ "--controller-id",
221
+ session.controllerId,
222
+ "--stores-base64",
223
+ Buffer.from(JSON.stringify(storesPayload), "utf8").toString("base64url"),
224
+ ],
225
+ });
226
+
227
+ return {
228
+ controllerSessionId,
229
+ gameId: runtime.gameId,
230
+ snapshotStoreDomains: [...contract.snapshotStoreDomains],
231
+ runtimeStoreDomains,
232
+ storeDomainBindings,
233
+ snapshotDescription: contract.snapshotDescription,
234
+ actions: contract.actions,
235
+ snapshot: helperResult.snapshot,
236
+ rawStores,
237
+ };
238
+ };
239
+
240
+ export const resolveGameActionPayload = async ({
241
+ cwd = process.cwd(),
242
+ gameId,
243
+ actionId,
244
+ payload,
245
+ }: {
246
+ cwd?: string;
247
+ gameId: string;
248
+ actionId: string;
249
+ payload?: unknown;
250
+ }): Promise<JsonObject | undefined> => {
251
+ const contract = await inspectGameAgentContract({
252
+ cwd,
253
+ gameId,
254
+ });
255
+ if (!contract.hasContract) {
256
+ throw new Error(`Game "${gameId}" does not publish an agent contract yet.`);
257
+ }
258
+
259
+ const action = contract.actions.find(
260
+ (candidate) => candidate.actionId === actionId,
261
+ );
262
+ if (!action) {
263
+ throw new Error(`Unknown game action "${actionId}" for game "${gameId}".`);
264
+ }
265
+
266
+ if (action.payload.kind === "none") {
267
+ return undefined;
268
+ }
269
+
270
+ const game = await inspectGame({
271
+ cwd,
272
+ gameId,
273
+ });
274
+
275
+ return (
276
+ runGameAgentHelper<{
277
+ payload: JsonObject | null;
278
+ }>({
279
+ cwd: game.rootDir,
280
+ configPath: game.configPath,
281
+ operation: "resolve-input",
282
+ args: [
283
+ "--game-id",
284
+ gameId,
285
+ "--action-id",
286
+ actionId,
287
+ "--payload-base64",
288
+ Buffer.from(JSON.stringify(payload ?? null), "utf8").toString(
289
+ "base64url",
290
+ ),
291
+ ],
292
+ }).payload ?? undefined
293
+ );
294
+ };
295
+
296
+ export const invokeGameAction = async ({
297
+ controllerSessionId,
298
+ actionId,
299
+ payload,
300
+ timeoutMs = DEFAULT_TIMEOUT_MS,
301
+ }: InvokeGameActionOptions): Promise<InvokeGameActionResult> => {
302
+ const session = inspectControllerSessionContext(controllerSessionId);
303
+ const runtime = await resolveControllerSessionGameRuntime({
304
+ controllerSessionId,
305
+ timeoutMs,
306
+ });
307
+ if (!runtime.gameId) {
308
+ throw new Error(
309
+ `Controller session "${controllerSessionId}" is not associated with an Air Jam game.`,
310
+ );
311
+ }
312
+
313
+ const contract = await inspectGameAgentContract({
314
+ cwd: session.cwd,
315
+ gameId: runtime.gameId,
316
+ });
317
+ if (!contract.hasContract) {
318
+ throw new Error(
319
+ `Game "${runtime.gameId}" does not publish an agent contract yet.`,
320
+ );
321
+ }
322
+
323
+ const action = contract.actions.find(
324
+ (candidate) => candidate.actionId === actionId,
325
+ );
326
+ if (!action) {
327
+ throw new Error(
328
+ `Unknown game action "${actionId}" for game "${runtime.gameId}".`,
329
+ );
330
+ }
331
+
332
+ const snapshotBefore = await readGameSnapshot({
333
+ controllerSessionId,
334
+ requestSync: true,
335
+ timeoutMs,
336
+ });
337
+
338
+ const resolvedPayload = await resolveGameActionPayload({
339
+ cwd: session.cwd,
340
+ gameId: runtime.gameId,
341
+ actionId,
342
+ payload,
343
+ });
344
+
345
+ const result = await invokeControllerAction({
346
+ controllerSessionId,
347
+ actionName: action.target.actionName,
348
+ storeDomain:
349
+ snapshotBefore.storeDomainBindings.find(
350
+ (binding) => binding.contractStoreDomain === action.target.storeDomain,
351
+ )?.runtimeStoreDomain ?? action.target.storeDomain,
352
+ payload: resolvedPayload,
353
+ });
354
+ const snapshotAfter = await readGameSnapshot({
355
+ controllerSessionId,
356
+ requestSync: true,
357
+ timeoutMs,
358
+ });
359
+ const { snapshotAfterStatus, observedStateChange } =
360
+ computeGameSnapshotObservation({
361
+ snapshotBefore,
362
+ snapshotAfter,
363
+ });
364
+ const { acknowledgementObservation, outcome } = classifyGameActionOutcome({
365
+ acknowledgement: result.acknowledgement,
366
+ observedStateChange,
367
+ });
368
+
369
+ return {
370
+ ...result,
371
+ actionId,
372
+ lane: "player",
373
+ acknowledgementObservation,
374
+ outcome,
375
+ snapshotBefore,
376
+ snapshotAfter,
377
+ snapshotAfterStatus,
378
+ observedStateChange,
379
+ };
380
+ };
@@ -0,0 +1,40 @@
1
+ import crossSpawn from "cross-spawn";
2
+ import type { CommandResult } from "./types.js";
3
+
4
+ const createBaseEnv = (): NodeJS.ProcessEnv => ({
5
+ ...process.env,
6
+ CI: process.env.CI ?? "1",
7
+ NO_UPDATE_NOTIFIER: "1",
8
+ });
9
+
10
+ export const runCommandResult = ({
11
+ command,
12
+ args,
13
+ cwd,
14
+ }: {
15
+ command: string;
16
+ args: string[];
17
+ cwd: string;
18
+ }): CommandResult => {
19
+ const startedAt = Date.now();
20
+ const result = crossSpawn.sync(command, args, {
21
+ cwd,
22
+ encoding: "utf8",
23
+ env: createBaseEnv(),
24
+ });
25
+
26
+ const exitCode = result.status ?? null;
27
+ return {
28
+ command,
29
+ args,
30
+ cwd,
31
+ exitCode,
32
+ signal: result.signal,
33
+ stdout: result.stdout ?? "",
34
+ stderr:
35
+ result.stderr ??
36
+ (result.error instanceof Error ? result.error.message : ""),
37
+ durationMs: Date.now() - startedAt,
38
+ ok: exitCode === 0 && !result.error,
39
+ };
40
+ };
package/src/context.ts ADDED
@@ -0,0 +1,229 @@
1
+ import path from "node:path";
2
+ import {
3
+ findUp,
4
+ firstExistingPath,
5
+ pathExists,
6
+ readPackageJson,
7
+ resolveCandidatePath,
8
+ resolveCanonicalPath,
9
+ } from "./fs-utils.js";
10
+ import type {
11
+ AirJamCapabilityGroup,
12
+ AirJamPackageManager,
13
+ AirJamProjectContext,
14
+ AirJamProjectInspection,
15
+ PackageJson,
16
+ } from "./types.js";
17
+ import { readWorkspaceContract } from "./workspace-contract.js";
18
+
19
+ export type {
20
+ AirJamCapabilityGroup,
21
+ AirJamPackageManager,
22
+ AirJamProjectContext,
23
+ AirJamProjectInspection,
24
+ } from "./types.js";
25
+
26
+ const hasDependency = (
27
+ packageJson: PackageJson,
28
+ packageName: string,
29
+ ): boolean =>
30
+ Boolean(
31
+ packageJson.dependencies?.[packageName] ??
32
+ packageJson.devDependencies?.[packageName] ??
33
+ packageJson.peerDependencies?.[packageName],
34
+ );
35
+
36
+ const detectPackageManager = async (
37
+ rootDir: string,
38
+ ): Promise<AirJamPackageManager> => {
39
+ if (await pathExists(path.join(rootDir, "pnpm-lock.yaml"))) {
40
+ return "pnpm";
41
+ }
42
+ if (await pathExists(path.join(rootDir, "package-lock.json"))) {
43
+ return "npm";
44
+ }
45
+ if (await pathExists(path.join(rootDir, "yarn.lock"))) {
46
+ return "yarn";
47
+ }
48
+ if (
49
+ (await pathExists(path.join(rootDir, "bun.lock"))) ||
50
+ (await pathExists(path.join(rootDir, "bun.lockb")))
51
+ ) {
52
+ return "bun";
53
+ }
54
+ return "unknown";
55
+ };
56
+
57
+ const findPackageRoot = async (cwd: string): Promise<string> => {
58
+ const packageJsonPath = await findUp(cwd, "package.json");
59
+ return packageJsonPath ? path.dirname(packageJsonPath) : path.resolve(cwd);
60
+ };
61
+
62
+ const findMonorepoRoot = async (cwd: string): Promise<string | null> => {
63
+ let currentDir = path.resolve(cwd);
64
+
65
+ while (true) {
66
+ const packageJsonResult = await readPackageJson(currentDir);
67
+ const packageJson = packageJsonResult?.value ?? null;
68
+
69
+ if (await isMonorepoRoot(currentDir, packageJson)) {
70
+ return currentDir;
71
+ }
72
+
73
+ const parent = path.dirname(currentDir);
74
+ if (parent === currentDir) {
75
+ return null;
76
+ }
77
+ currentDir = parent;
78
+ }
79
+ };
80
+
81
+ const isMonorepoRoot = async (
82
+ rootDir: string,
83
+ packageJson: PackageJson | null,
84
+ ): Promise<boolean> => {
85
+ if (!packageJson) {
86
+ return false;
87
+ }
88
+
89
+ const workspace = readWorkspaceContract(packageJson);
90
+ if (!workspace) return false;
91
+ if (!(await pathExists(path.resolve(rootDir, workspace.cli)))) {
92
+ throw new Error(
93
+ `Declared Air Jam workspace CLI does not exist: ${workspace.cli}`,
94
+ );
95
+ }
96
+ return true;
97
+ };
98
+
99
+ const isStandaloneGameRoot = async (
100
+ rootDir: string,
101
+ packageJson: PackageJson | null,
102
+ ): Promise<boolean> => {
103
+ if (!packageJson) {
104
+ return false;
105
+ }
106
+
107
+ if (hasDependency(packageJson, "@air-jam/sdk")) {
108
+ return true;
109
+ }
110
+
111
+ return Boolean(
112
+ await resolveCandidatePath(rootDir, [
113
+ "src/airjam.config.ts",
114
+ "src/airjam.config.tsx",
115
+ "src/airjam.config.js",
116
+ "src/airjam.config.mjs",
117
+ "airjam.config.ts",
118
+ "airjam.config.tsx",
119
+ "airjam.config.js",
120
+ "airjam.config.mjs",
121
+ ]),
122
+ );
123
+ };
124
+
125
+ export const detectProjectContext = async ({
126
+ cwd = process.cwd(),
127
+ }: {
128
+ cwd?: string;
129
+ } = {}): Promise<AirJamProjectContext> => {
130
+ const discoveredMonorepoRoot = await findMonorepoRoot(cwd);
131
+ const discoveredRootDir =
132
+ discoveredMonorepoRoot ?? (await findPackageRoot(cwd));
133
+ const rootDir = await resolveCanonicalPath(discoveredRootDir);
134
+ const monorepoRoot = discoveredMonorepoRoot ? rootDir : null;
135
+ const packageJsonResult = await readPackageJson(rootDir);
136
+ const packageJson = packageJsonResult?.value ?? null;
137
+ const reasons: string[] = [];
138
+
139
+ let workspaceRoot: string | null = null;
140
+ let mode: AirJamProjectContext["mode"] = "unknown";
141
+
142
+ if (monorepoRoot && rootDir === monorepoRoot) {
143
+ mode = "monorepo";
144
+ workspaceRoot = rootDir;
145
+ reasons.push("Detected a declared Air Jam workspace CLI.");
146
+ } else if (await isStandaloneGameRoot(rootDir, packageJson)) {
147
+ mode = "standalone-game";
148
+ reasons.push("Detected Air Jam game package or airjam config.");
149
+ } else {
150
+ reasons.push("No Air Jam monorepo or standalone game markers found.");
151
+ }
152
+
153
+ return {
154
+ rootDir,
155
+ mode,
156
+ packageManager: await detectPackageManager(rootDir),
157
+ packageJsonPath: packageJsonResult?.path ?? null,
158
+ packageJson,
159
+ workspaceRoot,
160
+ reasons,
161
+ };
162
+ };
163
+
164
+ const collectAirJamPackages = (
165
+ packageJson: PackageJson | null,
166
+ ): Record<string, string> => {
167
+ if (!packageJson) {
168
+ return {};
169
+ }
170
+
171
+ return Object.fromEntries(
172
+ Object.entries({
173
+ ...(packageJson.dependencies ?? {}),
174
+ ...(packageJson.devDependencies ?? {}),
175
+ ...(packageJson.peerDependencies ?? {}),
176
+ }).filter(
177
+ ([name]) => name === "create-airjam" || name.startsWith("@air-jam/"),
178
+ ),
179
+ );
180
+ };
181
+
182
+ const collectCapabilities = (
183
+ context: AirJamProjectContext,
184
+ ): AirJamCapabilityGroup[] => {
185
+ if (context.mode === "monorepo") {
186
+ return [
187
+ "project",
188
+ "games",
189
+ "logs",
190
+ "runtime",
191
+ "quality",
192
+ "repo-workspace",
193
+ "ai-pack",
194
+ ];
195
+ }
196
+
197
+ if (context.mode === "standalone-game") {
198
+ return ["project", "games", "logs", "runtime", "quality", "ai-pack"];
199
+ }
200
+
201
+ return ["project"];
202
+ };
203
+
204
+ export const inspectProject = async ({
205
+ cwd = process.cwd(),
206
+ }: {
207
+ cwd?: string;
208
+ } = {}): Promise<AirJamProjectInspection> => {
209
+ const context = await detectProjectContext({ cwd });
210
+ const rootDir = context.rootDir;
211
+
212
+ return {
213
+ context,
214
+ capabilities: collectCapabilities(context),
215
+ scripts: context.packageJson?.scripts ?? {},
216
+ airJamPackages: collectAirJamPackages(context.packageJson),
217
+ files: {
218
+ agents: await firstExistingPath([path.join(rootDir, "AGENTS.md")]),
219
+ plan: await firstExistingPath([path.join(rootDir, "plan.md")]),
220
+ suggestions: await firstExistingPath([
221
+ path.join(rootDir, "suggestions.md"),
222
+ path.join(rootDir, "docs", "suggestions.md"),
223
+ ]),
224
+ docsIndex: await firstExistingPath([
225
+ path.join(rootDir, "docs", "docs-index.md"),
226
+ ]),
227
+ },
228
+ };
229
+ };