@clagentic/console 1.7.0 → 1.8.0-beta.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 (58) hide show
  1. package/bin/cli.js +198 -2542
  2. package/lib/build-sha.json +4 -0
  3. package/lib/cli/daemon-launch.js +797 -0
  4. package/lib/cli/ipc-subcommands.js +186 -0
  5. package/lib/cli/menus.js +849 -0
  6. package/lib/cli/net-detect.js +209 -0
  7. package/lib/cli/tui.js +589 -0
  8. package/lib/daemon.js +15 -6
  9. package/lib/memory-shed.js +81 -2
  10. package/lib/pages.js +13 -17
  11. package/lib/project-connection.js +13 -0
  12. package/lib/project-loop.js +4 -0
  13. package/lib/project-sessions.js +9 -3
  14. package/lib/project.js +3 -2
  15. package/lib/public/css/diagnostics.css +29 -1
  16. package/lib/public/css/home-hub.css +10 -0
  17. package/lib/public/css/overlays.css +19 -0
  18. package/lib/public/index.html +12 -11
  19. package/lib/public/manifest.json +1 -1
  20. package/lib/public/modules/app-connection.js +150 -4
  21. package/lib/public/modules/app-history-replay.js +155 -0
  22. package/lib/public/modules/app-home-hub.js +24 -14
  23. package/lib/public/modules/app-messages.js +1246 -1469
  24. package/lib/public/modules/app-notifications.js +4 -4
  25. package/lib/public/modules/app-rate-limit.js +128 -27
  26. package/lib/public/modules/command-palette.js +11 -22
  27. package/lib/public/modules/context-sources.js +1 -6
  28. package/lib/public/modules/filebrowser.js +25 -13
  29. package/lib/public/modules/input.js +47 -12
  30. package/lib/public/modules/mcp-ui.js +2 -2
  31. package/lib/public/modules/notifications.js +22 -1
  32. package/lib/public/modules/playbook.js +6 -6
  33. package/lib/public/modules/project-settings.js +5 -13
  34. package/lib/public/modules/qrcode.js +2 -2
  35. package/lib/public/modules/rate-limit-state.js +133 -0
  36. package/lib/public/modules/relative-time.js +27 -0
  37. package/lib/public/modules/scheduler-history.js +1 -5
  38. package/lib/public/modules/server-settings.js +28 -15
  39. package/lib/public/modules/sidebar-mobile.js +8 -3
  40. package/lib/public/modules/sidebar-projects.js +1 -1
  41. package/lib/public/modules/sidebar-sessions.js +1 -15
  42. package/lib/public/modules/sidebar.js +3 -3
  43. package/lib/public/modules/utils.js +1 -0
  44. package/lib/public/sw.js +24 -4
  45. package/lib/sdk-bridge.js +22 -0
  46. package/lib/sdk-message-processor.js +27 -1
  47. package/lib/server-auth.js +48 -2
  48. package/lib/server-palette.js +17 -1
  49. package/lib/server-settings.js +70 -4
  50. package/lib/server.js +200 -4
  51. package/lib/session-search.js +20 -5
  52. package/lib/sessions.js +84 -3
  53. package/lib/smtp.js +6 -6
  54. package/lib/yoke/adapters/codex.js +1 -1
  55. package/package.json +4 -2
  56. package/scripts/install-local-test.js +97 -0
  57. package/scripts/verify-installed-build.js +80 -0
  58. package/scripts/write-build-sha.js +53 -0
package/lib/sessions.js CHANGED
@@ -90,6 +90,16 @@ function createSessionManager(opts) {
90
90
  if (session.allowedTools && Object.keys(session.allowedTools).length > 0) {
91
91
  metaObj.allowedTools = session.allowedTools;
92
92
  }
93
+ // lr-f36626: durable AUTO-RESUME marker set by lib/memory-shed.js when a
94
+ // session with a live background child was force-evicted under memory
95
+ // pressure. Persisted (not just in-memory) so the marker survives a
96
+ // daemon restart between the reclaim and the operator's next reconnect —
97
+ // otherwise the "never a silent orphan" guarantee only holds until the
98
+ // next process restart.
99
+ if (session.pendingAutoResume) {
100
+ metaObj.pendingAutoResume = true;
101
+ if (session.pendingAutoResumeReason) metaObj.pendingAutoResumeReason = session.pendingAutoResumeReason;
102
+ }
93
103
  return JSON.stringify(metaObj);
94
104
  }
95
105
 
@@ -376,6 +386,13 @@ function createSessionManager(opts) {
376
386
  // source of truth) and drop it from the LRU order. Shared by the
377
387
  // one-at-a-time post-load eviction (_lruEvictIfNeeded) and the
378
388
  // pressure-driven bulk eviction (forceEvictToLimit, lr-5e70).
389
+ //
390
+ // Note: this never touches candidate.queryInstance — an evicted session's
391
+ // live query (if any) keeps running; only its in-heap history window is
392
+ // dropped and reloaded lazily on next access. That is what makes force-
393
+ // eviction of a session with a live background child (lr-f36626) safe on
394
+ // its own — the child process is not killed here. See forceEvictToLimit's
395
+ // header for the escalation this enables.
379
396
  function _evictSession(candidate) {
380
397
  candidate.history = [];
381
398
  candidate._historyLoaded = false;
@@ -416,11 +433,32 @@ function createSessionManager(opts) {
416
433
  // active session or an isProcessing session (skip-active-session and
417
434
  // skip-processing are both load-bearing invariants, not incidental).
418
435
  //
436
+ // lr-f36626: a session with a live registered background child
437
+ // (session.activeTaskToolIds non-empty) is a LAST-RESORT candidate, not an
438
+ // exempt one — under real memory pressure the ceiling (lr-c10f6d) still
439
+ // wins. Pass 1 below only evicts childless candidates; pass 2 falls back to
440
+ // live-child candidates solely when pass 1 could not reach the limit alone.
441
+ // Eviction here never kills the child (_evictSession never touches
442
+ // queryInstance — see its header), so this is not the reap-and-orphan
443
+ // failure mode lr-f36626 diagnosed; it only unloads in-heap history. The
444
+ // caller (lib/memory-shed.js) uses reclaimedLiveChild to durably checkpoint
445
+ // and notify both UI surfaces for each such session, per lr-f36626's
446
+ // "never a silent orphan" requirement.
447
+ //
419
448
  // @param {number} limit — target max loaded-session count after this call
420
- // @returns {number} count of sessions actually evicted
449
+ // @returns {{ evicted: number, reclaimedLiveChild: Array<object> }}
450
+ // reclaimedLiveChild holds the actual session objects (not just ids) that
451
+ // were evicted while carrying a live registered child, in eviction order.
421
452
  function forceEvictToLimit(limit) {
422
453
  var evicted = 0;
454
+ var reclaimedLiveChild = [];
423
455
  var guard = lruOrder.length; // upper bound on loop iterations — no infinite loop
456
+
457
+ function hasLiveChild(candidate) {
458
+ return !!(candidate.activeTaskToolIds && Object.keys(candidate.activeTaskToolIds).length > 0);
459
+ }
460
+
461
+ // Pass 1: childless candidates only (the normal, non-escalated case).
424
462
  while (lruOrder.length > limit && guard-- > 0) {
425
463
  var evictedOne = false;
426
464
  for (var ei = 0; ei < lruOrder.length; ei++) {
@@ -428,14 +466,36 @@ function createSessionManager(opts) {
428
466
  if (candidateId === activeSessionId) continue;
429
467
  var candidate = sessions.get(candidateId);
430
468
  if (!candidate || candidate.isProcessing) continue;
469
+ if (hasLiveChild(candidate)) continue; // deferred to pass 2
431
470
  _evictSession(candidate);
432
471
  evicted++;
433
472
  evictedOne = true;
434
473
  break;
435
474
  }
436
- if (!evictedOne) break; // no further evictable candidate — stop
475
+ if (!evictedOne) break; // no further childless candidate — stop, try pass 2
476
+ }
477
+
478
+ // Pass 2 (last resort): still over limit and childless candidates are
479
+ // exhausted — fall back to live-child candidates so the memory ceiling
480
+ // is never silently deferred to in favor of a background dispatch.
481
+ guard = lruOrder.length;
482
+ while (lruOrder.length > limit && guard-- > 0) {
483
+ var evictedOne2 = false;
484
+ for (var ej = 0; ej < lruOrder.length; ej++) {
485
+ var candidateId2 = lruOrder[ej];
486
+ if (candidateId2 === activeSessionId) continue;
487
+ var candidate2 = sessions.get(candidateId2);
488
+ if (!candidate2 || candidate2.isProcessing) continue;
489
+ reclaimedLiveChild.push(candidate2);
490
+ _evictSession(candidate2);
491
+ evicted++;
492
+ evictedOne2 = true;
493
+ break;
494
+ }
495
+ if (!evictedOne2) break; // no further evictable candidate at all — stop
437
496
  }
438
- return evicted;
497
+
498
+ return { evicted: evicted, reclaimedLiveChild: reclaimedLiveChild };
439
499
  }
440
500
 
441
501
  // Parse every history line in a session's on-disk JSONL file (skipping the
@@ -623,6 +683,12 @@ function createSessionManager(opts) {
623
683
  session.sessionVisibility = m.sessionVisibility || "shared";
624
684
  session.bookmarked = !!m.bookmarked;
625
685
  session.favoriteOrder = typeof m.favoriteOrder === "number" ? m.favoriteOrder : null;
686
+ // lr-f36626: restore the durable AUTO-RESUME marker across a daemon
687
+ // restart — see buildMetaLine's write side for why this must persist.
688
+ if (m.pendingAutoResume) {
689
+ session.pendingAutoResume = true;
690
+ session.pendingAutoResumeReason = m.pendingAutoResumeReason || null;
691
+ }
626
692
  sessions.set(localId, session);
627
693
  }
628
694
  }
@@ -1011,6 +1077,18 @@ function createSessionManager(opts) {
1011
1077
  }
1012
1078
  }
1013
1079
 
1080
+ // lr-0827ba (PEACHES follow-up): explicit notification that a session was
1081
+ // deleted, carrying its localId, so the client can prune any per-session
1082
+ // state it tracks (e.g. rate-limit-state.js's armed-schedule map and
1083
+ // background reset timers) instead of leaking it forever. Prior to this,
1084
+ // the only client-observable signal was a fresh session_list broadcast
1085
+ // that simply omitted the deleted id — nothing told the client WHICH id(s)
1086
+ // disappeared, so nothing could target cleanup at them.
1087
+ function broadcastSessionDeleted(localIds) {
1088
+ var ids = Array.isArray(localIds) ? localIds : [localIds];
1089
+ send({ type: "session_deleted", ids: ids });
1090
+ }
1091
+
1014
1092
  function deleteSession(localId, targetWs) {
1015
1093
  var session = sessions.get(localId);
1016
1094
  if (!session) return;
@@ -1043,6 +1121,7 @@ function createSessionManager(opts) {
1043
1121
  }
1044
1122
 
1045
1123
  sessions.delete(localId);
1124
+ broadcastSessionDeleted(localId);
1046
1125
 
1047
1126
  if (activeSessionId === localId) {
1048
1127
  var remaining = [...sessions.keys()];
@@ -1105,6 +1184,7 @@ function createSessionManager(opts) {
1105
1184
  if (ids[j] === activeSessionId) deletedActive = true;
1106
1185
  deleteSessionQuiet(ids[j]);
1107
1186
  }
1187
+ broadcastSessionDeleted(ids);
1108
1188
 
1109
1189
  if (sessions.size === 0) {
1110
1190
  createSession(null, targetWs);
@@ -1482,6 +1562,7 @@ function createSessionManager(opts) {
1482
1562
  resumeSession: resumeSession,
1483
1563
  mapSessionForClient: mapSessionForClient,
1484
1564
  broadcastSessionList: broadcastSessionList,
1565
+ broadcastSessionDeleted: broadcastSessionDeleted,
1485
1566
  getTotalUnread: function (ws) {
1486
1567
  var unreadMap = (ws && ws._clayUnread) ? ws._clayUnread : {};
1487
1568
  var total = 0;
package/lib/smtp.js CHANGED
@@ -78,9 +78,9 @@ function sendTestEmail(cfg, toEmail) {
78
78
  return t.sendMail({
79
79
  from: cfg.from,
80
80
  to: toEmail,
81
- subject: "Clagentic:Console SMTP Test",
81
+ subject: "Clagentic: Console SMTP Test",
82
82
  html: '<div style="font-family:system-ui,sans-serif;max-width:400px;margin:0 auto;padding:24px">' +
83
- '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic:Console</h2>' +
83
+ '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic: Console</h2>' +
84
84
  '<p style="color:#333;margin:0">SMTP is configured correctly. You will receive login codes and invite emails at this address.</p>' +
85
85
  '</div>',
86
86
  }).then(function (info) {
@@ -160,7 +160,7 @@ function verifyOtp(email, code) {
160
160
  function sendOtpEmail(email, code) {
161
161
  var subject = "Your Clagentic login code: " + code;
162
162
  var html = '<div style="font-family:system-ui,sans-serif;max-width:400px;margin:0 auto;padding:24px">' +
163
- '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic:Console</h2>' +
163
+ '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic: Console</h2>' +
164
164
  '<p style="color:#333;margin:0 0 16px">Your verification code is:</p>' +
165
165
  '<div style="font-size:32px;font-weight:700;letter-spacing:8px;padding:16px 0;text-align:center;' +
166
166
  'background:#f5f5f5;border-radius:8px;color:#333;font-family:monospace">' + code + '</div>' +
@@ -170,10 +170,10 @@ function sendOtpEmail(email, code) {
170
170
  }
171
171
 
172
172
  function sendInviteEmail(email, inviteUrl, inviterName) {
173
- var subject = "You've been invited to Clagentic:Console";
173
+ var subject = "You've been invited to Clagentic: Console";
174
174
  var html = '<div style="font-family:system-ui,sans-serif;max-width:400px;margin:0 auto;padding:24px">' +
175
- '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic:Console</h2>' +
176
- '<p style="color:#333;margin:0 0 16px">' + (inviterName || "An admin") + ' has invited you to join Clagentic:Console.</p>' +
175
+ '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic: Console</h2>' +
176
+ '<p style="color:#333;margin:0 0 16px">' + (inviterName || "An admin") + ' has invited you to join Clagentic: Console.</p>' +
177
177
  '<p style="margin:0 0 16px"><a href="' + inviteUrl + '" style="display:inline-block;padding:12px 24px;' +
178
178
  'background:#DA7756;color:#fff;text-decoration:none;border-radius:8px;font-weight:600">Accept Invite</a></p>' +
179
179
  '<p style="color:#999;font-size:13px;margin:0">This invite link expires in 24 hours.</p>' +
@@ -1492,7 +1492,7 @@ function createCodexAdapter(opts) {
1492
1492
  await _appServer.start();
1493
1493
 
1494
1494
  await _appServer.send("initialize", {
1495
- clientInfo: { name: "clagentic", title: "Clagentic:Console", version: "1.0.0" },
1495
+ clientInfo: { name: "clagentic", title: "Clagentic: Console", version: "1.0.0" },
1496
1496
  capabilities: { experimentalApi: true },
1497
1497
  });
1498
1498
  _appServer.notify("initialized", {});
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.7.0",
6
+ "version": "1.8.0-beta.1",
7
7
  "description": "Self-hosted console for Claude Code and Codex. Multi-user, browser-based, persistent AI sessions.",
8
8
  "bin": {
9
9
  "clagentic-console": "./bin/cli.js"
@@ -11,8 +11,10 @@
11
11
  "scripts": {
12
12
  "dev": "node bin/cli.js --dev",
13
13
  "postinstall": "node scripts/postinstall.js",
14
+ "prepack": "node scripts/write-build-sha.js",
14
15
  "test": "node --test --test-force-exit test/*.test.js",
15
- "install:local-test": "sh -c 'f=$(npm pack) && npm install -g \"$f\" && rm -f \"$f\"'",
16
+ "install:local-test": "node scripts/install-local-test.js",
17
+ "verify:installed-build": "node scripts/verify-installed-build.js",
16
18
  "semantic-release": "semantic-release"
17
19
  },
18
20
  "files": [
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // install-local-test.js — pack the current tree and install it globally (lr-0d45).
5
+ //
6
+ // Replaces the old `sh -c 'f=$(npm pack) && npm install -g "$f" && rm -f "$f"'`
7
+ // one-liner. That form broke because `$(npm pack)` captures npm's multi-line
8
+ // human-readable notices AND any output written to stdout by the `prepack`
9
+ // lifecycle hook (scripts/write-build-sha.js's own console.log) — not just the
10
+ // tarball filename. The resulting `$f` was a garbage multi-line string, so
11
+ // `npm install -g "$f"` failed with EINVALIDPACKAGENAME.
12
+ //
13
+ // `npm pack --json` also mixes prepack-hook stdout into the same stream, so
14
+ // this reads npm's output and extracts the tarball filename by parsing the
15
+ // trailing JSON array specifically (the only valid JSON substring `npm pack
16
+ // --json` ever emits), rather than trusting the whole stdout to be clean.
17
+
18
+ const { execFileSync } = require('child_process');
19
+
20
+ // Extracts the packed tarball filename from `npm pack --json`'s raw stdout.
21
+ // Exported (not just used internally) so tests can exercise the parsing
22
+ // logic against captured/synthetic npm output without shelling out to a
23
+ // real `npm pack` — see test/install-local-test-lr-0d45.test.js.
24
+ function extractTarballFilename(raw) {
25
+ // npm pack --json emits a JSON array `[ { ... } ]` (pretty-printed,
26
+ // multi-line, in practice), but the prepack lifecycle hook
27
+ // (scripts/write-build-sha.js) writes its own log line to the same stdout
28
+ // stream first, and that line itself starts with a literal '[' (its
29
+ // "[write-build-sha] wrote ..." prefix) — so a naive raw.indexOf('[') finds
30
+ // that '[' instead of the JSON array's. Rather than assume a specific
31
+ // whitespace shape around the array's opening bracket, try every '[' that
32
+ // starts a line as a candidate array start and parse from there to the end
33
+ // of the string, taking the first candidate that parses as a non-empty
34
+ // array of objects with a "filename" field. This tolerates both
35
+ // pretty-printed and single-line npm output across npm versions.
36
+ const lines = raw.split('\n');
37
+ let offset = 0;
38
+ const candidates = [];
39
+ for (const line of lines) {
40
+ if (line.startsWith('[')) {
41
+ candidates.push(offset);
42
+ }
43
+ offset += line.length + 1;
44
+ }
45
+
46
+ for (const start of candidates) {
47
+ let parsed;
48
+ try {
49
+ parsed = JSON.parse(raw.slice(start));
50
+ } catch {
51
+ continue;
52
+ }
53
+ if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0].filename === 'string') {
54
+ // npm pack --json's "filename" field uses the @scope/name@version form
55
+ // with a literal '/' in place of the tarball's on-disk '-' separator;
56
+ // the actual file on disk uses '-'. Normalize to get the real path.
57
+ return parsed[0].filename.replace('/', '-');
58
+ }
59
+ }
60
+
61
+ throw new Error(`could not locate a valid \`npm pack --json\` array in output:\n${raw}`);
62
+ }
63
+
64
+ function packAndGetFilename() {
65
+ const raw = execFileSync('npm', ['pack', '--json'], { encoding: 'utf8' });
66
+ return extractTarballFilename(raw);
67
+ }
68
+
69
+ function main() {
70
+ let tarball;
71
+ try {
72
+ tarball = packAndGetFilename();
73
+ } catch (err) {
74
+ console.error(`[install-local-test] ERROR: ${err.message}`);
75
+ process.exit(1);
76
+ }
77
+
78
+ console.log(`[install-local-test] packed ${tarball}`);
79
+
80
+ try {
81
+ execFileSync('npm', ['install', '-g', tarball], { stdio: 'inherit' });
82
+ } finally {
83
+ try {
84
+ execFileSync('rm', ['-f', tarball]);
85
+ } catch (cleanupErr) {
86
+ console.error(`[install-local-test] WARN: could not remove ${tarball}: ${cleanupErr.message}`);
87
+ }
88
+ }
89
+
90
+ console.log('[install-local-test] ok: installed');
91
+ }
92
+
93
+ module.exports = { extractTarballFilename };
94
+
95
+ if (require.main === module) {
96
+ main();
97
+ }
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // verify-installed-build.js — post-merge install assertion (lr-0d45).
5
+ //
6
+ // Confirms the globally-installed @clagentic/console build (installed by the
7
+ // preceding `npm run install:local-test` post_merge_steps entry) actually
8
+ // reflects the merged HEAD commit, rather than trusting a zero exit code from
9
+ // `npm install -g` alone. Compares the SHA embedded by scripts/write-build-sha.js
10
+ // (baked into the tarball at `prepack` time, so it travels with the package
11
+ // that `npm install -g` unpacked) against this working tree's own HEAD SHA at
12
+ // the moment loadout-merge runs post_merge_steps (i.e. the merged commit).
13
+ //
14
+ // Exit codes:
15
+ // 0 — installed build-sha.json matches this tree's HEAD.
16
+ // 1 — mismatch, or build-sha.json missing/unreadable, or HEAD unresolvable.
17
+ // Reported on stderr with both SHAs so the exact drift is visible in
18
+ // loadout-merge's captured step output.
19
+ //
20
+ // Run as a SEPARATE post_merge_steps entry (on_failure: fail) after
21
+ // `npm run install:local-test` — never combined into one shell string, per
22
+ // loadout-merge's shell-operator-token rejection (merge/post_merge.py).
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const { execFileSync } = require('child_process');
27
+
28
+ function resolveHeadSha() {
29
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
30
+ cwd: path.join(__dirname, '..'),
31
+ stdio: ['ignore', 'pipe', 'pipe'],
32
+ }).toString().trim();
33
+ }
34
+
35
+ function resolveInstalledSha() {
36
+ // `npm install -g` resolves the global node_modules root via `npm root -g`;
37
+ // read the build-sha.json that write-build-sha.js baked into the tarball
38
+ // at pack time (lib/ is in package.json's `files`, so it ships).
39
+ const globalRoot = execFileSync('npm', ['root', '-g'], {
40
+ stdio: ['ignore', 'pipe', 'pipe'],
41
+ }).toString().trim();
42
+ const installedPath = path.join(globalRoot, '@clagentic', 'console', 'lib', 'build-sha.json');
43
+ const raw = fs.readFileSync(installedPath, 'utf8');
44
+ const parsed = JSON.parse(raw);
45
+ if (!parsed || typeof parsed.sha !== 'string') {
46
+ throw new Error(`${installedPath} does not contain a "sha" field`);
47
+ }
48
+ return { sha: parsed.sha, path: installedPath };
49
+ }
50
+
51
+ function main() {
52
+ let headSha;
53
+ try {
54
+ headSha = resolveHeadSha();
55
+ } catch (err) {
56
+ console.error(`[verify-installed-build] ERROR: could not resolve this tree's HEAD SHA: ${err.message}`);
57
+ process.exit(1);
58
+ }
59
+
60
+ let installed;
61
+ try {
62
+ installed = resolveInstalledSha();
63
+ } catch (err) {
64
+ console.error(`[verify-installed-build] ERROR: could not read installed build-sha.json: ${err.message}`);
65
+ process.exit(1);
66
+ }
67
+
68
+ if (installed.sha !== headSha) {
69
+ console.error(
70
+ `[verify-installed-build] MISMATCH: installed build (${installed.path}) is at ` +
71
+ `${installed.sha}, but merged HEAD is ${headSha}. The post-merge install did ` +
72
+ `not land the merged commit — investigate before trusting the running build.`
73
+ );
74
+ process.exit(1);
75
+ }
76
+
77
+ console.log(`[verify-installed-build] ok: installed build matches merged HEAD (${headSha})`);
78
+ }
79
+
80
+ main();
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // write-build-sha.js — embeds the current git commit SHA into lib/build-sha.json
5
+ // so a later install of this package can be checked against the source tree it
6
+ // was built from (lr-0d45: post-merge install verification).
7
+ //
8
+ // Runs as npm's `prepack` lifecycle hook — fires before `npm pack` builds the
9
+ // tarball, so `lib/build-sha.json` is always baked into what install:local-test
10
+ // ships. Also runs standalone via `node scripts/write-build-sha.js` for local
11
+ // debugging.
12
+ //
13
+ // Fails loudly (non-zero exit) if the SHA cannot be determined — a package
14
+ // packed without a resolvable SHA would make the post-install verification
15
+ // step (scripts/verify-installed-build.js) meaningless, so refuse to produce
16
+ // a stale/empty build-sha.json rather than pack one silently.
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { execFileSync } = require('child_process');
21
+
22
+ const OUT_PATH = path.join(__dirname, '..', 'lib', 'build-sha.json');
23
+
24
+ function resolveSha() {
25
+ try {
26
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
27
+ cwd: path.join(__dirname, '..'),
28
+ stdio: ['ignore', 'pipe', 'pipe'],
29
+ }).toString().trim();
30
+ } catch (err) {
31
+ const stderr = err.stderr ? err.stderr.toString().trim() : err.message;
32
+ throw new Error(`could not resolve git HEAD SHA: ${stderr}`);
33
+ }
34
+ }
35
+
36
+ function main() {
37
+ let sha;
38
+ try {
39
+ sha = resolveSha();
40
+ } catch (err) {
41
+ console.error(`[write-build-sha] ERROR: ${err.message}`);
42
+ process.exit(1);
43
+ }
44
+ if (!/^[0-9a-f]{40}$/i.test(sha)) {
45
+ console.error(`[write-build-sha] ERROR: resolved SHA does not look like a git commit hash: ${JSON.stringify(sha)}`);
46
+ process.exit(1);
47
+ }
48
+ const payload = { sha, writtenAt: new Date().toISOString() };
49
+ fs.writeFileSync(OUT_PATH, JSON.stringify(payload, null, 2) + '\n');
50
+ console.log(`[write-build-sha] wrote ${OUT_PATH} (sha=${sha})`);
51
+ }
52
+
53
+ main();