cli-diagnostic-evidence-smoke.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. import assert from "node:assert/strict";
  2. import { spawn } from "node:child_process";
  3. import { createHash } from "node:crypto";
  4. import { mkdir, mkdtemp, readFile, readdir, stat, utimes, writeFile } from "node:fs/promises";
  5. import { createRequire } from "node:module";
  6. import { dirname, join, resolve } from "node:path";
  7. import { fileURLToPath, pathToFileURL } from "node:url";
  8. import { build } from "esbuild";
  9. import yauzl from "yauzl";
  10. // 运行时验收仅操作独立 fixture;不注册产品退出钩子,不创建真实会话。
  11. const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
  12. const outputRoot = resolve(
  13. process.argv[2] ?? join(root, "packages/desktop/.e2e-artifacts", `cli-diagnostics-${Date.now()}`),
  14. );
  15. await mkdir(outputRoot, { recursive: true });
  16. const output = await mkdtemp(join(outputRoot, "run-"));
  17. const require = createRequire(join(root, "package.json"));
  18. const runtime = process.argv[3] ?? require("electron");
  19. const memorySource = join(root, "apps/zcode-cli/packages/adapters/src/memory-diagnostics/index.ts");
  20. const archiveSource = join(root, "packages/services/src/feedback/feedbackLogArchive.ts");
  21. const collectorSource = join(root, "packages/services/src/zcode-agent/agentStderrCollector.ts");
  22. const report = { platform: process.platform, runtime, checks: [], children: [], sourceHashes: {} };
  23. for (const path of [
  24. memorySource,
  25. archiveSource,
  26. collectorSource,
  27. join(dirname(memorySource), "recorder.ts"),
  28. join(root, "packages/shared/src/memoryDiagnostics.ts"),
  29. join(root, "packages/shared/src/feedbackPrivacy.ts"),
  30. join(root, "packages/shared/src/agent-crash-diagnostic/agentCrashDiagnostic.ts"),
  31. ]) {
  32. report.sourceHashes[path.slice(root.length + 1)] = createHash("sha256")
  33. .update(await readFile(path))
  34. .digest("hex");
  35. }
  36. async function bundle(source, name, minify = false) {
  37. const path = join(output, name);
  38. await build({
  39. stdin: { contents: source, resolveDir: root, loader: "ts" },
  40. outfile: path,
  41. platform: "node",
  42. format: "cjs",
  43. bundle: true,
  44. minify,
  45. sourcemap: false,
  46. logLevel: "silent",
  47. });
  48. return path;
  49. }
  50. const adapters = await bundle(
  51. `export { createFeedbackDiagnosticArchive } from ${JSON.stringify(archiveSource)};
  52. export { AgentStderrCollector, createAgentStderrTail } from ${JSON.stringify(collectorSource)};`,
  53. "adapters.cjs",
  54. );
  55. const { createFeedbackDiagnosticArchive, AgentStderrCollector, createAgentStderrTail } =
  56. await import(pathToFileURL(adapters).href);
  57. function unzip(path) {
  58. return new Promise((resolveZip, reject) => {
  59. yauzl.open(path, { lazyEntries: true }, (error, zip) => {
  60. if (error) return reject(error);
  61. const files = new Map();
  62. zip.on("error", reject);
  63. zip.on("entry", (entry) =>
  64. zip.openReadStream(entry, (readError, stream) => {
  65. if (readError) return reject(readError);
  66. const chunks = [];
  67. stream.on("error", reject);
  68. stream.on("data", (chunk) => chunks.push(chunk));
  69. stream.on("end", () => {
  70. files.set(entry.fileName, Buffer.concat(chunks).toString("utf8"));
  71. zip.readEntry();
  72. });
  73. }),
  74. );
  75. zip.on("end", () => resolveZip(files));
  76. zip.readEntry();
  77. });
  78. });
  79. }
  80. async function check(name, action) {
  81. try {
  82. const details = await action();
  83. report.checks.push({ name, passed: true, details });
  84. } catch (error) {
  85. report.checks.push({ name, passed: false, error: String(error) });
  86. }
  87. await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2));
  88. console.log(JSON.stringify(report.checks.at(-1)));
  89. }
  90. const crashMarker = "E2E_DIAGNOSTIC_FAILURE";
  91. const secret = "E2E_PRIVATE_CONTENT";
  92. await check("fatal-header-bounded-retention", async () => {
  93. const tail = createAgentStderrTail();
  94. tail.append(`FATAL ERROR: Reached heap limit token=${secret}`);
  95. for (let i = 0; i < 40; i++) tail.append(`${i}: 0x12345678 native_frame`);
  96. assert.equal(tail.snapshot().tail.length, 20);
  97. assert.match(tail.snapshot().tail[0], /^FATAL ERROR:/);
  98. assert.ok(!JSON.stringify(tail.snapshot()).includes(secret));
  99. tail.append("ordinary later warning");
  100. assert.ok(!tail.snapshot().tail.some((line) => line.startsWith("FATAL ERROR:")));
  101. });
  102. function exitLine(tail, code = 1, signal = null) {
  103. return `[2026-11-16 12:00:00] [error] [pid:123] [host] [zcode-agent] ZCode agent process exited unexpectedly ${JSON.stringify(
  104. {
  105. pid: 123,
  106. code,
  107. signal,
  108. terminationKind: "unexpected",
  109. stderr: { lineCount: tail.length, tail },
  110. },
  111. )}\n`;
  112. }
  113. async function archiveCase(name, body, budget, options = {}) {
  114. const directory = join(output, "logs", name);
  115. await mkdir(directory, { recursive: true });
  116. const path = join(directory, "app.log");
  117. await writeFile(path, body);
  118. if (options.yesterday) {
  119. const at = new Date(Date.now() - 86_400_000);
  120. await utimes(path, at, at);
  121. }
  122. const result = await createFeedbackDiagnosticArchive({
  123. sources: [{ directory, archivePrefix: "logs" }],
  124. outputRootDir: join(output, "archives", name),
  125. ...(budget ? { maxTotalBytes: budget } : {}),
  126. });
  127. return { files: await unzip(result.path), path: result.path };
  128. }
  129. function readCrashRecord(files) {
  130. const log = files.get("logs/app.log");
  131. assert.ok(log, "exit log missing from ZIP");
  132. return JSON.parse(log.slice(log.indexOf("{")));
  133. }
  134. for (const [format, address] of [
  135. ["prefixed", "0x1234abcd"],
  136. ["windows", "00007FF689BB5EBA"],
  137. ]) {
  138. for (const newline of ["\n", "\r\n"]) {
  139. await check(
  140. `native-stack-projection-${format}-${newline === "\n" ? "lf" : "crlf"}`,
  141. async () => {
  142. const frames = Array.from(
  143. { length: 5 },
  144. (_, i) =>
  145. ` ${i + 1}: ${address} ${format === "windows" ? `v8::internal::OOMErrorHandler${i}+878922` : `node::OOMErrorHandler${i}()`}`,
  146. );
  147. const tail = [
  148. `FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory token=${secret}`,
  149. ...frames,
  150. `TypeError: secondary failure context: ${secret}`,
  151. `RangeError: final failure password="${secret}"`,
  152. " at probe (zcode.cjs:7:19)",
  153. ];
  154. const { files, path } = await archiveCase(
  155. `native-stack-${format}-${newline.length}`,
  156. exitLine(
  157. tail.map((line, i) => (newline === "\r\n" && i < tail.length - 1 ? line + "\r" : line)),
  158. ),
  159. );
  160. const { agentCrash, stderr } = readCrashRecord(files);
  161. const lines = agentCrash.errorStack.split(/\r?\n/);
  162. assert.equal(agentCrash.errorCode, "ERR_OUT_OF_MEMORY");
  163. assert.match(lines[0], /^FATAL ERROR: Reached heap limit/);
  164. assert.deepEqual(lines.slice(1, 6), frames);
  165. assert.match(lines[6], /^TypeError: secondary failure/);
  166. assert.match(lines[7], /^RangeError: final failure/);
  167. assert.equal(lines[8], tail[8]);
  168. assert.equal(lines.length, tail.length);
  169. assert.equal(stderr, "[REDACTED]");
  170. assert.ok(!/token=|context:|password=/.test(agentCrash.errorStack));
  171. assert.ok(![...files.values()].join("\n").includes(secret));
  172. return { path, stackLines: lines.length, nativeFrames: frames.length };
  173. },
  174. );
  175. }
  176. }
  177. for (const [name, budget] of [["full"], ["compact", 2 * 1024 * 1024]]) {
  178. await check(`runtime-diagnostics-${name}`, async () => {
  179. const diagnostics = [
  180. [
  181. "Windows runtime host helper exit",
  182. {
  183. runId: "runtime-example",
  184. hostPid: 123,
  185. helperPid: 234,
  186. runtimePid: 345,
  187. code: 1,
  188. signal: null,
  189. rootSeen: false,
  190. empty: false,
  191. lastFrame: "started",
  192. closeSent: false,
  193. destroyReason: "none",
  194. },
  195. ],
  196. [
  197. "Windows runtime host native exit",
  198. {
  199. hostPid: 123,
  200. helperPid: 234,
  201. runtimePid: 345,
  202. nativeHostPid: 123,
  203. nativeHelperPid: 234,
  204. nativeRuntimePid: 345,
  205. reason: "control_lost",
  206. stage: "control_peek",
  207. win32Error: 109,
  208. running: true,
  209. rootExited: true,
  210. forced: true,
  211. jobEmpty: true,
  212. },
  213. ],
  214. ["main_schedule_delay", { pid: 123, delayedSampleCount: 2, maxDelayMs: 6000 }],
  215. ];
  216. const body =
  217. diagnostics
  218. .map(
  219. ([marker, fields]) =>
  220. `[2026-11-16 12:00:00] [warn] [pid:123] [resource] ${marker} ${JSON.stringify(fields)}\n`,
  221. )
  222. .join("") +
  223. `[2026-11-16 12:00:00] [info] [probe] ${JSON.stringify({ password: secret, stderr: secret })}\n`;
  224. const { files, path } = await archiveCase(`runtime-${name}`, body, budget);
  225. const lines = files.get("logs/app.log")?.trim().split("\n");
  226. assert.equal(lines?.length, diagnostics.length + 1);
  227. for (const [index, [marker, fields]] of diagnostics.entries()) {
  228. assert.ok(lines[index].includes(marker));
  229. assert.deepEqual(JSON.parse(lines[index].slice(lines[index].indexOf("{"))), fields);
  230. }
  231. assert.ok(![...files.values()].join("\n").includes(secret));
  232. return { path, diagnosticRecords: diagnostics.length };
  233. });
  234. }
  235. await check("error-header-leading-context", async () => {
  236. const { files, path } = await archiveCase(
  237. "leading-context",
  238. exitLine([
  239. `Error: token=${secret}`,
  240. `TypeError: context: ${secret}`,
  241. " at probe (zcode.cjs:7:19)",
  242. ]),
  243. );
  244. const { agentCrash } = readCrashRecord(files);
  245. const lines = agentCrash.errorStack.split(/\r?\n/);
  246. assert.equal(lines.length, 3);
  247. assert.match(lines[0], /^Error:[ \t]+\[REDACTED\]$/);
  248. assert.match(lines[1], /^TypeError:[ \t]+\[REDACTED\]$/);
  249. assert.equal(lines[2], " at probe (zcode.cjs:7:19)");
  250. assert.ok(![...files.values()].join("\n").includes(secret));
  251. return { path };
  252. });
  253. await check("stack-frame-privacy", async () => {
  254. const { files, path } = await archiveCase(
  255. "frame-privacy",
  256. exitLine([
  257. "FATAL ERROR: Reached heap limit",
  258. ` 1: 0x1234abcd node::OOMErrorHandler() token=${secret}`,
  259. ` 3: 00007FF689BB5EBA v8::internal::OOMErrorHandler+33 token=${secret}`,
  260. " 4: 00007FF8A5E9CC91 RtlUserThreadStart+33",
  261. " 5: 123 not_a_native_address",
  262. " 6: deadbeefg not_a_native_address",
  263. " 7: 12345678901234567 not_a_native_address",
  264. " 2: 0x2345bcde node::Abort()",
  265. ` at probe (zcode.cjs:7:19) password=${secret}`,
  266. " at caller (zcode.cjs:8:20)",
  267. ]),
  268. );
  269. const { agentCrash, stderr } = readCrashRecord(files);
  270. assert.match(agentCrash.errorStack, /^FATAL ERROR: Reached heap limit/m);
  271. assert.match(agentCrash.errorStack, /^ 2: 0x2345bcde node::Abort\(\)/m);
  272. assert.match(agentCrash.errorStack, /^ 4: 00007FF8A5E9CC91 RtlUserThreadStart\+33/m);
  273. assert.ok(!agentCrash.errorStack.includes("not_a_native_address"));
  274. assert.match(agentCrash.errorStack, /^ at caller \(zcode.cjs:8:20\)/m);
  275. assert.equal(stderr, "[REDACTED]");
  276. assert.ok(![...files.values()].join("\n").includes(secret));
  277. return { path };
  278. });
  279. for (const [mode, budget] of [["full"], ["compact", 2 * 1024 * 1024]]) {
  280. for (const newline of ["\n", "\r\n"]) {
  281. await check(`windows-native-frame-privacy-${mode}-${newline.length}`, async () => {
  282. const privateText = "SG01_PRIVATE_PLAIN_TEXT";
  283. const frames = [
  284. " 1: 00007FF689BB5EBA v8::internal::CallbackScope::~CallbackScope+33",
  285. " 2: 00007FF8A5E9CC91 RtlUserThreadStart+33",
  286. " 3: 00007FF689BB5EBA uv_run+42",
  287. ];
  288. const tail = [
  289. "FATAL ERROR: Reached heap limit",
  290. ...frames.map((frame) => `${frame} ${privateText} token=${secret}`),
  291. " 8: 20261120 private prompt text",
  292. " 9: 1380013800012345 secret words",
  293. ` 10: 2026112012345678 ${privateText}`,
  294. ` 11: 00007FF689BB5EBA ${privateText}`,
  295. ` 12: 00007FF689BB5EBA SymbolWithoutOffset ${privateText}`,
  296. ` 13: 00007FF689BB5EBA uv_run+42not_an_offset ${privateText}`,
  297. ];
  298. const { files, path } = await archiveCase(
  299. `windows-frame-privacy-${mode}-${newline.length}`,
  300. exitLine(tail.map((line) => line + (newline === "\r\n" ? "\r" : ""))),
  301. budget,
  302. );
  303. const { agentCrash, stderr } = readCrashRecord(files);
  304. assert.deepEqual(agentCrash.errorStack.split("\n"), [tail[0], ...frames]);
  305. assert.equal(stderr, "[REDACTED]");
  306. const exported = [...files.values()].join("\n");
  307. for (const text of [
  308. privateText,
  309. secret,
  310. "private prompt text",
  311. "secret words",
  312. "not_an_offset",
  313. "SymbolWithoutOffset",
  314. ])
  315. assert.ok(!exported.includes(text), `unexpected native frame body: ${text}`);
  316. return { path, nativeFrames: frames.length };
  317. });
  318. }
  319. }
  320. const errorLine = exitLine([
  321. `Error: ${crashMarker} token=${secret}`,
  322. " at probe (zcode.cjs:7:19)",
  323. " 1: 0x1234abcd node::OOMErrorHandler()",
  324. " 2: 00007FF8A5E9CC91 RtlUserThreadStart+33",
  325. `prompt: ${secret}`,
  326. ]);
  327. for (const [name, size, budget] of [
  328. ["full-large-log", 9 * 1024 * 1024],
  329. ["compact-large-log", 3 * 1024 * 1024, 2 * 1024 * 1024],
  330. ]) {
  331. await check(name, async () => {
  332. const routine = "[2026-11-16 12:00:00] [info] [probe] routine\n";
  333. const { files, path } = await archiveCase(
  334. name,
  335. routine.repeat(Math.ceil(size / routine.length)) + errorLine,
  336. budget,
  337. );
  338. const log = files.get("logs/app.log");
  339. assert.ok(log?.includes(crashMarker), "crash summary missing from ZIP");
  340. assert.ok(log.includes("agentCrash"));
  341. assert.ok(log.includes("zcode.cjs:7:19"));
  342. const { agentCrash } = readCrashRecord(
  343. new Map([["logs/app.log", log.trim().split("\n").at(-1)]]),
  344. );
  345. assert.ok(agentCrash.errorStack.includes(" 1: 0x1234abcd node::OOMErrorHandler()"));
  346. assert.ok(agentCrash.errorStack.includes(" 2: 00007FF8A5E9CC91 RtlUserThreadStart+33"));
  347. assert.ok(![...files.values()].join("\n").includes(secret));
  348. assert.match(files.get("about.txt"), /truncatedLogFiles: 1/);
  349. assert.ok(Buffer.byteLength(log) <= (budget ?? 8 * 1024 * 1024));
  350. return { path };
  351. });
  352. }
  353. await check("small-log-crash-projection", async () => {
  354. const { files, path } = await archiveCase(
  355. "small",
  356. errorLine + JSON.stringify({ event: "ordinary", stderr: secret, prompt: secret }) + "\n",
  357. );
  358. assert.ok(files.get("logs/app.log")?.includes(crashMarker));
  359. assert.ok(![...files.values()].join("\n").includes(secret));
  360. return { path };
  361. });
  362. await check("old-log-reason", async () => {
  363. const { files } = await archiveCase("old", errorLine, undefined, { yesterday: true });
  364. assert.ok(!files.has("logs/app.log"));
  365. assert.match(files.get("about.txt"), /not-current-day/);
  366. });
  367. for (const encoding of ["utf8", "utf16le", "utf16be"]) {
  368. await check(`tail-boundary-${encoding}`, async () => {
  369. const raw = `prompt: ${secret}\n${secret.repeat(1000)}\n` + errorLine + `partial:${secret}`;
  370. let bytes = Buffer.from(raw, encoding === "utf16be" ? "utf16le" : encoding);
  371. if (encoding !== "utf8") {
  372. bytes = Buffer.concat([Buffer.from([255, 254]), bytes]);
  373. if (encoding === "utf16be") bytes.swap16();
  374. }
  375. const { files, path } = await archiveCase(encoding, bytes, 4097);
  376. assert.ok(files.get("logs/app.log")?.includes(crashMarker));
  377. assert.ok(![...files.values()].join("\n").includes(secret));
  378. return { path };
  379. });
  380. }
  381. await check("source-reservation", async () => {
  382. const sources = [];
  383. for (const name of ["host", "cli"]) {
  384. const directory = join(output, "logs", `reserved-${name}`);
  385. await mkdir(directory, { recursive: true });
  386. await writeFile(
  387. join(directory, "app.log"),
  388. "[2026-11-16 12:00:00] [info] routine\n".repeat(2000) + errorLine,
  389. );
  390. sources.push({ directory, archivePrefix: name });
  391. }
  392. const result = await createFeedbackDiagnosticArchive({
  393. sources,
  394. maxTotalBytes: 8192,
  395. outputRootDir: join(output, "archives", "reserved"),
  396. });
  397. const files = await unzip(result.path);
  398. for (const name of ["host", "cli"])
  399. assert.ok(files.get(`${name}/app.log`)?.includes(crashMarker));
  400. return { path: result.path };
  401. });
  402. await check("windows-native-oom-signature", async () => {
  403. const { files } = await archiveCase("native-oom", exitLine([], 0xe0000008));
  404. assert.ok(files.get("logs/app.log")?.includes("ERR_OUT_OF_MEMORY"));
  405. });
  406. const childPath = await bundle(
  407. `
  408. import { startCliMemoryDiagnostics, createMemoryDiagnosticRecorder } from ${JSON.stringify(memorySource)};
  409. import { performance } from 'node:perf_hooks';
  410. async function main() {
  411. const mode = process.argv[2], directory = process.argv[3];
  412. console.log(JSON.stringify({event:'runtime', versions:process.versions}));
  413. if(mode === 'pending-write') {
  414. const recorder = createMemoryDiagnosticRecorder({bundlePath:process.argv[1], metadata:()=>({instanceId:'00000000-0000-4000-8000-000000000000',pid:process.pid,version:'probe',commit:'probe',node:process.versions.node,v8:process.versions.v8,bundleSha256:''}),
  415. profiler:{start:async()=>0,read:async()=>({head:{id:1,selfSize:0,callFrame:{functionName:'',url:'',lineNumber:0,columnNumber:0},children:[]},durationMs:0}),reset:async()=>0,dispose(){}},
  416. readMemory:()=>({...process.memoryUsage(),heapLimit:4000000000}),readCounters:()=>({sessions:0}),write:()=>new Promise(()=>{})});
  417. await recorder.start(); void recorder.sample(); await Promise.resolve(); recorder.stop();
  418. console.log(JSON.stringify({event:'finished'}));
  419. } else {
  420. const diagnostics = mode === 'off' ? undefined : startCliMemoryDiagnostics(()=>({sessions:1}),{directory});
  421. // 同一轮的业务计算过去被 await 计时误算为 Inspector 工作。
  422. const until=performance.now()+50; while(performance.now()<until) Math.sqrt(Math.random());
  423. if(mode === 'normal' || mode === 'off' || mode === 'storage-failure') {
  424. if(mode === 'storage-failure') await new Promise(resolve=>setTimeout(resolve,16000));
  425. diagnostics?.stop(); console.log(JSON.stringify({event:'finished'}));
  426. } else {
  427. globalThis.retained=[];
  428. function allocateProbe(){ for(let j=0;j<32;j++) globalThis.retained.push(Array.from({length:10000},(_,i)=>({i,label:'probe-'+j+'-'+i}))); }
  429. allocateProbe();
  430. setTimeout(()=>{
  431. console.log(JSON.stringify({event:'fault-start'}));
  432. if(mode==='oom') { while(true) globalThis.retained.push(new Array(100000).fill({value:1})); }
  433. else throw new Error(${JSON.stringify(crashMarker + " token=" + secret)});
  434. },17000);
  435. }
  436. }
  437. }
  438. void main();
  439. `,
  440. "probe-child.cjs",
  441. true,
  442. );
  443. async function runChild(mode) {
  444. const directory = join(output, "memory", mode);
  445. await mkdir(dirname(directory), { recursive: true });
  446. if (mode === "storage-failure") await writeFile(directory, "not a directory");
  447. const startedAt = Date.now();
  448. return new Promise((resolveChild, reject) => {
  449. const child = spawn(runtime, ["--max-old-space-size=128", childPath, mode, directory], {
  450. env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
  451. stdio: ["ignore", "pipe", "pipe"],
  452. });
  453. const stderrTail = createAgentStderrTail();
  454. let stdout = "";
  455. let finishedAt;
  456. let watchdog;
  457. // 使用产品已有的 stderr 解码器。Host 日志格式由验收器复现,未启动完整 App。
  458. const collector = new AgentStderrCollector(child.stderr, (line) => stderrTail.append(line));
  459. child.stdout.on("data", (chunk) => {
  460. stdout += chunk.toString();
  461. if (stdout.includes('"event":"finished"')) finishedAt ??= Date.now();
  462. });
  463. child.once("error", reject);
  464. // 仅测试 watchdog;产品不增加 timer、signal 或退出屏障。
  465. watchdog = setTimeout(() => {
  466. child.kill();
  467. reject(new Error(`${mode}: child did not exit`));
  468. }, 40_000);
  469. child.once("close", async (code, signal) => {
  470. clearTimeout(watchdog);
  471. try {
  472. await collector.waitForDrain();
  473. await writeFile(join(output, `${mode}-stdout.log`), stdout);
  474. const tail = stderrTail.snapshot().tail;
  475. await writeFile(join(output, `${mode}-stderr.log`), tail.join("\n"));
  476. const item = {
  477. mode,
  478. code,
  479. signal,
  480. elapsedMs: Date.now() - startedAt,
  481. ...(finishedAt ? { exitAfterFinishedMs: Date.now() - finishedAt } : {}),
  482. directory,
  483. };
  484. report.children.push(item);
  485. resolveChild({ ...item, tail });
  486. } catch (error) {
  487. reject(error);
  488. }
  489. });
  490. });
  491. }
  492. for (const mode of ["off", "normal", "pending-write", "storage-failure"]) {
  493. await check(`exit-${mode}`, async () => {
  494. const child = await runChild(mode);
  495. assert.equal(child.code, 0);
  496. assert.ok(child.exitAfterFinishedMs < 2000, "diagnostics kept process alive after finish");
  497. return { elapsedMs: child.elapsedMs, exitAfterFinishedMs: child.exitAfterFinishedMs };
  498. });
  499. }
  500. for (const mode of ["exception", "oom"]) {
  501. await check(`capture-${mode}`, async () => {
  502. const child = await runChild(mode);
  503. assert.ok(child.code !== 0 || child.signal);
  504. const names = await readdir(child.directory);
  505. const records = await Promise.all(
  506. names
  507. .filter((name) => name.endsWith(".jsonl"))
  508. .map(async (name) => JSON.parse(await readFile(join(child.directory, name), "utf8"))),
  509. );
  510. const record = records.find(
  511. (item) => item.sampler.profileCapturedAt > 0 && item.allocations.length > 0,
  512. );
  513. assert.ok(record, `no allocation evidence: ${JSON.stringify(records.map((r) => r.sampler))}`);
  514. assert.equal(
  515. record.bundleSha256,
  516. createHash("sha256")
  517. .update(await readFile(childPath))
  518. .digest("hex"),
  519. );
  520. const logs = join(output, "logs", mode);
  521. await mkdir(logs, { recursive: true });
  522. await writeFile(join(logs, "app.log"), exitLine(child.tail, child.code, child.signal));
  523. const archive = await createFeedbackDiagnosticArchive({
  524. sources: [
  525. {
  526. directory: child.directory,
  527. archivePrefix: ".zcode/cli/memory-diagnostics",
  528. contentPolicy: "cli-memory",
  529. onlyCurrentDay: false,
  530. },
  531. { directory: logs, archivePrefix: "logs" },
  532. ],
  533. outputRootDir: join(output, "archives", mode),
  534. });
  535. const files = await unzip(archive.path);
  536. const text = [...files.values()].join("\n");
  537. assert.ok(!text.includes(secret));
  538. assert.ok(text.includes("agentCrash"));
  539. assert.ok(text.includes(mode === "oom" ? "ERR_OUT_OF_MEMORY" : crashMarker));
  540. const { agentCrash } = readCrashRecord(files);
  541. if (mode === "oom") {
  542. assert.match(agentCrash.errorStack, /^FATAL ERROR:.*heap.*(?:limit|memory)/m);
  543. const nativeFrame = /^[ \t]*\d+:[ \t]*(?:0x[0-9a-f]+|[0-9a-f]{8,16})(?=[ \t]|$)/i;
  544. const expectedFrames = child.tail.filter((line) => nativeFrame.test(line));
  545. assert.ok(expectedFrames.length > 0, "runtime emitted no native OOM frames");
  546. assert.deepEqual(
  547. agentCrash.errorStack.split("\n").filter((line) => nativeFrame.test(line)),
  548. expectedFrames,
  549. );
  550. assert.ok(agentCrash.errorStack.split("\n").length > 1);
  551. } else {
  552. assert.match(agentCrash.errorStack, new RegExp(`^Error: ${crashMarker}`, "m"));
  553. assert.match(agentCrash.errorStack, /^[ \t]+at[ \t]+/m);
  554. }
  555. const exported = [...files.entries()]
  556. .filter(([name]) => name.includes("memory-diagnostics"))
  557. .map(([, body]) => JSON.parse(body));
  558. assert.ok(exported.some((r) => r.allocations.length > 0));
  559. return {
  560. path: archive.path,
  561. allocations: record.allocations.length,
  562. heapBytes: record.samples.at(-1).heapUsed,
  563. sourcePosition: record.allocations[0].stack.at(-1),
  564. archiveBytes: (await stat(archive.path)).size,
  565. };
  566. });
  567. }
  568. await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2));
  569. console.log(`Evidence: ${output}`);
  570. if (report.checks.some((check) => !check.passed)) process.exitCode = 1;