@clagentic/console 1.9.0-beta.3 → 1.10.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 (146) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +8 -2
  5. package/bin/cli.js +30 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/audit.js +3 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-check.js +138 -0
  10. package/lib/cli/daemon-launch.js +17 -17
  11. package/lib/config.js +32 -20
  12. package/lib/daemon-env-settings.js +84 -0
  13. package/lib/daemon-projects.js +38 -0
  14. package/lib/daemon.js +202 -158
  15. package/lib/drain.js +74 -17
  16. package/lib/env-compat.js +61 -0
  17. package/lib/extension-commands.js +45 -0
  18. package/lib/history-visibility.js +4 -0
  19. package/lib/idle-adapter-reaper.js +71 -0
  20. package/lib/link-trap.js +78 -0
  21. package/lib/lore-attestation.js +73 -0
  22. package/lib/mcp-local.js +8 -6
  23. package/lib/mcp-tool-input.js +116 -0
  24. package/lib/mcp-tool-schema.js +179 -0
  25. package/lib/memory-limits.js +61 -5
  26. package/lib/memory-setting-validate.js +65 -0
  27. package/lib/new-work-gate.js +47 -0
  28. package/lib/os-users.js +5 -3
  29. package/lib/project-access.js +139 -0
  30. package/lib/project-connection.js +23 -22
  31. package/lib/project-external-trigger.js +103 -10
  32. package/lib/project-file-scope.js +172 -0
  33. package/lib/project-file-watch.js +86 -61
  34. package/lib/project-filesystem.js +144 -128
  35. package/lib/project-git.js +119 -0
  36. package/lib/project-http.js +44 -28
  37. package/lib/project-loop.js +12 -5
  38. package/lib/project-mcp.js +53 -72
  39. package/lib/project-message-gate.js +70 -0
  40. package/lib/project-notifications.js +31 -4
  41. package/lib/project-prompt-responses.js +216 -0
  42. package/lib/project-sessions.js +164 -302
  43. package/lib/project-user-message.js +36 -11
  44. package/lib/project.js +189 -142
  45. package/lib/projects-dir.js +90 -0
  46. package/lib/prompt-access.js +22 -0
  47. package/lib/prompt-kinds/answer-limits.js +15 -0
  48. package/lib/prompt-kinds/ask-user.js +58 -0
  49. package/lib/prompt-kinds/codecs.js +97 -0
  50. package/lib/prompt-kinds/elicitation.js +77 -0
  51. package/lib/prompt-kinds/extension.js +39 -0
  52. package/lib/prompt-kinds/index.js +68 -0
  53. package/lib/prompt-kinds/permission.js +114 -0
  54. package/lib/prompt-kinds/plan.js +79 -0
  55. package/lib/prompt-kinds/tool-call.js +38 -0
  56. package/lib/prompt-registry.js +673 -0
  57. package/lib/public/app.js +1 -1
  58. package/lib/public/css/diagnostics.css +50 -0
  59. package/lib/public/css/input.css +17 -3
  60. package/lib/public/css/menus.css +10 -0
  61. package/lib/public/css/messages.css +5 -0
  62. package/lib/public/css/rewind.css +22 -0
  63. package/lib/public/index.html +4 -12
  64. package/lib/public/modules/app-connection.js +7 -0
  65. package/lib/public/modules/app-cursors.js +7 -5
  66. package/lib/public/modules/app-messages.js +45 -45
  67. package/lib/public/modules/app-notifications.js +47 -71
  68. package/lib/public/modules/app-panels.js +61 -58
  69. package/lib/public/modules/app-projects.js +2 -1
  70. package/lib/public/modules/app-rendering.js +4 -10
  71. package/lib/public/modules/diagnostics.js +60 -16
  72. package/lib/public/modules/filebrowser.js +18 -16
  73. package/lib/public/modules/history-visibility.js +4 -0
  74. package/lib/public/modules/mention.js +3 -2
  75. package/lib/public/modules/mode-options.js +38 -0
  76. package/lib/public/modules/project-settings.js +19 -8
  77. package/lib/public/modules/prompt-banner.js +78 -0
  78. package/lib/public/modules/prompt-card.js +201 -0
  79. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  80. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  81. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  82. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  83. package/lib/public/modules/prompt-kinds/index.js +18 -0
  84. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  85. package/lib/public/modules/prompt-kinds/package.json +3 -0
  86. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  87. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  88. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  89. package/lib/public/modules/prompt-state.js +142 -0
  90. package/lib/public/modules/prompts.js +134 -0
  91. package/lib/public/modules/rewind.js +4 -1
  92. package/lib/public/modules/server-settings.js +2 -4
  93. package/lib/public/modules/sidebar-mobile.js +19 -9
  94. package/lib/public/modules/sidebar-sessions.js +21 -14
  95. package/lib/public/modules/sticky-notes.js +3 -2
  96. package/lib/public/modules/team-panel.js +5 -4
  97. package/lib/public/modules/tools.js +67 -904
  98. package/lib/public/modules/vendor-picker.js +53 -0
  99. package/lib/public/modules/vendor-registry.js +133 -0
  100. package/lib/public/sw.js +3 -1
  101. package/lib/rc-migrate.js +44 -0
  102. package/lib/runtime-env-keys.js +109 -0
  103. package/lib/runtime-env.js +236 -0
  104. package/lib/sdk-bridge.js +290 -273
  105. package/lib/sdk-message-processor.js +125 -145
  106. package/lib/server-hub-sessions.js +13 -10
  107. package/lib/server-palette.js +28 -19
  108. package/lib/server.js +141 -113
  109. package/lib/service-install.js +96 -0
  110. package/lib/session-capabilities.js +76 -0
  111. package/lib/sessions.js +45 -28
  112. package/lib/users-permissions.js +9 -6
  113. package/lib/users.js +9 -0
  114. package/lib/utils.js +4 -2
  115. package/lib/vendor-auth.js +22 -0
  116. package/lib/vendor-registry-message.js +65 -0
  117. package/lib/ws-origin.js +99 -0
  118. package/lib/ws-schema.js +33 -22
  119. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  120. package/lib/yoke/adapters/claude-vendor.js +35 -0
  121. package/lib/yoke/adapters/claude-worker.js +55 -87
  122. package/lib/yoke/adapters/claude.js +156 -62
  123. package/lib/yoke/adapters/codex-capabilities.js +37 -0
  124. package/lib/yoke/adapters/codex-vendor.js +46 -0
  125. package/lib/yoke/adapters/codex.js +347 -156
  126. package/lib/yoke/adapters/effort-control.js +34 -0
  127. package/lib/yoke/adapters/permission-relay.js +58 -0
  128. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  129. package/lib/yoke/auth-checks.js +104 -0
  130. package/lib/yoke/capabilities.js +49 -0
  131. package/lib/yoke/codex-app-server.js +23 -5
  132. package/lib/yoke/env-ownership.js +40 -0
  133. package/lib/yoke/index.js +67 -173
  134. package/lib/yoke/install-probe.js +121 -0
  135. package/lib/yoke/instructions.js +7 -11
  136. package/lib/yoke/interface.js +199 -3
  137. package/lib/yoke/package.json +1 -1
  138. package/lib/yoke/provider-credentials.js +96 -0
  139. package/lib/yoke/registry.js +340 -0
  140. package/package.json +12 -8
  141. package/scripts/check-sdk-lock-drift.js +160 -0
  142. package/scripts/check-test-count.js +76 -1
  143. package/scripts/postinstall.js +218 -136
  144. package/scripts/prompt-harness-history.js +202 -0
  145. package/scripts/verify-installed.js +67 -0
  146. package/lib/sdk-permission-ownership.js +0 -136
@@ -3,162 +3,94 @@
3
3
 
4
4
  // postinstall.js — installs/updates the systemd service unit on Linux global npm installs.
5
5
  // Runs automatically after `npm install -g @clagentic/console`.
6
- // Silently exits on non-Linux platforms and non-root invocations.
6
+ // Does nothing on non-Linux platforms, on non-global installs (a local `npm ci` /
7
+ // `npm install` in a dev checkout or worktree must never touch /etc/systemd or
8
+ // /usr/local/bin), and for non-root invocations.
9
+ //
10
+ // All host effects go through the `deps` object so tests can stub the filesystem,
11
+ // systemctl and the environment; the exported run() is what main() calls with real ones.
7
12
 
8
13
  const { execFileSync } = require('child_process');
9
14
  const fs = require('fs');
10
15
  const path = require('path');
11
16
 
12
- const PREFIX = '[clagentic-console postinstall]';
13
- const { applyDropIn, parseMemoryLimit } = require('../lib/memory-limits');
14
-
15
- function log(msg) {
16
- console.log(`${PREFIX} ${msg}`);
17
- }
18
-
19
- function runCmd(cmd, args) {
20
- // Returns stdout string on success, throws on failure.
21
- // stderr is captured in err.stderr on failure.
22
- return execFileSync(cmd, args, { stdio: 'pipe' }).toString().trim();
23
- }
24
-
25
- function errMsg(err) {
26
- // execFileSync puts detail in err.stderr; fall back to err.message.
27
- const stderr = err.stderr && err.stderr.toString().trim();
28
- return stderr || err.message;
29
- }
30
-
31
- // Skip silently on non-Linux platforms.
32
- if (process.platform !== 'linux') {
33
- process.exit(0);
34
- }
17
+ const {
18
+ LEGACY_WRAPPER_PATH,
19
+ isLegacyWrapperContent,
20
+ isGlobalInstall,
21
+ resolveCliBin,
22
+ renderUnit,
23
+ } = require('../lib/service-install');
35
24
 
36
- // Skip silently when not running as root — cannot write to /etc/systemd/system/.
37
- if (process.getuid() !== 0) {
38
- log('skipping (not root)');
39
- process.exit(0);
40
- }
41
-
42
- // When the daemon triggers its own in-app update it passes CLAGENTIC_SELF_UPDATE=1.
43
- // In that case, skip restarting the service — the daemon calls gracefulShutdown()
44
- // immediately after npm install completes, and systemd Restart=always handles the
45
- // supervised restart. Issuing systemctl restart here would race with gracefulShutdown
46
- // and tear down sessions before state is flushed.
47
- const selfUpdate = process.env.CLAGENTIC_SELF_UPDATE === '1';
48
- if (selfUpdate) {
49
- log('self-update detected (CLAGENTIC_SELF_UPDATE=1) — skipping service restart');
50
- }
25
+ const PREFIX = '[clagentic-console postinstall]';
51
26
 
52
27
  const SYSTEMD_DIR = '/etc/systemd/system';
53
28
  const NEW_UNIT = 'clagentic-console.service';
54
29
  const OLD_UNIT = 'clagentic.service';
55
- const NEW_UNIT_DEST = path.join(SYSTEMD_DIR, NEW_UNIT);
56
- const OLD_UNIT_PATH = path.join(SYSTEMD_DIR, OLD_UNIT);
57
30
  const UNIT_SRC = path.join(__dirname, '..', 'deploy', 'clagentic-console.service');
31
+ const PKG_DIR = path.join(__dirname, '..');
58
32
 
59
- // Step 1: Copy the new unit file.
60
- log(`installing unit file -> ${NEW_UNIT_DEST}`);
61
- try {
62
- fs.copyFileSync(UNIT_SRC, NEW_UNIT_DEST);
63
- } catch (err) {
64
- log(`ERROR copying unit file: ${errMsg(err)}`);
65
- // Cannot continue without the unit file in place.
66
- process.exit(0);
67
- }
68
-
69
- // Step 2: daemon-reload to pick up the new unit file.
70
- log('running systemctl daemon-reload');
71
- try {
72
- runCmd('systemctl', ['daemon-reload']);
73
- } catch (err) {
74
- log(`WARNING: daemon-reload failed: ${errMsg(err)}`);
33
+ function errMsg(err) {
34
+ // execFileSync puts detail in err.stderr; fall back to err.message.
35
+ const stderr = err.stderr && err.stderr.toString().trim();
36
+ return stderr || err.message;
75
37
  }
76
38
 
77
- // Step 3: Enable the new unit if not already enabled.
78
- log(`enabling ${NEW_UNIT}`);
79
- try {
80
- runCmd('systemctl', ['enable', NEW_UNIT]);
81
- } catch (err) {
82
- log(`WARNING: enable ${NEW_UNIT} failed: ${errMsg(err)}`);
39
+ function realDeps() {
40
+ return {
41
+ fs,
42
+ env: process.env,
43
+ platform: process.platform,
44
+ getuid: () => process.getuid(),
45
+ systemdDir: SYSTEMD_DIR,
46
+ legacyWrapperPath: LEGACY_WRAPPER_PATH,
47
+ pkgDir: PKG_DIR,
48
+ unitSrc: UNIT_SRC,
49
+ log: (msg) => console.log(`${PREFIX} ${msg}`),
50
+ // Returns stdout string on success, throws on failure.
51
+ runCmd: (cmd, args) => execFileSync(cmd, args, { stdio: 'pipe' }).toString().trim(),
52
+ loadConfig: () => require('../lib/config').loadConfig(),
53
+ applyDropIn: (limits, logFn) => require('../lib/memory-limits').applyDropIn(limits, logFn),
54
+ parseMemoryLimit: (v) => require('../lib/memory-limits').parseMemoryLimit(v),
55
+ };
83
56
  }
84
57
 
85
- // Step 4: Handle rename — migrate from old clagentic.service if present.
86
- let wasRunningUnderOldUnit = false;
87
- if (fs.existsSync(OLD_UNIT_PATH)) {
88
- log(`old unit file detected: ${OLD_UNIT_PATH} — performing rename cutover`);
89
-
90
- // Detect whether the old unit is currently active before stopping it.
91
- try {
92
- const activeState = runCmd('systemctl', ['is-active', OLD_UNIT]);
93
- if (activeState === 'active') {
94
- wasRunningUnderOldUnit = true;
95
- }
96
- } catch (_) {
97
- // is-active exits non-zero when not active — not an error.
98
- }
99
-
100
- // Disable the old unit.
101
- log(`disabling ${OLD_UNIT}`);
58
+ // Removes the hand-placed legacy wrapper only when it is byte-for-byte the known
59
+ // legacy content; an operator-modified file is left alone.
60
+ function removeLegacyWrapper(deps) {
61
+ const { fs: fsx, log, legacyWrapperPath } = deps;
62
+ let content;
102
63
  try {
103
- runCmd('systemctl', ['disable', OLD_UNIT]);
64
+ content = fsx.readFileSync(legacyWrapperPath, 'utf8');
104
65
  } catch (err) {
105
- log(`WARNING: disable ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
66
+ if (err.code === 'ENOENT') return 'absent';
67
+ log(`WARNING: could not read ${legacyWrapperPath}: ${errMsg(err)}`);
68
+ return 'unreadable';
106
69
  }
107
-
108
- // Stop the old unit.
109
- log(`stopping ${OLD_UNIT}`);
110
- try {
111
- runCmd('systemctl', ['stop', OLD_UNIT]);
112
- } catch (err) {
113
- log(`WARNING: stop ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
70
+ if (!isLegacyWrapperContent(content)) {
71
+ log(`${legacyWrapperPath} differs from the known legacy wrapper — leaving it in place`);
72
+ return 'modified';
114
73
  }
115
-
116
- // Remove the old unit file.
117
- log(`removing ${OLD_UNIT_PATH}`);
118
74
  try {
119
- fs.unlinkSync(OLD_UNIT_PATH);
75
+ fsx.unlinkSync(legacyWrapperPath);
76
+ log(`removed legacy wrapper ${legacyWrapperPath} (the unit now runs "clagentic-console daemon")`);
77
+ return 'removed';
120
78
  } catch (err) {
121
- log(`WARNING: remove ${OLD_UNIT_PATH} failed: ${errMsg(err)}`);
122
- }
123
-
124
- // daemon-reload again to clear the old unit from systemd's view.
125
- log('running systemctl daemon-reload (post-rename)');
126
- try {
127
- runCmd('systemctl', ['daemon-reload']);
128
- } catch (err) {
129
- log(`WARNING: daemon-reload (post-rename) failed: ${errMsg(err)}`);
79
+ log(`WARNING: remove ${legacyWrapperPath} failed: ${errMsg(err)}`);
80
+ return 'failed';
130
81
  }
131
82
  }
132
83
 
133
- // Step 5: Start clagentic-console.service only if it was running under the old unit
134
- // and needs to be moved to the new one. Never restart a running service — that kills
135
- // live sessions. Never auto-start on a fresh install — the daemon needs configuration.
136
- // Self-updates use gracefulShutdown() + Restart=always; postinstall must not interfere.
137
- if (selfUpdate) {
138
- log('skipping start (self-update — gracefulShutdown will hand off to systemd)');
139
- } else if (wasRunningUnderOldUnit) {
140
- // Stopped the old unit during rename cutover — start under the new one now.
141
- log(`starting ${NEW_UNIT} (was running under ${OLD_UNIT})`);
142
- try {
143
- runCmd('systemctl', ['start', NEW_UNIT]);
144
- } catch (err) {
145
- log(`WARNING: start ${NEW_UNIT} failed: ${errMsg(err)}`);
146
- }
147
- } else {
148
- log(`skipping start (daemon was not running or is already running — operator controls restarts)`);
149
- }
150
-
151
- // Step 6: Apply the memory-limit drop-in (lr-c10f6d).
152
- // When the operator has NOT set memoryHigh/memoryMax in daemon.json, the
153
- // drop-in is still written — with ABSOLUTE byte values computed from
154
- // /proc/meminfo MemTotal (floor(60%) / floor(75%)) — because a `%` directive
155
- // in the shipped unit file is resolved by systemd against the wrong MemTotal
156
- // inside an LXC container; only userspace sees the lxcfs-corrected value.
157
- // Recomputed on every postinstall so it tracks RAM changes. Operator
158
- // overrides in daemon.json always keep precedence (unchanged from lr-de07).
159
- (function applyMemoryDropIn() {
160
- const { loadConfig } = require('../lib/config');
161
- const cfg = loadConfig();
84
+ function applyMemoryDropIn(deps) {
85
+ const { log, runCmd } = deps;
86
+ // When the operator has NOT set memoryHigh/memoryMax in daemon.json, the
87
+ // drop-in is still written — with ABSOLUTE byte values computed from
88
+ // /proc/meminfo MemTotal (floor(60%) / floor(75%)) — because a `%` directive
89
+ // in the shipped unit file is resolved by systemd against the wrong MemTotal
90
+ // inside an LXC container; only userspace sees the lxcfs-corrected value.
91
+ // Recomputed on every postinstall so it tracks RAM changes. Operator
92
+ // overrides in daemon.json always keep precedence.
93
+ const cfg = deps.loadConfig();
162
94
  const memoryHigh = cfg && cfg.memoryHigh ? String(cfg.memoryHigh) : null;
163
95
  const memoryMax = cfg && cfg.memoryMax ? String(cfg.memoryMax) : null;
164
96
 
@@ -166,14 +98,14 @@ if (selfUpdate) {
166
98
  // (Computed defaults are always well-formed bare-byte strings, so no
167
99
  // validation is needed for that path.)
168
100
  if (memoryHigh) {
169
- const vr = parseMemoryLimit(memoryHigh);
101
+ const vr = deps.parseMemoryLimit(memoryHigh);
170
102
  if (!vr.ok) {
171
103
  log(`WARNING: ignoring invalid memoryHigh value in daemon.json: ${vr.error}`);
172
104
  return;
173
105
  }
174
106
  }
175
107
  if (memoryMax) {
176
- const vr = parseMemoryLimit(memoryMax);
108
+ const vr = deps.parseMemoryLimit(memoryMax);
177
109
  if (!vr.ok) {
178
110
  log(`WARNING: ignoring invalid memoryMax value in daemon.json: ${vr.error}`);
179
111
  return;
@@ -181,7 +113,7 @@ if (selfUpdate) {
181
113
  }
182
114
 
183
115
  try {
184
- applyDropIn({ memoryHigh, memoryMax }, (msg) => log(msg.replace(/^\[memory-limits\] /, '')));
116
+ deps.applyDropIn({ memoryHigh, memoryMax }, (msg) => log(msg.replace(/^\[memory-limits\] /, '')));
185
117
  log('running systemctl daemon-reload (memory drop-in updated)');
186
118
  try {
187
119
  runCmd('systemctl', ['daemon-reload']);
@@ -191,6 +123,156 @@ if (selfUpdate) {
191
123
  } catch (err) {
192
124
  log(`WARNING: memory drop-in apply failed: ${err.message}`);
193
125
  }
194
- })();
126
+ }
127
+
128
+ function run(deps) {
129
+ const { fs: fsx, env, log, runCmd } = deps;
130
+
131
+ // Skip silently on non-Linux platforms.
132
+ if (deps.platform !== 'linux') return 'skipped-platform';
133
+
134
+ // A local install (npm ci / npm install in a checkout, a crew worktree, or an npx
135
+ // cache) is not the production install. Acting on it as root rewrote the live unit
136
+ // and ran daemon-reload on the production host.
137
+ if (!isGlobalInstall(env)) {
138
+ log('skipping (not a global install: npm_config_global/npm_config_location not set)');
139
+ return 'skipped-not-global';
140
+ }
141
+
142
+ // Skip when not running as root — cannot write to /etc/systemd/system/.
143
+ if (deps.getuid() !== 0) {
144
+ log('skipping (not root)');
145
+ return 'skipped-not-root';
146
+ }
147
+
148
+ // When the daemon triggers its own in-app update it passes CLAGENTIC_CONSOLE_SELF_UPDATE=1.
149
+ // In that case, skip restarting the service — the daemon calls gracefulShutdown()
150
+ // immediately after npm install completes, and systemd Restart=always handles the
151
+ // supervised restart. Issuing systemctl restart here would race with gracefulShutdown
152
+ // and tear down sessions before state is flushed.
153
+ const { readConsoleEnv } = require('../lib/env-compat');
154
+ const selfUpdate = readConsoleEnv('CLAGENTIC_CONSOLE_SELF_UPDATE', { env }) === '1';
155
+ if (selfUpdate) {
156
+ log('self-update detected (CLAGENTIC_CONSOLE_SELF_UPDATE=1) — skipping service restart');
157
+ }
158
+
159
+ const newUnitDest = path.join(deps.systemdDir, NEW_UNIT);
160
+ const oldUnitPath = path.join(deps.systemdDir, OLD_UNIT);
161
+
162
+ // Step 0: Resolve the installed bin the unit will run; refuse to write a unit that
163
+ // points nowhere.
164
+ const cliBin = resolveCliBin({ env, pkgDir: deps.pkgDir });
165
+ if (!cliBin) {
166
+ log(`ERROR: cannot determine the global clagentic-console bin path from ${deps.pkgDir}; unit not installed`);
167
+ return 'error-no-bin';
168
+ }
169
+
170
+ // Step 1: Render and write the new unit file.
171
+ log(`installing unit file -> ${newUnitDest} (ExecStart=${cliBin} daemon)`);
172
+ try {
173
+ const rendered = renderUnit(fsx.readFileSync(deps.unitSrc, 'utf8'), cliBin);
174
+ fsx.writeFileSync(newUnitDest, rendered);
175
+ } catch (err) {
176
+ log(`ERROR installing unit file: ${errMsg(err)}`);
177
+ // Cannot continue without the unit file in place.
178
+ return 'error-unit';
179
+ }
180
+
181
+ // Step 2: daemon-reload to pick up the new unit file.
182
+ log('running systemctl daemon-reload');
183
+ try {
184
+ runCmd('systemctl', ['daemon-reload']);
185
+ } catch (err) {
186
+ // systemd still holds the previous ExecStart, which points at the legacy
187
+ // wrapper. Removing the wrapper now would make the next Restart=always fail,
188
+ // so keep it, stop here and fail the install step with the reason.
189
+ log(`ERROR: daemon-reload failed: ${errMsg(err)}; the new unit is written but not loaded, the legacy wrapper ${deps.legacyWrapperPath} is kept. Run "systemctl daemon-reload" and reinstall.`);
190
+ return 'error-reload';
191
+ }
192
+
193
+ // Step 3: Enable the new unit if not already enabled.
194
+ log(`enabling ${NEW_UNIT}`);
195
+ try {
196
+ runCmd('systemctl', ['enable', NEW_UNIT]);
197
+ } catch (err) {
198
+ log(`WARNING: enable ${NEW_UNIT} failed: ${errMsg(err)}`);
199
+ }
200
+
201
+ // Step 3b: The reload above succeeded, so systemd now runs the new ExecStart and the
202
+ // hand-placed wrapper is unreferenced; clean it up if untouched.
203
+ removeLegacyWrapper(deps);
204
+
205
+ // Step 4: Handle rename — migrate from old clagentic.service if present.
206
+ let wasRunningUnderOldUnit = false;
207
+ if (fsx.existsSync(oldUnitPath)) {
208
+ log(`old unit file detected: ${oldUnitPath} — performing rename cutover`);
209
+
210
+ // Detect whether the old unit is currently active before stopping it.
211
+ try {
212
+ const activeState = runCmd('systemctl', ['is-active', OLD_UNIT]);
213
+ if (activeState === 'active') {
214
+ wasRunningUnderOldUnit = true;
215
+ }
216
+ } catch (_) {
217
+ // is-active exits non-zero when not active — not an error.
218
+ }
219
+
220
+ log(`disabling ${OLD_UNIT}`);
221
+ try {
222
+ runCmd('systemctl', ['disable', OLD_UNIT]);
223
+ } catch (err) {
224
+ log(`WARNING: disable ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
225
+ }
226
+
227
+ log(`stopping ${OLD_UNIT}`);
228
+ try {
229
+ runCmd('systemctl', ['stop', OLD_UNIT]);
230
+ } catch (err) {
231
+ log(`WARNING: stop ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
232
+ }
233
+
234
+ log(`removing ${oldUnitPath}`);
235
+ try {
236
+ fsx.unlinkSync(oldUnitPath);
237
+ } catch (err) {
238
+ log(`WARNING: remove ${oldUnitPath} failed: ${errMsg(err)}`);
239
+ }
240
+
241
+ // daemon-reload again to clear the old unit from systemd's view.
242
+ log('running systemctl daemon-reload (post-rename)');
243
+ try {
244
+ runCmd('systemctl', ['daemon-reload']);
245
+ } catch (err) {
246
+ log(`WARNING: daemon-reload (post-rename) failed: ${errMsg(err)}`);
247
+ }
248
+ }
249
+
250
+ // Step 5: Start clagentic-console.service only if it was running under the old unit
251
+ // and needs to be moved to the new one. Never restart a running service — that kills
252
+ // live sessions. Never auto-start on a fresh install — the daemon needs configuration.
253
+ // Self-updates use gracefulShutdown() + Restart=always; postinstall must not interfere.
254
+ if (selfUpdate) {
255
+ log('skipping start (self-update — gracefulShutdown will hand off to systemd)');
256
+ } else if (wasRunningUnderOldUnit) {
257
+ log(`starting ${NEW_UNIT} (was running under ${OLD_UNIT})`);
258
+ try {
259
+ runCmd('systemctl', ['start', NEW_UNIT]);
260
+ } catch (err) {
261
+ log(`WARNING: start ${NEW_UNIT} failed: ${errMsg(err)}`);
262
+ }
263
+ } else {
264
+ log('skipping start (daemon was not running or is already running — operator controls restarts)');
265
+ }
266
+
267
+ // Step 6: Apply the memory-limit drop-in.
268
+ applyMemoryDropIn(deps);
269
+
270
+ log('done');
271
+ return 'installed';
272
+ }
273
+
274
+ module.exports = { run, realDeps, removeLegacyWrapper };
195
275
 
196
- log('done');
276
+ if (require.main === module) {
277
+ if (run(realDeps()) === 'error-reload') process.exitCode = 1;
278
+ }
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // Runs the prompt invariant harness's named regression scenarios
4
+ // (test/prompt-invariants.test.js) against the lib/ of the commits before
5
+ // and after each past fix, and against this checkout, and prints which
6
+ // invariants each run violated. A scenario that fails before its fix and
7
+ // passes after it shows the harness would have caught that defect.
8
+ //
9
+ // A commit just after one fix can still carry defects fixed later (the
10
+ // banner that outlived its prompt, fixed after most of these), so the
11
+ // scenario as a whole may still fail there. What must hold is narrower and
12
+ // exact: the violation the defect causes (its signature) appears before the
13
+ // fix and is gone after it, and the scenario passes outright on this
14
+ // checkout. The run exits non-zero when any of that does not hold, or when
15
+ // a run fails without naming an invariant (it crashed).
16
+ //
17
+ // npm run test:prompt-history [-- --scenario <scenario-label>]
18
+ //
19
+ // Each commit's lib/ is extracted with `git archive` into a temporary
20
+ // directory that borrows this checkout's node_modules; nothing in the
21
+ // repository is modified.
22
+
23
+ var fs = require("fs");
24
+ var os = require("os");
25
+ var path = require("path");
26
+ var { spawnSync, execFileSync } = require("child_process");
27
+
28
+ var REPO = path.join(__dirname, "..");
29
+ var HARNESS = path.join(REPO, "test", "prompt-invariants.test.js");
30
+
31
+ // scenario label (as passed to scenario() in the harness) -> its test title,
32
+ // the defect it reproduces, the violation that defect produces in the
33
+ // harness's report, and the commits just before and just after its fix.
34
+ var MATRIX = [
35
+ {
36
+ scenario: "grant-across-restart",
37
+ title: "Allow for Session survives a daemon restart",
38
+ defect: "an Allow for Session grant was lost on daemon restart",
39
+ signature: /was granted for the session but prompted again \(I7\)/,
40
+ before: "a31b2f4", after: "0ffb16f",
41
+ },
42
+ {
43
+ scenario: "subagent-vs-parent-result",
44
+ title: "a sub-agent's request survives its parent's turn result",
45
+ defect: "the parent turn's result dropped a sub-agent's pending request",
46
+ signature: /is still awaiting the operator but the server no longer offers it \(I1\)|did not settle it \(I4\)/,
47
+ before: "c886cf0", after: "ac18d9f",
48
+ },
49
+ {
50
+ scenario: "skill-grant-scope",
51
+ title: "Allow for Session on one skill does not approve another",
52
+ defect: "a Skill grant was keyed on the bare tool name",
53
+ signature: /did not open exactly one prompt \(I7\)|was granted for the session but/,
54
+ before: "270f0ee", after: "e8e8bfa",
55
+ },
56
+ {
57
+ scenario: "task-notification-before-answer",
58
+ title: "a Task's completion before the operator answers keeps its request answerable",
59
+ defect: "task_notification released half of the ownership guard",
60
+ signature: /the request ended before the operator answered \(I6\)/,
61
+ before: "b4811a2", after: "68aa87d",
62
+ },
63
+ {
64
+ scenario: "late-second-response",
65
+ title: "a second client's late response is answered and every banner retires",
66
+ defect: "a late second response got no answer and the banner stayed",
67
+ signature: /is over but its notification still offers buttons \(I2\)|got no reply \(I4\)/,
68
+ before: "349dbc2", after: "e49bd48",
69
+ },
70
+ {
71
+ scenario: "pending-across-restart",
72
+ title: "a request open across a daemon restart is not offered afterwards",
73
+ defect: "a request open at restart was still offered as pending",
74
+ signature: /still sees \S+ as pending after it ended \(I2\)/,
75
+ before: "e49bd48", after: "4015dbc",
76
+ },
77
+ ];
78
+
79
+ function parseArgs(argv) {
80
+ var out = { scenario: null };
81
+ for (var i = 0; i < argv.length; i++) {
82
+ if (argv[i] === "--scenario") out.scenario = argv[++i];
83
+ }
84
+ return out;
85
+ }
86
+
87
+ function escapeRegExp(s) {
88
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
89
+ }
90
+
91
+ // A directory holding <commit>'s lib/ and a link to this checkout's
92
+ // node_modules, so the old modules resolve their dependencies.
93
+ function materializeLib(commit, root) {
94
+ var dir = path.join(root, commit);
95
+ fs.mkdirSync(dir, { recursive: true });
96
+ var archive = spawnSync("git", ["-C", REPO, "archive", "--format=tar", commit, "lib"], { maxBuffer: 512 * 1024 * 1024 });
97
+ if (archive.status !== 0) throw new Error("git archive " + commit + " failed: " + String(archive.stderr));
98
+ var untar = spawnSync("tar", ["-x", "-C", dir], { input: archive.stdout });
99
+ if (untar.status !== 0) throw new Error("tar for " + commit + " failed: " + String(untar.stderr));
100
+ fs.symlinkSync(path.join(REPO, "node_modules"), path.join(dir, "node_modules"), "dir");
101
+ return path.join(dir, "lib");
102
+ }
103
+
104
+ // Environment for one harness run. The un-scoped name is cleared as well as the
105
+ // scoped one: an inherited value of either must not steer a HEAD (libDir-less)
106
+ // run at an older checkout.
107
+ function harnessEnv(baseEnv, libDir) {
108
+ var env = Object.assign({}, baseEnv);
109
+ delete env.CLAGENTIC_PROMPT_HARNESS_LIB;
110
+ if (libDir) env.CLAGENTIC_CONSOLE_PROMPT_HARNESS_LIB = libDir;
111
+ else delete env.CLAGENTIC_CONSOLE_PROMPT_HARNESS_LIB;
112
+ return env;
113
+ }
114
+
115
+ // The invariants a run violated, e.g. ["I2", "I8"], or [] for a pass.
116
+ function runScenario(row, libDir) {
117
+ var env = harnessEnv(process.env, libDir);
118
+ var res = spawnSync(process.execPath, [
119
+ "--test", "--test-reporter=tap", "--test-name-pattern=^" + escapeRegExp(row.title) + "$", HARNESS,
120
+ ], { env: env, encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
121
+ var output = (res.stdout || "") + (res.stderr || "");
122
+ var codes = {};
123
+ var re = /\((I\d)(?:\/(I\d))?\)/g;
124
+ var m;
125
+ while ((m = re.exec(output)) !== null) {
126
+ codes[m[1]] = true;
127
+ if (m[2]) codes[m[2]] = true;
128
+ }
129
+ var passed = res.status === 0;
130
+ if (!passed && Object.keys(codes).length === 0) codes.error = true;
131
+ return { passed: passed, codes: Object.keys(codes).sort(), output: output };
132
+ }
133
+
134
+ function shows(row, result) {
135
+ return !result.passed && row.signature.test(result.output);
136
+ }
137
+
138
+ function crashed(result) {
139
+ return !result.passed && result.codes.indexOf("error") !== -1;
140
+ }
141
+
142
+ function describe(row, result) {
143
+ if (result.passed) return "pass";
144
+ return "FAIL " + result.codes.join(",") + (shows(row, result) ? "" : " (not this defect)");
145
+ }
146
+
147
+ /**
148
+ * What is wrong with one scenario's three runs: before its fix the run
149
+ * must show the defect's own violation (else the harness does not
150
+ * reproduce it); after the fix that violation must be gone and the run must
151
+ * not have crashed (else the fix did not hold, or nothing was checked); on
152
+ * this checkout the scenario must pass outright.
153
+ * @returns {string[]} one line per problem; [] when the row holds.
154
+ */
155
+ function rowProblems(row, before, after, now) {
156
+ var out = [];
157
+ if (!shows(row, before)) out.push(row.scenario + " does not show its defect before its fix (" + row.before + "): the harness does not reproduce it\n" + before.output);
158
+ if (shows(row, after) || crashed(after)) out.push(row.scenario + " still fails with its defect after its fix (" + row.after + "):\n" + after.output);
159
+ if (!now.passed) out.push(row.scenario + " fails on this checkout:\n" + now.output);
160
+ return out;
161
+ }
162
+
163
+ function main() {
164
+ var args = parseArgs(process.argv.slice(2));
165
+ var rows = MATRIX.filter(function (r) { return !args.scenario || r.scenario === args.scenario; });
166
+ if (rows.length === 0) {
167
+ console.error("no scenario named " + args.scenario + "; known: " + MATRIX.map(function (r) { return r.scenario; }).join(", "));
168
+ process.exitCode = 1;
169
+ return;
170
+ }
171
+ // Commits must exist locally; a shallow clone cannot reproduce history.
172
+ rows.forEach(function (r) {
173
+ [r.before, r.after].forEach(function (c) { execFileSync("git", ["-C", REPO, "cat-file", "-e", c + "^{commit}"]); });
174
+ });
175
+
176
+ var root = fs.mkdtempSync(path.join(os.tmpdir(), "prompt-harness-history-"));
177
+ var libs = {};
178
+ var unexpected = [];
179
+ try {
180
+ console.log("scenario | defect | before fix | after fix | this checkout");
181
+ console.log("---|---|---|---|---");
182
+ rows.forEach(function (r) {
183
+ [r.before, r.after].forEach(function (c) { if (!libs[c]) libs[c] = materializeLib(c, root); });
184
+ var before = runScenario(r, libs[r.before]);
185
+ var after = runScenario(r, libs[r.after]);
186
+ var now = runScenario(r, null);
187
+ console.log([r.scenario, r.defect,
188
+ r.before + ": " + describe(r, before), r.after + ": " + describe(r, after), describe(r, now)].join(" | "));
189
+ unexpected = unexpected.concat(rowProblems(r, before, after, now));
190
+ });
191
+ } finally {
192
+ fs.rmSync(root, { recursive: true, force: true });
193
+ }
194
+ if (unexpected.length) {
195
+ console.error("\n" + unexpected.join("\n\n"));
196
+ process.exitCode = 1;
197
+ }
198
+ }
199
+
200
+ if (require.main === module) main();
201
+
202
+ module.exports = { MATRIX: MATRIX, rowProblems: rowProblems, harnessEnv: harnessEnv };