@team-antioch/sc2-adjutant 0.1.0 → 0.1.1

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 (149) hide show
  1. package/README.md +2 -0
  2. package/data/blizzard-baseline.json +3061 -0
  3. package/data/button-hotkeys.json +5722 -0
  4. package/data/game-assets.json +50909 -0
  5. package/data/package-entries.json +32361 -2
  6. package/dist/capture/bank-fixtures.d.ts +13 -0
  7. package/dist/capture/bank-fixtures.js +35 -0
  8. package/dist/capture/bank-snapshots.d.ts +95 -0
  9. package/dist/capture/bank-snapshots.js +302 -0
  10. package/dist/capture/editor-broker-client.d.ts +27 -4
  11. package/dist/capture/editor-broker-client.js +3 -3
  12. package/dist/capture/editor-broker.js +154 -9
  13. package/dist/capture/effect-tour.d.ts +113 -0
  14. package/dist/capture/effect-tour.js +283 -0
  15. package/dist/capture/effect-video.d.ts +74 -0
  16. package/dist/capture/effect-video.js +173 -0
  17. package/dist/capture/exemplar-capture.d.ts +4 -0
  18. package/dist/capture/exemplar-capture.js +4 -1
  19. package/dist/capture/shots.d.ts +6 -1
  20. package/dist/capture/shots.js +1 -1
  21. package/dist/capture/stop-tour.d.ts +3 -1
  22. package/dist/capture/stop-tour.js +1 -1
  23. package/dist/capture/style-pack-captures.d.ts +67 -0
  24. package/dist/capture/style-pack-captures.js +172 -0
  25. package/dist/catalog/stock-catalog.d.ts +8 -0
  26. package/dist/catalog/stock-catalog.js +13 -0
  27. package/dist/cli/capture-exemplars.js +18 -32
  28. package/dist/cli/effect-tour.d.ts +2 -0
  29. package/dist/cli/effect-tour.js +378 -0
  30. package/dist/cli/make-frames.d.ts +1 -0
  31. package/dist/cli/make-frames.js +21 -0
  32. package/dist/cli/sound-mix.d.ts +1 -0
  33. package/dist/cli/sound-mix.js +75 -0
  34. package/dist/cli/study.js +6 -26
  35. package/dist/domain/blueprint-trigger.d.ts +355 -3
  36. package/dist/domain/blueprint-trigger.js +149 -8
  37. package/dist/domain/library-interface.d.ts +50 -29
  38. package/dist/domain/library-interface.js +54 -41
  39. package/dist/domain/mission-blueprint.d.ts +13 -6
  40. package/dist/domain/mission-blueprint.js +6 -0
  41. package/dist/domain/mod-blueprint.d.ts +4 -4
  42. package/dist/host/game-logs.d.ts +63 -0
  43. package/dist/host/game-logs.js +178 -0
  44. package/dist/host/game-ownership.d.ts +37 -0
  45. package/dist/host/game-ownership.js +84 -0
  46. package/dist/host/game-run-report.d.ts +63 -0
  47. package/dist/host/game-run-report.js +119 -0
  48. package/dist/host/known-errors.d.ts +34 -0
  49. package/dist/host/known-errors.js +73 -0
  50. package/dist/init/init-workspace.d.ts +3 -1
  51. package/dist/init/init-workspace.js +10 -1
  52. package/dist/map/convert-mission-triggers.d.ts +115 -7
  53. package/dist/map/convert-mission-triggers.js +527 -47
  54. package/dist/map/editor-changes.d.ts +1 -1
  55. package/dist/map/editor-form.d.ts +5 -0
  56. package/dist/map/editor-form.js +72 -0
  57. package/dist/map/game-packages.d.ts +3 -2
  58. package/dist/map/game-packages.js +5 -2
  59. package/dist/map/kept-references.js +47 -1
  60. package/dist/map/kept-session.js +3 -1
  61. package/dist/map/outline-diff.d.ts +24 -0
  62. package/dist/map/outline-diff.js +95 -0
  63. package/dist/map/outline-trigger.d.ts +7 -0
  64. package/dist/map/outline-trigger.js +29 -20
  65. package/dist/map/ownership-plan.d.ts +6 -2
  66. package/dist/map/ownership-plan.js +1 -1
  67. package/dist/map/package-output.js +13 -8
  68. package/dist/map/tune-kept-triggers.d.ts +7 -0
  69. package/dist/map/tune-kept-triggers.js +33 -6
  70. package/dist/map/write-blueprint-trigger.d.ts +9 -4
  71. package/dist/map/write-blueprint-trigger.js +46 -13
  72. package/dist/map/write-map-package.js +20 -9
  73. package/dist/mcp/capture-jobs.d.ts +2 -0
  74. package/dist/mcp/capture-jobs.js +2 -0
  75. package/dist/mcp/server.d.ts +11 -2
  76. package/dist/mcp/server.js +17 -4
  77. package/dist/mcp/tools/bank-report.d.ts +19 -0
  78. package/dist/mcp/tools/bank-report.js +51 -0
  79. package/dist/mcp/tools/blueprint.js +18 -14
  80. package/dist/mcp/tools/capture.d.ts +4 -0
  81. package/dist/mcp/tools/capture.js +22 -5
  82. package/dist/mcp/tools/catalog.d.ts +1 -1
  83. package/dist/mcp/tools/catalog.js +30 -1
  84. package/dist/mcp/tools/compile.d.ts +1 -1
  85. package/dist/mcp/tools/compile.js +100 -9
  86. package/dist/mcp/tools/editor-handoff.d.ts +4 -1
  87. package/dist/mcp/tools/editor-handoff.js +6 -3
  88. package/dist/mcp/tools/style-pack.d.ts +11 -0
  89. package/dist/mcp/tools/style-pack.js +245 -0
  90. package/dist/mcp/tools/tool-group.d.ts +9 -0
  91. package/dist/mods/button-hotkeys.d.ts +45 -0
  92. package/dist/mods/button-hotkeys.js +185 -0
  93. package/dist/mods/compile-mod.js +19 -5
  94. package/dist/mods/custom-doodads.d.ts +21 -1
  95. package/dist/mods/custom-doodads.js +53 -7
  96. package/dist/mods/data-rules.js +8 -1
  97. package/dist/mods/effective-entry.d.ts +18 -0
  98. package/dist/mods/effective-entry.js +52 -0
  99. package/dist/mods/function-search.js +12 -0
  100. package/dist/mods/library-xml.d.ts +34 -5
  101. package/dist/mods/library-xml.js +94 -22
  102. package/dist/mods/sound-mix.d.ts +92 -0
  103. package/dist/mods/sound-mix.js +195 -0
  104. package/dist/plugins/check-workspace.js +22 -3
  105. package/dist/plugins/plugin-api.d.ts +59 -5
  106. package/dist/plugins/plugin-api.js +6 -0
  107. package/dist/plugins/plugin-sdk.d.ts +13 -1
  108. package/dist/plugins/plugin-sdk.js +16 -1
  109. package/dist/plugins/plugin-sources.js +1 -0
  110. package/dist/plugins/registry.d.ts +4 -0
  111. package/dist/plugins/registry.js +6 -2
  112. package/dist/plugins/workspace.d.ts +5 -0
  113. package/dist/plugins/workspace.js +10 -2
  114. package/dist/study/blizzard-baseline.d.ts +76 -0
  115. package/dist/study/blizzard-baseline.js +137 -0
  116. package/dist/study/exemplar-report.d.ts +71 -0
  117. package/dist/study/exemplar-report.js +163 -0
  118. package/dist/study/find-places.d.ts +127 -0
  119. package/dist/study/find-places.js +306 -0
  120. package/dist/study/load-map-package.d.ts +3 -0
  121. package/dist/study/load-map-package.js +11 -0
  122. package/dist/study/map-study.d.ts +1 -0
  123. package/dist/study/map-study.js +3 -0
  124. package/dist/study/measure-lighting.d.ts +6 -0
  125. package/dist/study/measure-lighting.js +1 -1
  126. package/dist/study/measures.d.ts +225 -0
  127. package/dist/study/measures.js +366 -0
  128. package/dist/study/scaffold-style-pack.d.ts +58 -0
  129. package/dist/study/scaffold-style-pack.js +261 -0
  130. package/dist/study/study-exemplars.d.ts +67 -0
  131. package/dist/study/study-exemplars.js +133 -0
  132. package/dist/triggers/blueprint-triggers.d.ts +71 -11
  133. package/dist/triggers/blueprint-triggers.js +403 -48
  134. package/dist/triggers/kept-trigger-galaxy.d.ts +29 -0
  135. package/dist/triggers/kept-trigger-galaxy.js +103 -7
  136. package/dist/triggers/splice-map-script.d.ts +2 -0
  137. package/dist/triggers/splice-map-script.js +309 -8
  138. package/dist/triggers/write-triggers-xml.js +20 -5
  139. package/dist/ui/frame-path-check.d.ts +43 -4
  140. package/dist/ui/frame-path-check.js +121 -13
  141. package/dist/ui/frame-paths.d.ts +21 -1
  142. package/dist/ui/frame-paths.js +26 -6
  143. package/dist/ui/toast.d.ts +4 -5
  144. package/dist/ui/toast.js +6 -10
  145. package/examples/example-campaign/README.md +27 -0
  146. package/examples/example-campaign/missions/ashfall-relay/blueprint.json +11 -1
  147. package/examples/example-campaign/missions/ashfall-relay/triggers/ash-tremors.json +69 -0
  148. package/examples/example-campaign/missions/ashfall-relay/triggers/start-ash-tremors.json +31 -0
  149. package/package.json +3 -3
@@ -0,0 +1,178 @@
1
+ // Reading the game's GameLogs folder: which files belong to one game session, and the distinct
2
+ // errors in them. The folder is each Host Adapter's (`game.logsFolder`); the reading is the same
3
+ // on every machine, so it lives here and runs over a fixture folder in tests.
4
+ //
5
+ // What the folder looks like (Mac, 2026-11-24): files named `<YYYY-MM-DD HH.MM.SS> <Channel>.txt`
6
+ // in local time, the stamp being when the game made the file. The game writes them as it exits, so
7
+ // a session's files can be created minutes apart (Graphics and SystemInfo at start; Alerts,
8
+ // ScriptError and Text a little later; UI, Cutscenes whenever they're first needed) and are all
9
+ // modified at the quit. A crash or an error makes a folder `<stamp> <computer> B<build> P<pid> Crash`
10
+ // (or `Error`) holding that session's files and the crash report. Most files open with a header
11
+ // block (`<Parameters>`, the game's command line, is in it); Text.txt has none.
12
+ import { readdir, readFile, stat } from "node:fs/promises";
13
+ import path from "node:path";
14
+ /** The channels whose lines are what went wrong. SystemInfo, Graphics and the rest only describe the machine. */
15
+ export const ERROR_CHANNELS = ["ScriptError", "Alerts", "Text", "UI", "Cutscenes"];
16
+ const STAMP = /^(\d{4})-(\d\d)-(\d\d) (\d\d)\.(\d\d)\.(\d\d) (.+)$/;
17
+ const CRASH_FOLDER = /^(.+) B\d+ P(\d+) (Crash|Error)$/;
18
+ function stampOf(name) {
19
+ const match = STAMP.exec(name);
20
+ if (!match)
21
+ return undefined;
22
+ const [, y, mo, d, h, mi, s, rest] = match;
23
+ return { at: new Date(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s)), rest: rest };
24
+ }
25
+ async function fileOf(filePath, channel, createdAt) {
26
+ return { path: filePath, channel, createdAt, modifiedAt: (await stat(filePath)).mtime };
27
+ }
28
+ /** The `<Parameters>` line of a file's header, if it has one; only its first few kilobytes are read. */
29
+ async function parametersOf(file) {
30
+ const text = (await readFile(file.path, "utf8")).slice(0, 4096);
31
+ return /<Parameters>[ \t]+(.+)/.exec(text)?.[1]?.trim();
32
+ }
33
+ /**
34
+ * Every session in a GameLogs folder, oldest first. Files are grouped in the order the game made
35
+ * them: a file joins the latest group that has no file of its channel yet and whose command line
36
+ * agrees (a file with no header, such as Text, agrees with any), else it starts a group. Time alone
37
+ * can't group them, since one session's files are made minutes or an hour apart. A crash or error
38
+ * folder is one session, its own files in it. Files of a game still running are read as they are.
39
+ */
40
+ export async function readGameSessions(folder) {
41
+ let entries;
42
+ try {
43
+ entries = await readdir(folder, { withFileTypes: true });
44
+ }
45
+ catch (error) {
46
+ if (error.code === "ENOENT")
47
+ return [];
48
+ throw error;
49
+ }
50
+ const loose = [];
51
+ const crashes = [];
52
+ for (const entry of entries) {
53
+ const stamped = stampOf(entry.name);
54
+ if (!stamped)
55
+ continue;
56
+ if (entry.isDirectory()) {
57
+ const match = CRASH_FOLDER.exec(stamped.rest);
58
+ if (match)
59
+ crashes.push({ crash: { kind: match[3], folder: path.join(folder, entry.name), pid: Number(match[2]), at: stamped.at }, dir: path.join(folder, entry.name), name: entry.name });
60
+ }
61
+ else if (entry.isFile() && entry.name.endsWith(".txt")) {
62
+ loose.push(await fileOf(path.join(folder, entry.name), stamped.rest.slice(0, -".txt".length), stamped.at));
63
+ }
64
+ }
65
+ loose.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.path.localeCompare(b.path));
66
+ const groups = [];
67
+ for (const file of loose) {
68
+ const parameters = await parametersOf(file);
69
+ const home = [...groups].reverse().find((group) => !group.files.some((each) => each.channel === file.channel) && (!parameters || !group.parameters || group.parameters === parameters));
70
+ if (home) {
71
+ home.files.push(file);
72
+ if (parameters && !home.parameters)
73
+ home.parameters = parameters;
74
+ }
75
+ else
76
+ groups.push({ files: [file], ...(parameters ? { parameters } : {}) });
77
+ }
78
+ const sessions = groups.map(({ files, parameters }) => sessionOf(files, parameters));
79
+ for (const { crash, dir, name } of crashes) {
80
+ const files = [];
81
+ let report;
82
+ for (const inner of await readdir(dir, { withFileTypes: true })) {
83
+ if (!inner.isFile() || !inner.name.endsWith(".txt"))
84
+ continue;
85
+ if (inner.name === `${name}.txt`)
86
+ report = path.join(dir, inner.name);
87
+ // The crash's own files (report, NGDP, Streaming, Variables) carry the folder's name after the stamp; the session's are plain channels.
88
+ const stamped = stampOf(inner.name);
89
+ if (stamped && !stamped.rest.startsWith(stampOf(name).rest))
90
+ files.push(await fileOf(path.join(dir, inner.name), stamped.rest.slice(0, -".txt".length), stamped.at));
91
+ }
92
+ let parameters;
93
+ for (const file of files)
94
+ parameters ??= await parametersOf(file);
95
+ sessions.push(sessionOf(files, parameters, { ...crash, ...(report ? { report } : {}) }));
96
+ }
97
+ return sessions.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());
98
+ }
99
+ function sessionOf(files, parameters, crash) {
100
+ const created = files.map((file) => file.createdAt.getTime());
101
+ const modified = files.map((file) => file.modifiedAt.getTime());
102
+ const startedAt = new Date(Math.min(...created, ...(crash ? [crash.at.getTime()] : [])));
103
+ const endedAt = new Date(Math.max(...modified, ...(crash ? [crash.at.getTime()] : [])));
104
+ return { startedAt, endedAt, ...(parameters ? { parameters } : {}), files, ...(crash ? { crash } : {}) };
105
+ }
106
+ const SLACK_MS = 2000;
107
+ export function selectSessions(sessions, selection) {
108
+ const matching = sessions.filter((session) => {
109
+ if (selection.after && session.startedAt.getTime() < selection.after.getTime() - SLACK_MS)
110
+ return false;
111
+ if (selection.before && session.startedAt.getTime() >= selection.before.getTime())
112
+ return false;
113
+ if (session.crash && selection.pids?.includes(session.crash.pid))
114
+ return true;
115
+ if (!selection.parameters)
116
+ return true;
117
+ return session.parameters !== undefined && selection.parameters.some((part) => session.parameters.includes(part));
118
+ });
119
+ return selection.latest ? matching.slice(-1) : matching;
120
+ }
121
+ const RULE = /^=+$/;
122
+ /** A line's channel prefix in Alerts-style files (`USER 0 0.000 0.062 `) and Text-style ones (`TextError 06:01:32.000 `). */
123
+ const PREFIX = /^[A-Za-z]+[ \t]+(?:\d+[ \t]+\d+\.\d+[ \t]+\d+\.\d+|\d\d:\d\d:\d\d\.\d+)[ \t]?/;
124
+ /** The `[ 13 1]` object stamp some Alerts lines carry: differs per line, so it's not part of the message. */
125
+ const OBJECT_STAMP = /^\[\s*[0-9a-f]+\s+\d+\]\s*/i;
126
+ /** A throttle notice after an error, not an error of its own. */
127
+ const THROTTLE = /^Final report for this error/;
128
+ /** The messages of one file, repeats included, in order: its header skipped, a continuation line joined to its error. */
129
+ export function parseLogMessages(text) {
130
+ const messages = [];
131
+ let inHeader;
132
+ let headerRules = 0;
133
+ for (const raw of text.replace(/^\uFEFF/, "").split(/\r?\n/)) {
134
+ const line = raw.replace(PREFIX, "");
135
+ if (inHeader === undefined) {
136
+ if (line.trim() === "")
137
+ continue;
138
+ inHeader = RULE.test(line.trim());
139
+ if (inHeader) {
140
+ headerRules = 1;
141
+ continue;
142
+ }
143
+ }
144
+ else if (inHeader) {
145
+ if (RULE.test(line.trim())) {
146
+ headerRules++;
147
+ if (headerRules === 2)
148
+ inHeader = false;
149
+ }
150
+ continue;
151
+ }
152
+ if (line.trim() === "" || RULE.test(line.trim()))
153
+ continue;
154
+ const text = line.replace(OBJECT_STAMP, "");
155
+ if (THROTTLE.test(text.trim()))
156
+ continue;
157
+ if (/^\s/.test(line) && messages.length > 0)
158
+ messages[messages.length - 1] += ` | ${text.trim()}`;
159
+ else
160
+ messages.push(text.trim());
161
+ }
162
+ return messages;
163
+ }
164
+ /** The distinct errors across a session's error channels, most frequent first. */
165
+ export async function readSessionErrors(session) {
166
+ const found = new Map();
167
+ for (const file of session.files) {
168
+ if (!ERROR_CHANNELS.includes(file.channel))
169
+ continue;
170
+ for (const message of parseLogMessages(await readFile(file.path, "utf8"))) {
171
+ const entry = found.get(message) ?? { count: 0, channels: new Set() };
172
+ entry.count++;
173
+ entry.channels.add(file.channel);
174
+ found.set(message, entry);
175
+ }
176
+ }
177
+ return [...found].map(([message, { count, channels }]) => ({ message, count, channels: [...channels] })).sort((a, b) => b.count - a.count || a.message.localeCompare(b.message));
178
+ }
@@ -0,0 +1,37 @@
1
+ import { type GameProcess } from "../plugins/plugin-api.js";
2
+ /** What quitting a game does to the machine. */
3
+ export type GameSystem = {
4
+ /** Every running game, with the start time the machine reports. */
5
+ readonly list: () => Promise<GameProcess[]>;
6
+ /** Asks this game to quit: the key or the window close that brings up its Confirm Exit dialog. */
7
+ readonly requestQuit: (pid: number) => Promise<void>;
8
+ /** Presses Yes in this game's Confirm Exit dialog. */
9
+ readonly confirmQuit: (pid: number) => Promise<void>;
10
+ /** Ends this process at once. */
11
+ readonly kill: (pid: number) => Promise<void>;
12
+ readonly sleep: (seconds: number) => Promise<void>;
13
+ };
14
+ /** How long the game may take to go after Yes, in seconds, before its process is killed. */
15
+ export declare const QUIT_GRACE_SECONDS = 20;
16
+ export declare const sameGame: (a: GameProcess, b: GameProcess) => boolean;
17
+ /** Whether this exact process (the pid and its start time) still runs: a reused pid isn't it. */
18
+ export declare function stillRuns(game: GameProcess, system: GameSystem): Promise<boolean>;
19
+ /** Rejects with the refusal when any game runs: a capture that isn't attaching never quits one it didn't start. */
20
+ export declare function refuseForeignGame(system: GameSystem): Promise<void>;
21
+ /**
22
+ * The game a capture started, once there is one. Before the capture starts any, none ran
23
+ * (refuseForeignGame), so the first game that appears is its own: recorded through `onStarted`, and
24
+ * from then on the only one `running` asks about.
25
+ */
26
+ export declare function ownedGame(system: GameSystem, onStarted?: (game: GameProcess) => void): {
27
+ /** The game, once found. */
28
+ game: () => GameProcess | undefined;
29
+ /** Whether the game this capture started runs; false while it hasn't started one. */
30
+ running(): Promise<boolean>;
31
+ };
32
+ /**
33
+ * Quits this game and no other, gracefully: the quit request, then Yes, then up to `graceSeconds` for it
34
+ * to exit, then SIGKILL on its pid if it is still the same process. "gone" when no process matches
35
+ * the pid and start time; "closed" when it exited on its own; "killed" after the timeout. Logs which.
36
+ */
37
+ export declare function quitOwnedGame(game: GameProcess, system: GameSystem, log: (line: string) => void, graceSeconds?: number): Promise<"closed" | "killed" | "gone">;
@@ -0,0 +1,84 @@
1
+ // Which games a capture may quit, and how, for both Host Adapters. The Editor Broker records each
2
+ // game a job starts as its pid and start time (a pid is reused once its process exits); a capture
3
+ // quits only a game it recorded, by pid, never every game process, since the author may be playing
4
+ // one. The quit is the game's own, so it writes its logs on the way out: a quit request (Mac:
5
+ // Cmd+Option+Q; Windows: close the window), then Yes in its Confirm Exit dialog; the process is
6
+ // killed only if it hasn't exited by a timeout. All of it runs against a `GameSystem`, which the
7
+ // adapters give their machine's and the tests a fake process table.
8
+ import { FOREIGN_GAME_REFUSAL } from "../plugins/plugin-api.js";
9
+ /** How long the game may take to go after Yes, in seconds, before its process is killed. */
10
+ export const QUIT_GRACE_SECONDS = 20;
11
+ /** How long the dialog may take to show after the quit request, in seconds. */
12
+ const DIALOG_SECONDS = 1.5;
13
+ const POLL_SECONDS = 0.5;
14
+ export const sameGame = (a, b) => a.pid === b.pid && a.startedAt === b.startedAt;
15
+ /** Whether this exact process (the pid and its start time) still runs: a reused pid isn't it. */
16
+ export async function stillRuns(game, system) {
17
+ return (await system.list()).some((each) => sameGame(each, game));
18
+ }
19
+ /** Rejects with the refusal when any game runs: a capture that isn't attaching never quits one it didn't start. */
20
+ export async function refuseForeignGame(system) {
21
+ if ((await system.list()).length > 0)
22
+ throw new Error(FOREIGN_GAME_REFUSAL);
23
+ }
24
+ /**
25
+ * The game a capture started, once there is one. Before the capture starts any, none ran
26
+ * (refuseForeignGame), so the first game that appears is its own: recorded through `onStarted`, and
27
+ * from then on the only one `running` asks about.
28
+ */
29
+ export function ownedGame(system, onStarted) {
30
+ let own;
31
+ return {
32
+ /** The game, once found. */
33
+ game: () => own,
34
+ /** Whether the game this capture started runs; false while it hasn't started one. */
35
+ async running() {
36
+ const games = await system.list();
37
+ if (!own) {
38
+ own = games[0];
39
+ if (own)
40
+ onStarted?.(own);
41
+ }
42
+ return own !== undefined && games.some((each) => sameGame(each, own));
43
+ },
44
+ };
45
+ }
46
+ /**
47
+ * Quits this game and no other, gracefully: the quit request, then Yes, then up to `graceSeconds` for it
48
+ * to exit, then SIGKILL on its pid if it is still the same process. "gone" when no process matches
49
+ * the pid and start time; "closed" when it exited on its own; "killed" after the timeout. Logs which.
50
+ */
51
+ export async function quitOwnedGame(game, system, log, graceSeconds = QUIT_GRACE_SECONDS) {
52
+ if (!(await stillRuns(game, system))) {
53
+ log(`game ${game.pid} isn't running (or its pid was reused): left alone`);
54
+ return "gone";
55
+ }
56
+ const attempt = async (what, press) => {
57
+ try {
58
+ await press(game.pid);
59
+ }
60
+ catch (error) {
61
+ log(`couldn't send ${what} to game ${game.pid}: ${error.message}`);
62
+ }
63
+ };
64
+ await attempt("the quit request", system.requestQuit);
65
+ await system.sleep(DIALOG_SECONDS);
66
+ if (await stillRuns(game, system))
67
+ await attempt("Yes", system.confirmQuit);
68
+ for (let waited = 0; waited < graceSeconds; waited += POLL_SECONDS) {
69
+ if (!(await stillRuns(game, system))) {
70
+ log(`game ${game.pid} quit gracefully (quit request, then Yes)`);
71
+ return "closed";
72
+ }
73
+ await system.sleep(POLL_SECONDS);
74
+ }
75
+ // Checked again at the last moment: a process that exited and whose pid was reused isn't ours to kill.
76
+ if (!(await stillRuns(game, system))) {
77
+ log(`game ${game.pid} quit gracefully (quit request, then Yes)`);
78
+ return "closed";
79
+ }
80
+ log(`game ${game.pid} still running ${graceSeconds} s after the quit request and Yes: killing it`);
81
+ await system.kill(game.pid).catch((error) => log(`couldn't kill game ${game.pid}: ${error.message}`));
82
+ await system.sleep(1);
83
+ return "killed";
84
+ }
@@ -0,0 +1,63 @@
1
+ import type { Host } from "./host.js";
2
+ import { type GameCrash, type SessionSelection } from "./game-logs.js";
3
+ /** How long a pattern may go unmatched, in days, before the report flags it. */
4
+ export declare const STALE_DAYS = 30;
5
+ export type ReportedError = {
6
+ readonly message: string;
7
+ readonly count: number;
8
+ readonly channels: readonly string[];
9
+ /** The known-error pattern that knows it; absent for a new error. */
10
+ readonly known?: {
11
+ readonly level: "workspace" | "mission";
12
+ readonly list: string;
13
+ readonly match: string;
14
+ readonly reason: string;
15
+ };
16
+ };
17
+ export type SessionReport = {
18
+ readonly startedAt: string;
19
+ readonly endedAt: string;
20
+ readonly parameters?: string;
21
+ readonly crash?: {
22
+ readonly kind: GameCrash["kind"];
23
+ readonly folder: string;
24
+ readonly report?: string;
25
+ };
26
+ /** Every distinct error, most frequent first. */
27
+ readonly errors: readonly ReportedError[];
28
+ /** How many distinct errors no list knows. */
29
+ readonly newErrors: number;
30
+ };
31
+ export type StalePattern = {
32
+ readonly level: "workspace" | "mission";
33
+ readonly list: string;
34
+ readonly match: string;
35
+ readonly reason: string;
36
+ readonly days: number;
37
+ };
38
+ export type RunLogReport = {
39
+ readonly folder: string;
40
+ readonly sessions: readonly SessionReport[];
41
+ /** Patterns of the lists that applied, which no run has matched for STALE_DAYS. */
42
+ readonly stale: readonly StalePattern[];
43
+ /** Why there is nothing to report, when there isn't. */
44
+ readonly note?: string;
45
+ };
46
+ export type RunLogOptions = {
47
+ readonly host: Host;
48
+ readonly workspaceRoot: string;
49
+ /** The Mission's folder (beside its Blueprint), for its own list. */
50
+ readonly missionDir?: string;
51
+ readonly selection: SessionSelection;
52
+ /** Now, for the stale check and a proposed pattern's date. */
53
+ readonly now?: Date;
54
+ };
55
+ /**
56
+ * Reads the GameLogs of the sessions `selection` names and reports them against the two lists.
57
+ * Without a Host Adapter that names its GameLogs folder, there is nothing to read, and the report
58
+ * says so. The patterns it matched are recorded in the machine's cache folder, which is how a
59
+ * pattern no run matches is told from one that just hasn't been needed.
60
+ */
61
+ export declare function reportRunLogs(options: RunLogOptions): Promise<RunLogReport>;
62
+ /** The report as lines for a tool's reply. */
63
+ export declare function formatRunLogReport(report: RunLogReport, heading: string, now?: Date): string[];
@@ -0,0 +1,119 @@
1
+ // What a tool says about a game run's logs: after a run that quit, the crash or error report, each
2
+ // distinct error with its count, and which are new, that is, which neither known-error list
3
+ // (Workspace, then Mission; known-errors.ts) knows. Also the patterns no run has matched in a
4
+ // while, which the author may remove.
5
+ import { existsSync } from "node:fs";
6
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { readGameSessions, readSessionErrors, selectSessions } from "./game-logs.js";
9
+ import { KNOWN_ERRORS_FILE, knownBy, matches, proposePattern, readKnownErrors } from "./known-errors.js";
10
+ /** How long a pattern may go unmatched, in days, before the report flags it. */
11
+ export const STALE_DAYS = 30;
12
+ /** The most distinct errors a report lists for one session; the rest are counted. */
13
+ const MAX_LISTED = 12;
14
+ const day = (date) => date.toISOString().slice(0, 10);
15
+ /**
16
+ * Reads the GameLogs of the sessions `selection` names and reports them against the two lists.
17
+ * Without a Host Adapter that names its GameLogs folder, there is nothing to read, and the report
18
+ * says so. The patterns it matched are recorded in the machine's cache folder, which is how a
19
+ * pattern no run matches is told from one that just hasn't been needed.
20
+ */
21
+ export async function reportRunLogs(options) {
22
+ const { host, selection } = options;
23
+ const now = options.now ?? new Date();
24
+ if (!host.has("game.logsFolder"))
25
+ return { folder: "", sessions: [], stale: [], note: "the machine's Host Adapter doesn't name the game's log folder, so its logs weren't read" };
26
+ const folder = await host.run("game.logsFolder", {});
27
+ const sessions = selectSessions(await readGameSessions(folder), selection);
28
+ if (sessions.length === 0)
29
+ return { folder, sessions: [], stale: [], note: `no game session in ${folder} matches this run (its logs are written when the game quits; a game killed may have left none)` };
30
+ const lists = [
31
+ { level: "workspace", file: path.join(options.workspaceRoot, KNOWN_ERRORS_FILE) },
32
+ ...(options.missionDir ? [{ level: "mission", file: path.join(options.missionDir, KNOWN_ERRORS_FILE) }] : []),
33
+ ];
34
+ const patterns = [];
35
+ for (const { level, file } of lists) {
36
+ const list = path.relative(options.workspaceRoot, file).split(path.sep).join("/");
37
+ try {
38
+ patterns.push(...(await readKnownErrors(file, list)).map((pattern) => ({ ...pattern, level, list })));
39
+ }
40
+ catch (error) {
41
+ return { folder, sessions: [], stale: [], note: `${error.message}; fix it, or run check` };
42
+ }
43
+ }
44
+ const matched = new Set();
45
+ const reports = [];
46
+ for (const session of sessions) {
47
+ const errors = (await readSessionErrors(session)).map((error) => {
48
+ const pattern = knownBy(patterns, error.message);
49
+ for (const each of patterns)
50
+ if (matches(each, error.message))
51
+ matched.add(keyOf(each));
52
+ return { ...error, ...(pattern ? { known: { level: pattern.level, list: pattern.list, match: pattern.match, reason: pattern.reason } } : {}) };
53
+ });
54
+ reports.push({
55
+ startedAt: session.startedAt.toISOString(),
56
+ endedAt: session.endedAt.toISOString(),
57
+ ...(session.parameters ? { parameters: session.parameters } : {}),
58
+ ...(session.crash ? { crash: { kind: session.crash.kind, folder: session.crash.folder, ...(session.crash.report ? { report: session.crash.report } : {}) } } : {}),
59
+ errors,
60
+ newErrors: errors.filter((error) => !error.known).length,
61
+ });
62
+ }
63
+ const stale = await staleAfterRun(host, patterns, matched, now);
64
+ return { folder, sessions: reports, stale };
65
+ }
66
+ const keyOf = (pattern) => `${pattern.list}\u0000${pattern.regex ? "re:" : ""}${pattern.match}`;
67
+ /** Records this run's matches, and lists the patterns last matched (else added) over STALE_DAYS ago. No cache folder, no record, no flags. */
68
+ async function staleAfterRun(host, patterns, matched, now) {
69
+ const cacheDir = host.machine.cacheDir;
70
+ if (!cacheDir || patterns.length === 0)
71
+ return [];
72
+ const file = path.join(cacheDir, "known-error-hits.json");
73
+ let hits = {};
74
+ try {
75
+ if (existsSync(file))
76
+ hits = JSON.parse(await readFile(file, "utf8"));
77
+ }
78
+ catch {
79
+ hits = {};
80
+ }
81
+ for (const key of matched)
82
+ hits[key] = now.toISOString();
83
+ try {
84
+ await mkdir(cacheDir, { recursive: true });
85
+ await writeFile(file, `${JSON.stringify(hits, null, 2)}\n`);
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ return patterns.flatMap((pattern) => {
91
+ const last = new Date(hits[keyOf(pattern)] ?? `${pattern.added}T00:00:00Z`);
92
+ const days = Math.floor((now.getTime() - last.getTime()) / 86_400_000);
93
+ return days >= STALE_DAYS ? [{ level: pattern.level, list: pattern.list, match: pattern.match, reason: pattern.reason, days }] : [];
94
+ });
95
+ }
96
+ /** The report as lines for a tool's reply. */
97
+ export function formatRunLogReport(report, heading, now = new Date()) {
98
+ if (report.sessions.length === 0)
99
+ return report.note ? [`${heading}: ${report.note}`] : [];
100
+ const lines = [];
101
+ for (const session of report.sessions) {
102
+ const what = session.crash ? `${session.crash.kind.toUpperCase()}: the game left ${session.crash.folder}${session.crash.report ? ` (report: ${session.crash.report})` : ""}` : "no crash";
103
+ lines.push(`${heading} (game session ${session.startedAt} to ${session.endedAt}): ${what}; ${session.errors.length} distinct error${session.errors.length === 1 ? "" : "s"}, ${session.newErrors} new`);
104
+ const listed = [...session.errors.filter((error) => !error.known), ...session.errors.filter((error) => error.known)].slice(0, MAX_LISTED);
105
+ for (const error of listed)
106
+ lines.push(` ${error.known ? "known" : "NEW "} x${error.count} [${error.channels.join(", ")}] ${error.message}${error.known ? ` (${error.known.level} list: ${error.known.reason})` : ""}`);
107
+ if (session.errors.length > listed.length)
108
+ lines.push(` and ${session.errors.length - listed.length} more distinct errors`);
109
+ const fresh = session.errors.filter((error) => !error.known).slice(0, 3);
110
+ if (fresh.length > 0) {
111
+ lines.push(` To call a new error known, the author adds a pattern with a reason to ${KNOWN_ERRORS_FILE} (the Workspace's root for every Mission, or beside the Mission's Blueprint for this one), for example:`);
112
+ for (const error of fresh)
113
+ lines.push(` ${JSON.stringify(proposePattern(error.message, day(now)))}`);
114
+ }
115
+ }
116
+ for (const pattern of report.stale)
117
+ lines.push(` Unmatched for ${pattern.days} days, so maybe remove it from ${pattern.list}: "${pattern.match}" (${pattern.reason})`);
118
+ return lines;
119
+ }
@@ -0,0 +1,34 @@
1
+ import { z } from "zod";
2
+ /** The file name of both lists. */
3
+ export declare const KNOWN_ERRORS_FILE = "known-errors.json";
4
+ declare const KnownPatternSchema: z.ZodObject<{
5
+ match: z.ZodString;
6
+ regex: z.ZodOptional<z.ZodBoolean>;
7
+ reason: z.ZodString;
8
+ added: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export declare const KnownErrorsSchema: z.ZodObject<{
11
+ patterns: z.ZodArray<z.ZodObject<{
12
+ match: z.ZodString;
13
+ regex: z.ZodOptional<z.ZodBoolean>;
14
+ reason: z.ZodString;
15
+ added: z.ZodString;
16
+ }, z.core.$strict>>;
17
+ }, z.core.$strict>;
18
+ export type KnownPattern = z.infer<typeof KnownPatternSchema>;
19
+ /** The patterns of a known-errors file's text, `file` naming it in the error when they don't read. */
20
+ export declare function parseKnownErrors(text: string, file: string): KnownPattern[];
21
+ /** The list at `absolute`: none when there's no file. `file` names it for the author. */
22
+ export declare function readKnownErrors(absolute: string, file: string): Promise<KnownPattern[]>;
23
+ /** A known pattern with the list it came from. */
24
+ export type ListedPattern = KnownPattern & {
25
+ readonly level: "workspace" | "mission";
26
+ readonly list: string;
27
+ };
28
+ /** Whether this pattern's text is in the message. */
29
+ export declare function matches(pattern: KnownPattern, message: string): boolean;
30
+ /** The first pattern that knows the message; the Mission's own come after the Workspace's, so the Workspace's reason shows when both match. */
31
+ export declare function knownBy(patterns: readonly ListedPattern[], message: string): ListedPattern | undefined;
32
+ /** A pattern to propose for a new error: its message as the text to match, with the reason left to the author. */
33
+ export declare function proposePattern(message: string, today: string): KnownPattern;
34
+ export {};
@@ -0,0 +1,73 @@
1
+ // Known-error lists: errors the author has judged harmless or already understood, so a report of a
2
+ // game's logs leaves them out of what's new. Two lists, both in the Workspace and both the
3
+ // author's: `known-errors.json` at the Workspace root applies to every Mission, and a Mission's
4
+ // own, beside its Blueprint, adds to it. Each pattern has a reason. A tool may propose a pattern
5
+ // (the report prints one for each new error); only the author adds one.
6
+ import { existsSync } from "node:fs";
7
+ import { readFile } from "node:fs/promises";
8
+ import { z } from "zod";
9
+ import { formatIssues } from "../util/format-issues.js";
10
+ /** The file name of both lists. */
11
+ export const KNOWN_ERRORS_FILE = "known-errors.json";
12
+ const KnownPatternSchema = z
13
+ .object({
14
+ /** Text a message contains, or, with `regex`, a regular expression it matches. */
15
+ match: z.string().min(1),
16
+ regex: z.boolean().optional(),
17
+ /** Why it's known: what makes it harmless, or the ticket that tracks it. */
18
+ reason: z.string().trim().min(1, "a pattern needs a reason"),
19
+ /** The day the author added it, `YYYY-MM-DD`: a pattern no run has matched since is flagged for removal. */
20
+ added: z.string().regex(/^\d{4}-\d\d-\d\d$/, "added is a date, YYYY-MM-DD"),
21
+ })
22
+ .strict()
23
+ .superRefine((pattern, context) => {
24
+ if (!pattern.regex)
25
+ return;
26
+ try {
27
+ new RegExp(pattern.match);
28
+ }
29
+ catch (error) {
30
+ context.addIssue({ code: "custom", path: ["match"], message: `isn't a regular expression: ${error.message}` });
31
+ }
32
+ });
33
+ export const KnownErrorsSchema = z
34
+ .object({ patterns: z.array(KnownPatternSchema) })
35
+ .strict()
36
+ .superRefine((list, context) => {
37
+ list.patterns.forEach((pattern, index) => {
38
+ if (list.patterns.findIndex((each) => each.match === pattern.match && !!each.regex === !!pattern.regex) < index)
39
+ context.addIssue({ code: "custom", path: ["patterns", index, "match"], message: "is listed twice" });
40
+ });
41
+ });
42
+ /** The patterns of a known-errors file's text, `file` naming it in the error when they don't read. */
43
+ export function parseKnownErrors(text, file) {
44
+ let json;
45
+ try {
46
+ json = JSON.parse(text);
47
+ }
48
+ catch (error) {
49
+ throw new Error(`${file} isn't JSON: ${error.message}`);
50
+ }
51
+ const parsed = KnownErrorsSchema.safeParse(json);
52
+ if (!parsed.success)
53
+ throw new Error(`${file} isn't a known-errors list: ${formatIssues(parsed.error, "(file)")}`);
54
+ return parsed.data.patterns;
55
+ }
56
+ /** The list at `absolute`: none when there's no file. `file` names it for the author. */
57
+ export async function readKnownErrors(absolute, file) {
58
+ if (!existsSync(absolute))
59
+ return [];
60
+ return parseKnownErrors(await readFile(absolute, "utf8"), file);
61
+ }
62
+ /** Whether this pattern's text is in the message. */
63
+ export function matches(pattern, message) {
64
+ return pattern.regex ? new RegExp(pattern.match).test(message) : message.includes(pattern.match);
65
+ }
66
+ /** The first pattern that knows the message; the Mission's own come after the Workspace's, so the Workspace's reason shows when both match. */
67
+ export function knownBy(patterns, message) {
68
+ return patterns.find((pattern) => matches(pattern, message));
69
+ }
70
+ /** A pattern to propose for a new error: its message as the text to match, with the reason left to the author. */
71
+ export function proposePattern(message, today) {
72
+ return { match: message, reason: "TODO(author): why this is known", added: today };
73
+ }
@@ -13,11 +13,13 @@ export declare const EXAMPLE_WORKSPACE: string;
13
13
  export declare const WORKSPACE_GITIGNORE: string;
14
14
  /** The core CLIs a Workspace runs, as its package.json's scripts: `npm run <name> -- …` from the Workspace's folder. */
15
15
  export declare const WORKSPACE_SCRIPTS: Readonly<Record<string, string>>;
16
+ /** The Utilities every new Workspace gets, as `bundled:<name>`: installed with it and listed in its config's `utilities`. */
17
+ export declare const DEFAULT_UTILITIES: readonly string[];
16
18
  /** The Host Adapter for a platform, as `bundled:<name>`: none on Linux, which has no Editor. */
17
19
  export declare function platformHostAdapter(platform: NodeJS.Platform): string | undefined;
18
20
  /** A Workspace's package name, from its folder's: lowercase, with a hyphen for each run of anything npm's names can't hold. */
19
21
  export declare function workspacePackageName(folder: string): string;
20
- /** The new Workspace's package.json: core and the Host Adapter package at core's version, and core's CLIs as scripts. */
22
+ /** The new Workspace's package.json: core, the Host Adapter package and the default Utilities' packages at core's version, and core's CLIs as scripts. */
21
23
  export declare function workspacePackageJson(name: string, coreVersion: string, hostAdapter: string | undefined): Record<string, unknown>;
22
24
  /** What happened to the machine config. */
23
25
  export type MachineConfigResult =
@@ -57,6 +57,8 @@ export const WORKSPACE_SCRIPTS = {
57
57
  "import-mod": "import-mod",
58
58
  "model-anims": "record-model-anims",
59
59
  };
60
+ /** The Utilities every new Workspace gets, as `bundled:<name>`: installed with it and listed in its config's `utilities`. */
61
+ export const DEFAULT_UTILITIES = ["bundled:anim-testbed"];
60
62
  /** The Host Adapter for a platform, as `bundled:<name>`: none on Linux, which has no Editor. */
61
63
  export function platformHostAdapter(platform) {
62
64
  if (platform === "darwin")
@@ -74,10 +76,11 @@ export function workspacePackageName(folder) {
74
76
  .replace(/^[._-]+|[-]+$/g, "");
75
77
  return name || "sc2-adjutant-workspace";
76
78
  }
77
- /** The new Workspace's package.json: core and the Host Adapter package at core's version, and core's CLIs as scripts. */
79
+ /** The new Workspace's package.json: core, the Host Adapter package and the default Utilities' packages at core's version, and core's CLIs as scripts. */
78
80
  export function workspacePackageJson(name, coreVersion, hostAdapter) {
79
81
  const range = `^${coreVersion}`;
80
82
  const adapterPackage = hostAdapter ? BUNDLED_PACKAGES[hostAdapter.slice("bundled:".length)] : undefined;
83
+ const utilityPackages = DEFAULT_UTILITIES.map((source) => BUNDLED_PACKAGES[source.slice("bundled:".length)]);
81
84
  const cli = (file) => `node node_modules/${CORE_PACKAGE}/dist/cli/${file}.js`;
82
85
  return {
83
86
  name,
@@ -92,6 +95,7 @@ export function workspacePackageJson(name, coreVersion, hostAdapter) {
92
95
  dependencies: {
93
96
  [CORE_PACKAGE]: range,
94
97
  ...(adapterPackage ? { [adapterPackage]: range } : {}),
98
+ ...Object.fromEntries(utilityPackages.map((pkg) => [pkg, range])),
95
99
  },
96
100
  };
97
101
  }
@@ -177,6 +181,11 @@ export async function initWorkspace({ folder, install = true, runInstall = npmIn
177
181
  await cp(example, root, { recursive: true, filter: leftOut(example), force: false });
178
182
  await writeFile(path.join(root, ".gitignore"), WORKSPACE_GITIGNORE);
179
183
  await writeFile(path.join(root, "package.json"), `${JSON.stringify(workspacePackageJson(workspacePackageName(root), version, hostAdapter), null, 2)}\n`);
184
+ // The default Utilities join any the example lists.
185
+ const configFile = path.join(root, WORKSPACE_FILE);
186
+ const config = JSON.parse(await readFile(configFile, "utf8"));
187
+ const utilities = [...(config.utilities ?? []), ...DEFAULT_UTILITIES.filter((source) => !(config.utilities ?? []).includes(source))];
188
+ await writeFile(configFile, `${JSON.stringify({ ...config, utilities }, null, 2)}\n`);
180
189
  const machineConfig = await writeMachineConfig(env, platform);
181
190
  if (!install)
182
191
  return { root, ...(hostAdapter ? { hostAdapter } : {}), installed: false, machineConfig, skillsNote: "not copied: npm install wasn't run" };