evolcore 0.0.24 → 0.0.25

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 (197) hide show
  1. package/CHANGELOG.md +578 -561
  2. package/LICENSE +21 -21
  3. package/README.md +455 -455
  4. package/bin/codex-managed-acl.ps1 +160 -160
  5. package/bin/codex-managed-hook.mjs +208 -208
  6. package/bin/ec-safe-output.js +327 -327
  7. package/bin/ec.js +29 -29
  8. package/bin/install-codex-managed-hooks.mjs +555 -555
  9. package/dist/agents/claude-runner.js +4 -1
  10. package/dist/agents/codex-runner.js +7 -4
  11. package/dist/agents/ecagent-runner.js +14 -13
  12. package/dist/agents/gemini-runner.js +22 -2
  13. package/dist/aun/aid/agentmd.js +56 -4
  14. package/dist/aun/aid/index.js +1 -0
  15. package/dist/aun/aid/managed-operation.js +53 -1
  16. package/dist/aun/storage/client.js +4 -1
  17. package/dist/aun/storage/index.js +1 -1
  18. package/dist/cli/agent-command.js +186 -87
  19. package/dist/cli/agent-create.js +42 -4
  20. package/dist/cli/agent.js +103 -1
  21. package/dist/cli/aun-commands.js +360 -294
  22. package/dist/cli/bench.js +20 -20
  23. package/dist/cli/config.js +20 -20
  24. package/dist/cli/contact.js +10 -10
  25. package/dist/cli/ctl-command.js +22 -22
  26. package/dist/cli/daemon-commands.js +15 -15
  27. package/dist/cli/fs-command.js +67 -67
  28. package/dist/cli/handoff-command.js +7 -7
  29. package/dist/cli/index.js +77 -77
  30. package/dist/cli/link-rules.js +21 -21
  31. package/dist/cli/menu-client.js +11 -11
  32. package/dist/cli/net-check.js +22 -22
  33. package/dist/cli/queue-command.js +29 -29
  34. package/dist/cli/response.js +30 -30
  35. package/dist/cli/restart-monitor.js +30 -30
  36. package/dist/cli/stats.js +51 -51
  37. package/dist/cli/trigger-command.js +56 -56
  38. package/dist/config/builtin-roles.js +1 -0
  39. package/dist/config/config-manager.js +15 -0
  40. package/dist/config/config-operation-service.js +20 -3
  41. package/dist/config/resolved-config-op.js +39 -1
  42. package/dist/core/auth/operation-authorizer.js +62 -4
  43. package/dist/core/auth/operation-catalog.js +16 -0
  44. package/dist/core/command/agent-control.js +54 -25
  45. package/dist/core/command/cli-intent-parser.js +18 -0
  46. package/dist/core/command/command-handler.js +91 -16
  47. package/dist/core/command/menu-catalog.js +1 -0
  48. package/dist/core/command/menu-handler.js +41 -5
  49. package/dist/core/command/menu-protocol.js +1 -0
  50. package/dist/core/command/slash-handler.js +9 -9
  51. package/dist/core/event-catalog.js +5 -0
  52. package/dist/core/evolagent.js +3 -3
  53. package/dist/core/message/response-engine.js +12 -6
  54. package/dist/core/permission/tool-policy.js +45 -6
  55. package/dist/index.js +209 -162
  56. package/dist/stats/db.js +159 -159
  57. package/dist/stats/eck-vars.js +9 -9
  58. package/dist/stats/query.js +139 -139
  59. package/dist/stats/role-budget.js +6 -6
  60. package/dist/stats/writer.js +51 -51
  61. package/dist/utils/avatar-upload.js +282 -23
  62. package/dist/utils/error-dict.json +160 -160
  63. package/dist/utils/macos-autostart.js +22 -22
  64. package/dist/utils/model-prices.jsonl +23 -23
  65. package/dist/utils/welcome.js +22 -22
  66. package/ecagent/LICENSE +21 -21
  67. package/ecagent/NOTICE +11 -11
  68. package/ecagent/README.md +61 -61
  69. package/ecagent/dist/harness/compaction/branch-summarization.js +30 -30
  70. package/ecagent/dist/harness/compaction/compaction.js +83 -83
  71. package/ecagent/dist/harness/messages.js +7 -7
  72. package/kits/docs/GUIDE.md +20 -20
  73. package/kits/docs/INDEX.md +66 -66
  74. package/kits/docs/aun/CHEATSHEET.md +19 -19
  75. package/kits/docs/aun/SYNC_PROTOCOL.md +15 -15
  76. package/kits/docs/channels/aun.md +56 -56
  77. package/kits/docs/channels/feishu.md +56 -56
  78. package/kits/docs/context-assembly.md +365 -364
  79. package/kits/docs/eck_templates/GUIDE.template.md +22 -22
  80. package/kits/docs/eck_templates/INDEX.template.md +28 -28
  81. package/kits/docs/eck_templates/path-registry.template.md +33 -33
  82. package/kits/docs/eck_templates/runtime.template.md +19 -19
  83. package/kits/docs/evolcore/INDEX.md +71 -69
  84. package/kits/docs/evolcore/agent-create.md +170 -156
  85. package/kits/docs/evolcore/agent.md +83 -73
  86. package/kits/docs/evolcore/aid.md +64 -62
  87. package/kits/docs/evolcore/codex-windows-sandbox.md +146 -0
  88. package/kits/docs/evolcore/config.md +195 -195
  89. package/kits/docs/evolcore/contact.md +68 -68
  90. package/kits/docs/evolcore/ctl.md +46 -46
  91. package/kits/docs/evolcore/event.md +216 -216
  92. package/kits/docs/evolcore/fs-architecture.md +1215 -1215
  93. package/kits/docs/evolcore/fs.md +110 -110
  94. package/kits/docs/evolcore/group-collaboration.md +243 -243
  95. package/kits/docs/evolcore/group-fs.md +17 -17
  96. package/kits/docs/evolcore/group-rules.md +251 -251
  97. package/kits/docs/evolcore/group.md +152 -152
  98. package/kits/docs/evolcore/menu-client.md +34 -34
  99. package/kits/docs/evolcore/model.md +50 -50
  100. package/kits/docs/evolcore/msg.md +165 -165
  101. package/kits/docs/evolcore/response.md +75 -75
  102. package/kits/docs/evolcore/rpc.md +37 -37
  103. package/kits/docs/evolcore/self-summary.md +29 -29
  104. package/kits/docs/evolcore/stats.md +83 -83
  105. package/kits/docs/evolcore/storage.md +50 -50
  106. package/kits/docs/evolcore/trigger.md +575 -575
  107. package/kits/docs/identity/AID_PROFILE_SPEC.md +26 -26
  108. package/kits/docs/identity/PATH_OPS.md +16 -16
  109. package/kits/docs/identity/ROLE_DETAIL.md +25 -25
  110. package/kits/docs/identity/identity-tools.md +26 -26
  111. package/kits/docs/path-registry.md +62 -62
  112. package/kits/docs/prompt-loading-architecture.md +270 -269
  113. package/kits/docs/venues/aun-group.md +45 -45
  114. package/kits/docs/venues/aun-private.md +10 -10
  115. package/kits/docs/venues/client-desktop.md +10 -10
  116. package/kits/docs/venues/client-mobile.md +10 -10
  117. package/kits/docs/venues/feishu-group.md +13 -13
  118. package/kits/docs/venues/feishu-private.md +9 -9
  119. package/kits/docs/venues/group.md +25 -25
  120. package/kits/docs/venues/private.md +10 -10
  121. package/kits/eck_manifest.auxiliary.json +43 -43
  122. package/kits/eck_manifest.json +195 -183
  123. package/kits/eck_message_manifest.json +74 -74
  124. package/kits/migrations/README-role-config-v4.md +32 -32
  125. package/kits/migrations/migrate-contact-book-v2.mjs +748 -748
  126. package/kits/migrations/migrate-role-config-v4.mjs +614 -614
  127. package/kits/migrations/migrate-role-config-v5.mjs +365 -365
  128. package/kits/migrations/rename-config-file.mjs +99 -99
  129. package/kits/rules/01-overview.md +162 -162
  130. package/kits/rules/02-navigation.md +96 -96
  131. package/kits/rules/03-identity.md +39 -37
  132. package/kits/rules/04-relation.md +75 -75
  133. package/kits/rules/05-venue.md +60 -60
  134. package/kits/rules/06-channel.md +63 -63
  135. package/kits/schemas/_meta.json +53 -53
  136. package/kits/schemas/agent-config.schema.1.json +177 -177
  137. package/kits/schemas/agent-config.schema.10.json +395 -395
  138. package/kits/schemas/agent-config.schema.11.json +421 -421
  139. package/kits/schemas/agent-config.schema.12.json +427 -427
  140. package/kits/schemas/agent-config.schema.2.json +239 -239
  141. package/kits/schemas/agent-config.schema.3.json +119 -119
  142. package/kits/schemas/agent-config.schema.4.json +208 -208
  143. package/kits/schemas/agent-config.schema.5.json +326 -326
  144. package/kits/schemas/agent-config.schema.6.json +322 -322
  145. package/kits/schemas/agent-config.schema.7.json +303 -303
  146. package/kits/schemas/agent-config.schema.8.json +304 -304
  147. package/kits/schemas/agent-config.schema.9.json +364 -364
  148. package/kits/schemas/contact-book.schema.1.json +36 -36
  149. package/kits/schemas/contact-book.schema.2.json +43 -43
  150. package/kits/schemas/contact-book.schema.3.json +67 -67
  151. package/kits/schemas/daemon.schema.1.json +91 -91
  152. package/kits/schemas/daemon.schema.2.json +101 -101
  153. package/kits/schemas/daemon.schema.3.json +123 -123
  154. package/kits/schemas/daemon.schema.4.json +136 -136
  155. package/kits/schemas/daemon.schema.5.json +135 -135
  156. package/kits/schemas/daemon.schema.6.json +131 -131
  157. package/kits/schemas/defaults.schema.1.json +81 -81
  158. package/kits/schemas/defaults.schema.2.json +85 -85
  159. package/kits/schemas/defaults.schema.3.json +73 -73
  160. package/kits/schemas/defaults.schema.4.json +107 -107
  161. package/kits/schemas/defaults.schema.5.json +119 -119
  162. package/kits/schemas/menu-exec-schema-commands.md +208 -208
  163. package/kits/schemas/migrations/README.md +30 -30
  164. package/kits/schemas/relation-config.schema.1.json +158 -158
  165. package/kits/schemas/relation-config.schema.2.json +73 -73
  166. package/kits/schemas/relation-config.schema.3.json +50 -50
  167. package/kits/schemas/relation-config.schema.4.json +47 -47
  168. package/kits/schemas/relation-config.schema.5.json +47 -47
  169. package/kits/schemas/relation-config.schema.6.json +46 -46
  170. package/kits/schemas/relation-config.schema.7.json +59 -59
  171. package/kits/schemas/relation-config.schema.8.json +103 -103
  172. package/kits/schemas/role-config.schema.1.json +201 -201
  173. package/kits/schemas/role-registry.schema.1.json +35 -35
  174. package/kits/schemas/single-session.schema.1.json +31 -31
  175. package/kits/schemas/single-session.schema.2.json +57 -57
  176. package/kits/schemas/single-session.schema.3.json +32 -32
  177. package/kits/templates/bootstrap-welcome.md +17 -17
  178. package/kits/templates/message-fragments/handoff-context-to-target.md +9 -9
  179. package/kits/templates/message-fragments/handoff-request-to-target.md +19 -19
  180. package/kits/templates/message-fragments/handoff-response-to-origin.md +9 -9
  181. package/kits/templates/message-fragments/inject-default.md +2 -2
  182. package/kits/templates/message-fragments/item.md +2 -2
  183. package/kits/templates/roles/admin.json +96 -84
  184. package/kits/templates/roles/member.json +97 -96
  185. package/kits/templates/roles/owner.json +9 -9
  186. package/kits/templates/roles/visitor.json +86 -85
  187. package/kits/templates/system-fragments/baseagent.md +14 -14
  188. package/kits/templates/system-fragments/bootstrap.md +38 -29
  189. package/kits/templates/system-fragments/channel.md +64 -64
  190. package/kits/templates/system-fragments/commands.md +28 -28
  191. package/kits/templates/system-fragments/identity.md +13 -13
  192. package/kits/templates/system-fragments/relation.md +19 -19
  193. package/kits/templates/system-fragments/session.md +59 -59
  194. package/kits/templates/system-fragments/venue.md +31 -31
  195. package/package.json +98 -98
  196. package/skills/eclink/SKILL.md +0 -84
  197. package/skills/eclink/agents/openai.yaml +0 -4
@@ -1,555 +1,555 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { randomUUID } from 'node:crypto';
7
- import { execFileSync } from 'node:child_process';
8
- import { fileURLToPath, pathToFileURL } from 'node:url';
9
- import { isDeepStrictEqual } from 'node:util';
10
- import { parse as parseToml } from 'smol-toml';
11
-
12
- const markerStart = '# BEGIN EVOLCORE MANAGED CODEX HOOK';
13
- const markerEnd = '# END EVOLCORE MANAGED CODEX HOOK';
14
- const aclScript = fileURLToPath(new URL('./codex-managed-acl.ps1', import.meta.url));
15
-
16
- function argument(name) {
17
- const index = process.argv.indexOf(name);
18
- return index >= 0 ? process.argv[index + 1] : undefined;
19
- }
20
-
21
- function hasArgument(name) {
22
- return process.argv.includes(name);
23
- }
24
-
25
- function fail(message) {
26
- process.stderr.write(`[evolcore] ${message}\n`);
27
- process.exit(1);
28
- }
29
-
30
- function isGlobalInstall() {
31
- return ['1', 'true'].includes(String(process.env.npm_config_global || '').toLowerCase());
32
- }
33
-
34
- function lifecycleEvent() {
35
- const entry = Object.entries(process.env).find(([key]) => key.toLowerCase() === 'npm_lifecycle_event');
36
- return String(entry?.[1] || '').toLowerCase();
37
- }
38
-
39
- function ensureRealDirectory(directory) {
40
- let stat;
41
- try {
42
- stat = fs.lstatSync(directory);
43
- } catch (error) {
44
- if (error?.code !== 'ENOENT') {
45
- fail(`could not inspect the Codex managed requirements mountpoint ${directory}: ${error?.message || String(error)}`);
46
- }
47
- }
48
-
49
- if (stat) {
50
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
51
- fail(`Codex managed requirements mountpoint is unsafe: ${directory} must be a real directory.`);
52
- }
53
- return;
54
- }
55
-
56
- try {
57
- fs.mkdirSync(directory, { mode: 0o755 });
58
- fs.chmodSync(directory, 0o755);
59
- } catch (error) {
60
- if (error?.code === 'EEXIST') {
61
- const raced = fs.lstatSync(directory);
62
- if (raced.isDirectory() && !raced.isSymbolicLink()) return;
63
- }
64
- fail(
65
- `Linux global installation requires the real directory ${directory}, but it could not be created: `
66
- + `${error?.message || String(error)}. `
67
- + `Create it first with: sudo install -d -m 0755 ${directory}`,
68
- );
69
- }
70
-
71
- const created = fs.lstatSync(directory);
72
- if (!created.isDirectory() || created.isSymbolicLink()) {
73
- fail(`Codex managed requirements mountpoint provisioning failed: ${directory} must be a real directory.`);
74
- }
75
- process.stdout.write(`[evolcore] Prepared Codex managed requirements mountpoint at ${directory}.\n`);
76
- }
77
-
78
- function runLinuxPostinstall() {
79
- const explicitMountpoint = argument('--mountpoint');
80
- if (process.platform !== 'linux') return;
81
- // Local source installs do not launch the Linux Codex guard and must not
82
- // mutate machine-wide configuration. An explicit path is accepted only for
83
- // isolated lifecycle behavior tests.
84
- if (!isGlobalInstall() && !explicitMountpoint) return;
85
- ensureRealDirectory(explicitMountpoint || '/etc/codex');
86
- }
87
-
88
- function tomlString(value) {
89
- return JSON.stringify(value);
90
- }
91
-
92
- function windowsCommandArg(value) {
93
- // Keep filesystem separators intact; tomlString() performs the required
94
- // TOML escaping after this Windows command-line quoting step.
95
- return `"${value.replaceAll('"', '\\"')}"`;
96
- }
97
-
98
- function windowsPostinstallNotice() {
99
- if (process.platform !== 'win32') return;
100
- process.stderr.write(
101
- '[evolcore] ec start/restart automatically checks and installs missing Codex managed hooks on Windows.\n'
102
- + '[evolcore] Accept the Windows administrator (UAC) prompt when installation is needed; no separate setup command is required.\n',
103
- );
104
- }
105
-
106
- function removeManagedBlock(source) {
107
- const original = parseToml(source);
108
- if (!source.includes(markerStart) && !source.includes(markerEnd)) return source;
109
- const unsafe = () => new Error('Ambiguous EvolCore managed Hook markers in requirements.toml. Existing configuration was not modified.');
110
- const expression = new RegExp(`^${markerStart}\\r?\\n[\\s\\S]*?^${markerEnd}(?:\\r?\\n|$)`, 'gm');
111
- const matches = [...source.matchAll(expression)];
112
- if (matches.length !== 1 || source.split(markerStart).length !== 2 || source.split(markerEnd).length !== 2) throw unsafe();
113
- const block = parseToml(matches[0][0]);
114
- const groups = block.hooks?.PreToolUse;
115
- if (!Array.isArray(groups) || groups.length !== 1
116
- || !isDeepStrictEqual(block, { hooks: { PreToolUse: groups } })) throw unsafe();
117
- const content = source.replace(matches[0][0], '');
118
- const retained = parseToml(content);
119
- const originalGroups = original.hooks?.PreToolUse;
120
- if (!Array.isArray(originalGroups)) throw unsafe();
121
- // Markers inside a TOML string are not comments. Prove that removing the
122
- // block removes only its Hook group, with every other policy unchanged.
123
- const safe = originalGroups.some((group, index) => {
124
- if (!isDeepStrictEqual(group, groups[0])) return false;
125
- const expected = structuredClone(original);
126
- expected.hooks.PreToolUse.splice(index, 1);
127
- if (!expected.hooks.PreToolUse.length && !retained.hooks?.PreToolUse) delete expected.hooks.PreToolUse;
128
- if (!Object.keys(expected.hooks).length && !retained.hooks) delete expected.hooks;
129
- return isDeepStrictEqual(expected, retained);
130
- });
131
- if (!safe) throw unsafe();
132
- return content;
133
- }
134
-
135
- function tableBounds(lines, table) {
136
- const header = table ? `[${table}]` : null;
137
- const start = header
138
- ? lines.findIndex(line => line.trim() === header || line.trim().startsWith(`${header} #`))
139
- : -1;
140
- if (table && start < 0) return null;
141
- const from = table ? start + 1 : 0;
142
- let to = lines.length;
143
- for (let index = from; index < lines.length; index += 1) {
144
- if (/^\s*\[\[?[^\]]+\]\]?\s*(?:#.*)?$/.test(lines[index])) {
145
- to = index;
146
- break;
147
- }
148
- }
149
- return { start, from, to };
150
- }
151
-
152
- function setTomlKey(source, table, key, value) {
153
- const lines = source.split('\n');
154
- let bounds = tableBounds(lines, table);
155
- if (!bounds) {
156
- if (table) {
157
- if (lines.length && lines.at(-1) !== '') lines.push('');
158
- lines.push(`[${table}]`, `${key} = ${value}`);
159
- } else {
160
- let insertAt = lines.findIndex(line => /^\s*\[/.test(line));
161
- if (insertAt < 0) insertAt = lines.length;
162
- lines.splice(insertAt, 0, `${key} = ${value}`);
163
- }
164
- return lines.join('\n');
165
- }
166
- const keyExpression = new RegExp(`^\\s*${key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}\\s*=`);
167
- const existing = lines.slice(bounds.from, bounds.to).findIndex(line => keyExpression.test(line));
168
- if (existing >= 0) {
169
- lines[bounds.from + existing] = `${key} = ${value}`;
170
- } else {
171
- lines.splice(bounds.from, 0, `${key} = ${value}`);
172
- }
173
- return lines.join('\n');
174
- }
175
-
176
- export function managedHookLauncher(packageRoot) {
177
- // Keep the machine-wide entrypoint stable across npm upgrades. Those
178
- // upgrades replace the package contents at this stable global path, so
179
- // this file never needs to be rewritten just because the hook changed.
180
- const trustedPackageRoot = path.resolve(packageRoot);
181
- return `#!/usr/bin/env node
182
- import path from 'node:path';
183
- import { pathToFileURL } from 'node:url';
184
-
185
- // EVOLCORE_MANAGED_HOOK_LAUNCHER
186
- const packageRoot = ${JSON.stringify(trustedPackageRoot)};
187
-
188
- try {
189
- await import(pathToFileURL(path.join(packageRoot, 'bin', 'codex-managed-hook.mjs')).href);
190
- } catch (error) {
191
- process.stderr.write('[evolcore] failed to load the current managed hook: '
192
- + (error instanceof Error ? error.message : String(error)) + '\\n');
193
- process.exit(2);
194
- }
195
- `;
196
- }
197
-
198
- export function buildManagedRequirements(source, { targetDirectory, nodePath, hookPath }) {
199
- // Keep the existing text editor, but reject unsupported TOML layouts before
200
- // writing anything. Parsing also catches duplicate tables/keys on reinstall.
201
- let content = removeManagedBlock(source);
202
- const before = parseToml(content);
203
- content = setTomlKey(content, null, 'allow_managed_hooks_only', 'true');
204
- content = setTomlKey(content, 'features', 'hooks', 'true');
205
- content = setTomlKey(content, 'hooks', 'windows_managed_dir', tomlString(path.resolve(targetDirectory)));
206
- if (!content.endsWith('\n')) content += '\n';
207
- // Windows hook command must include %EVOLCORE_INSTANCE_SOCKET% so Codex
208
- // expands it at runtime with the per-daemon socket path
209
- const command = `${windowsCommandArg(nodePath)} ${windowsCommandArg(hookPath)} %EVOLCORE_INSTANCE_SOCKET%`;
210
- content += [
211
- markerStart,
212
- '[[hooks.PreToolUse]]',
213
- 'matcher = "*"',
214
- '',
215
- '[[hooks.PreToolUse.hooks]]',
216
- 'type = "command"',
217
- `command = ${tomlString(command)}`,
218
- `command_windows = ${tomlString(command)}`,
219
- // Intentionally omit timeout: Codex applies its documented 600-second
220
- // default for synchronous PreToolUse hooks. The application pause gate
221
- // itself has no timeout; Codex remains the outer infrastructure ceiling.
222
- 'statusMessage = "Checking EvolCore session policy"',
223
- markerEnd,
224
- '',
225
- ].join('\n');
226
- const after = parseToml(content);
227
- const expected = {
228
- ...before,
229
- allow_managed_hooks_only: true,
230
- features: { ...before.features, hooks: true },
231
- hooks: {
232
- ...before.hooks,
233
- windows_managed_dir: path.resolve(targetDirectory),
234
- PreToolUse: [
235
- ...(before.hooks?.PreToolUse || []),
236
- { matcher: '*', hooks: [{ type: 'command', command, command_windows: command, statusMessage: 'Checking EvolCore session policy' }] },
237
- ],
238
- },
239
- };
240
- if (!isDeepStrictEqual(after, expected)) {
241
- throw new Error('Could not safely update requirements.toml without changing unrelated policy. Existing configuration was not modified.');
242
- }
243
- return content;
244
- }
245
-
246
- function regularFile(file) {
247
- try {
248
- const stat = fs.lstatSync(file);
249
- if (!stat.isFile() || stat.isSymbolicLink()) return { ok: false, unsafe: true };
250
- return { ok: true };
251
- } catch (error) {
252
- if (error?.code === 'ENOENT') return { ok: false, unsafe: false };
253
- return { ok: false, unsafe: true, error };
254
- }
255
- }
256
-
257
- function sourceHasManagedMarker(source) {
258
- return source.includes(markerStart) || source.includes(markerEnd);
259
- }
260
-
261
- /** Inspect only the canonical EvolCore managed-hook targets. */
262
- export function inspectManagedHookInstallation({ requirements, managedDir, packageRoot }) {
263
- const canonicalRequirements = path.resolve(requirements);
264
- const canonicalManagedDir = path.resolve(managedDir);
265
- const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
266
- for (const directory of [path.dirname(canonicalRequirements), canonicalManagedDir]) {
267
- try {
268
- const stat = fs.lstatSync(directory);
269
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
270
- return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `${directory} must be a real directory` };
271
- }
272
- } catch (error) {
273
- if (error?.code !== 'ENOENT') return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: error?.message || String(error) };
274
- }
275
- }
276
- const req = regularFile(canonicalRequirements);
277
- const hook = regularFile(hookPath);
278
- if (req.unsafe || hook.unsafe) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is not a regular file' };
279
- if (!req.ok && hook.ok) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'canonical launcher exists but requirements.toml is missing' };
280
- if (req.ok && !hook.ok) {
281
- // A missing launcher can be repaired only when the requirements file is
282
- // still an untouched user configuration. If it already contains any
283
- // EvolCore-managed policy, treat the partial state as drift and fail
284
- // closed instead of guessing which policy is authoritative.
285
- try {
286
- const source = fs.readFileSync(canonicalRequirements, 'utf8');
287
- const partial = parseToml(source);
288
- const managedPolicyPresent = sourceHasManagedMarker(source)
289
- || partial.allow_managed_hooks_only !== undefined
290
- || partial.hooks?.windows_managed_dir !== undefined
291
- || partial.hooks?.managed_dir !== undefined;
292
- if (managedPolicyPresent) {
293
- return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements contains managed-hook policy but the canonical launcher is missing' };
294
- }
295
- } catch (error) {
296
- return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` };
297
- }
298
- }
299
- if (!req.ok || !hook.ok) return { status: 'missing', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is missing' };
300
- let parsed;
301
- try { parsed = parseToml(fs.readFileSync(canonicalRequirements, 'utf8')); }
302
- catch (error) { return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` }; }
303
- const configured = parsed.hooks?.windows_managed_dir ?? parsed.hooks?.managed_dir;
304
- const normalized = value => path.normalize(String(value || '')).toLowerCase();
305
- const launcher = fs.readFileSync(hookPath, 'utf8');
306
- const packageMarker = launcher.includes('EVOLCORE_MANAGED_HOOK_LAUNCHER')
307
- && launcher.toLowerCase().includes(JSON.stringify(path.resolve(packageRoot || process.cwd())).toLowerCase());
308
- const preToolUse = parsed.hooks?.PreToolUse;
309
- const canonicalCommand = value => {
310
- if (typeof value !== 'string' || !value || /[\r\n;&|<>]/.test(value)) return false;
311
- const withoutSocket = value.replace(/\s+%EVOLCORE_INSTANCE_SOCKET%\s*$/i, '').trim();
312
- return withoutSocket.replace(/["']+$/, '').toLowerCase().endsWith(normalized(hookPath));
313
- };
314
- const loaded = Array.isArray(preToolUse) && preToolUse.some(group => group?.matcher === '*'
315
- && Array.isArray(group.hooks) && group.hooks.some(handler => handler?.type === 'command'
316
- && handler.async !== true && typeof handler.command === 'string'
317
- && canonicalCommand(handler.command)
318
- && canonicalCommand(handler.command_windows ?? handler.commandWindows)));
319
- const valid = parsed.allow_managed_hooks_only === true
320
- && parsed.features?.hooks === true
321
- && normalized(configured) === normalized(canonicalManagedDir)
322
- && packageMarker && loaded;
323
- return valid
324
- ? { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath }
325
- : { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'managed-hook policy is missing, altered, or points outside the canonical target' };
326
- }
327
-
328
- /** Idempotently repair a missing canonical installation; unsafe edits fail closed. */
329
- export function repairManagedHookInstallation(options, acl = windowsAcl) {
330
- const { requirements, managedDir, packageRoot, nodePath = process.execPath } = options;
331
- const canonicalRequirements = path.resolve(requirements);
332
- const canonicalManagedDir = path.resolve(managedDir);
333
- const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
334
- const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
335
- const state = inspectManagedHookInstallation({ requirements: canonicalRequirements, managedDir: canonicalManagedDir, packageRoot });
336
- if (state.status === 'installed') return { ...state, repaired: false, warnings: [] };
337
- if (state.status === 'unsafe') throw new Error(`Refusing automatic managed-hook repair: ${state.reason}`);
338
- if (!fs.existsSync(sourceHook)) throw new Error(`Required Hook runtime file was not found: ${sourceHook}`);
339
- const previousContent = fs.existsSync(canonicalRequirements) ? fs.readFileSync(canonicalRequirements, 'utf8') : '';
340
- const content = buildManagedRequirements(previousContent, { targetDirectory: canonicalManagedDir, nodePath, hookPath });
341
- const warnings = provisionManagedFiles({ requirements: canonicalRequirements, hookPath, sourceHook, nodePath, previousContent, content, launcher: managedHookLauncher(packageRoot) }, acl);
342
- return { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, repaired: true, warnings };
343
- }
344
-
345
- export function windowsAcl(action, payload = {}, run = execFileSync) {
346
- const executable = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
347
- try {
348
- const output = run(executable, [
349
- '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', aclScript,
350
- '-Request', Buffer.from(JSON.stringify({ action, ...payload })).toString('base64'),
351
- ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, timeout: 30_000 });
352
- return JSON.parse(output.replace(/^\uFEFF/, '').trim());
353
- } catch (error) {
354
- const detail = error.stderr?.toString().trim() || error.message || String(error);
355
- throw new Error(`Windows ACL ${action} failed (${payload.path || 'access verification'}, exit=${error.status ?? 'unknown'}): ${detail}`, { cause: error });
356
- }
357
- }
358
-
359
- function existingFile(file, io) {
360
- try {
361
- const stat = io.lstatSync(file);
362
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Expected a regular file: ${file}`);
363
- return stat;
364
- } catch (error) {
365
- if (error.code === 'ENOENT') return undefined;
366
- throw error;
367
- }
368
- }
369
-
370
- function makeReplaceable(file, io) {
371
- const stat = existingFile(file, io);
372
- // Windows' readonly attribute prevents replacement even for Administrators.
373
- // chmod affects that attribute, not the DACL. Restore it on the old inode.
374
- if (process.platform === 'win32' && stat && !(stat.mode & 0o200)) io.chmodSync(file, 0o600);
375
- }
376
-
377
- /** Keep the original inodes (including ACLs) until both replacements validate. */
378
- export function commitPreparedFiles(entries, verify, io = fs) {
379
- const records = [];
380
- try {
381
- for (const entry of entries) {
382
- const stat = existingFile(entry.file, io);
383
- const record = { ...entry, mode: stat?.mode, backup: undefined, installed: false };
384
- if (stat) {
385
- const backup = `${entry.file}.evolcore-backup-${randomUUID()}`;
386
- // A same-directory hard link retains the exact original security
387
- // descriptor. If unsupported, stop before replacing any live file.
388
- io.linkSync(entry.file, backup);
389
- record.backup = backup;
390
- }
391
- records.push(record);
392
- }
393
- for (const record of records) {
394
- makeReplaceable(record.file, io);
395
- io.renameSync(record.temporary, record.file);
396
- record.installed = true;
397
- if (record.backup) io.chmodSync(record.backup, record.mode);
398
- }
399
- verify();
400
- } catch (error) {
401
- const recoveryErrors = [];
402
- for (const record of records.toReversed()) {
403
- try {
404
- if (record.installed) {
405
- makeReplaceable(record.file, io);
406
- if (record.backup) io.renameSync(record.backup, record.file);
407
- else io.unlinkSync(record.file);
408
- }
409
- if (record.backup && io.existsSync(record.backup)) {
410
- makeReplaceable(record.backup, io);
411
- io.unlinkSync(record.backup);
412
- }
413
- if (record.mode !== undefined) io.chmodSync(record.file, record.mode);
414
- } catch (recoveryError) {
415
- recoveryErrors.push(`${record.file}: ${recoveryError.message}; original retained at ${record.backup || '(new installation)'}`);
416
- }
417
- }
418
- throw new Error(`${error.message}${recoveryErrors.length
419
- ? `; rollback incomplete: ${recoveryErrors.join(' | ')}`
420
- : '; previous files and permissions restored'}`, { cause: error });
421
- }
422
- const warnings = [];
423
- for (const record of records) {
424
- if (!record.backup) continue;
425
- try {
426
- makeReplaceable(record.backup, io);
427
- io.unlinkSync(record.backup);
428
- } catch (error) {
429
- warnings.push(`Installed successfully, but could not remove backup ${record.backup}: ${error.message}`);
430
- }
431
- }
432
- return warnings;
433
- }
434
-
435
- /** This transaction is used only by explicit provisioning, never npm upgrades. */
436
- export function provisionManagedFiles(options, acl = windowsAcl) {
437
- const { requirements, hookPath, sourceHook, nodePath, content, launcher } = options;
438
- const directory = path.dirname(hookPath);
439
- const configDirectory = path.dirname(requirements);
440
- acl('preflight');
441
- fs.mkdirSync(configDirectory, { recursive: true });
442
- const lockPath = path.join(configDirectory, '.evolcore-hooks.install.lock');
443
- let lock;
444
- try { lock = fs.openSync(lockPath, 'wx', 0o600); } catch (error) {
445
- throw new Error(`Cannot acquire installer lock ${lockPath}: ${error.message}. If an installer crashed, confirm it has stopped before removing the lock.`, { cause: error });
446
- }
447
- const staged = [];
448
- let committed = false;
449
- try {
450
- fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
451
- const existing = existingFile(requirements, fs);
452
- // Detect edits made after configuration generation, including a second
453
- // installer completing just before this process acquired the lock.
454
- if ((existing ? fs.readFileSync(requirements, 'utf8') : '') !== options.previousContent) {
455
- throw new Error(`Configuration changed while preparing installation: ${requirements}. Retry using the latest configuration.`);
456
- }
457
- if (fs.existsSync(directory)) {
458
- const stat = fs.lstatSync(directory);
459
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Expected a real hook directory: ${directory}`);
460
- } else {
461
- fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
462
- acl('prepare', { path: directory, directory: true });
463
- }
464
- // Existing directory ACLs are checked below, never rewritten: changing
465
- // inheritable ACEs could alter the live Hook before the transaction starts.
466
- for (const [file, value, reference] of [
467
- [hookPath, launcher, undefined],
468
- [requirements, content, existing ? requirements : undefined],
469
- ]) {
470
- const temporary = `${file}.evolcore-${randomUUID()}.tmp`;
471
- staged.push({ file, temporary, value });
472
- fs.writeFileSync(temporary, value, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
473
- acl('prepare', { path: temporary, reference });
474
- }
475
- const readable = [
476
- { path: configDirectory, execute: true },
477
- { path: sourceHook },
478
- { path: nodePath, execute: true },
479
- ];
480
- const verify = (temporary) => {
481
- for (const entry of staged) {
482
- const target = temporary ? entry.temporary : entry.file;
483
- if (fs.readFileSync(target, 'utf8') !== entry.value) throw new Error(`Installed content differs: ${target}`);
484
- }
485
- return acl('verify', { entries: [
486
- { path: directory, protected: true, execute: true },
487
- ...staged.map(entry => ({ path: temporary ? entry.temporary : entry.file, protected: true })),
488
- ...readable,
489
- ] });
490
- };
491
- verify(true);
492
- let accessReport;
493
- const warnings = commitPreparedFiles(staged, () => { accessReport = verify(false); });
494
- committed = true;
495
- if ([accessReport].flat().some(entry => entry?.userProbe === 'unavailable')) {
496
- warnings.push('ACLs verified, but this elevated account has no normal UAC linked token. Verify file reads and Hook execution from the intended non-elevated user before use.');
497
- }
498
- return warnings;
499
- } finally {
500
- for (const entry of staged) {
501
- try { fs.rmSync(entry.temporary, { force: true }); } catch (error) {
502
- process.stderr.write(`[evolcore] Could not clean staging file ${entry.temporary}: ${error.message}\n`);
503
- }
504
- }
505
- fs.closeSync(lock);
506
- try { fs.unlinkSync(lockPath); } catch (error) {
507
- process.stderr.write(`[evolcore] ${committed ? 'Installed; ' : ''}could not remove installer lock ${lockPath}: ${error.message}\n`);
508
- }
509
- }
510
- }
511
-
512
- function main() {
513
- // An explicit package root selects provisioning, even if the elevated
514
- // child inherited npm lifecycle variables. Ordinary postinstall skips it.
515
- if (!argument('--package-root') && (lifecycleEvent() === 'postinstall' || isGlobalInstall())) {
516
- runLinuxPostinstall();
517
- windowsPostinstallNotice();
518
- return;
519
- }
520
- if (process.platform === 'linux' && argument('--mountpoint')) {
521
- runLinuxPostinstall();
522
- return;
523
- }
524
- if (process.platform !== 'win32') fail('Codex managed hook provisioning is only supported on Windows.');
525
- if (!argument('--package-root')) fail('--package-root is required.');
526
- const packageRoot = path.resolve(argument('--package-root'));
527
- const nodePath = path.resolve(argument('--node-path') || process.execPath);
528
- const requirements = path.resolve(argument('--requirements')
529
- || path.join(process.env.ProgramData || path.join(os.homedir(), 'ProgramData'), 'OpenAI', 'Codex', 'requirements.toml'));
530
- const targetDirectory = path.resolve(argument('--managed-dir') || path.join(path.dirname(requirements), 'EvolCore', 'hooks'));
531
- const hookPath = path.join(targetDirectory, 'pre-tool-use.mjs');
532
- const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
533
- for (const file of [sourceHook, nodePath]) {
534
- if (!fs.statSync(file).isFile()) fail(`Required Hook runtime file was not found: ${file}`);
535
- }
536
- if (hasArgument('--repair')) {
537
- const result = repairManagedHookInstallation({ requirements, managedDir: targetDirectory, packageRoot, nodePath });
538
- process.stdout.write(`${JSON.stringify(result)}\n`);
539
- return;
540
- }
541
- const previousContent = fs.existsSync(requirements) ? fs.readFileSync(requirements, 'utf8') : '';
542
- const content = buildManagedRequirements(previousContent, { targetDirectory, nodePath, hookPath });
543
- const warnings = provisionManagedFiles({
544
- requirements, hookPath, sourceHook, nodePath, previousContent, content,
545
- launcher: managedHookLauncher(packageRoot),
546
- });
547
- for (const warning of warnings) process.stderr.write(`[evolcore] ${warning}\n`);
548
- process.stdout.write(`${JSON.stringify({ requirements, managedDir: targetDirectory, hookPath })}\n`);
549
- }
550
-
551
- if (process.argv[1] && pathToFileURL(fs.realpathSync(process.argv[1])).href === import.meta.url) {
552
- try { main(); } catch (error) {
553
- fail(error instanceof Error ? error.message : String(error));
554
- }
555
- }
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
+ import { isDeepStrictEqual } from 'node:util';
10
+ import { parse as parseToml } from 'smol-toml';
11
+
12
+ const markerStart = '# BEGIN EVOLCORE MANAGED CODEX HOOK';
13
+ const markerEnd = '# END EVOLCORE MANAGED CODEX HOOK';
14
+ const aclScript = fileURLToPath(new URL('./codex-managed-acl.ps1', import.meta.url));
15
+
16
+ function argument(name) {
17
+ const index = process.argv.indexOf(name);
18
+ return index >= 0 ? process.argv[index + 1] : undefined;
19
+ }
20
+
21
+ function hasArgument(name) {
22
+ return process.argv.includes(name);
23
+ }
24
+
25
+ function fail(message) {
26
+ process.stderr.write(`[evolcore] ${message}\n`);
27
+ process.exit(1);
28
+ }
29
+
30
+ function isGlobalInstall() {
31
+ return ['1', 'true'].includes(String(process.env.npm_config_global || '').toLowerCase());
32
+ }
33
+
34
+ function lifecycleEvent() {
35
+ const entry = Object.entries(process.env).find(([key]) => key.toLowerCase() === 'npm_lifecycle_event');
36
+ return String(entry?.[1] || '').toLowerCase();
37
+ }
38
+
39
+ function ensureRealDirectory(directory) {
40
+ let stat;
41
+ try {
42
+ stat = fs.lstatSync(directory);
43
+ } catch (error) {
44
+ if (error?.code !== 'ENOENT') {
45
+ fail(`could not inspect the Codex managed requirements mountpoint ${directory}: ${error?.message || String(error)}`);
46
+ }
47
+ }
48
+
49
+ if (stat) {
50
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
51
+ fail(`Codex managed requirements mountpoint is unsafe: ${directory} must be a real directory.`);
52
+ }
53
+ return;
54
+ }
55
+
56
+ try {
57
+ fs.mkdirSync(directory, { mode: 0o755 });
58
+ fs.chmodSync(directory, 0o755);
59
+ } catch (error) {
60
+ if (error?.code === 'EEXIST') {
61
+ const raced = fs.lstatSync(directory);
62
+ if (raced.isDirectory() && !raced.isSymbolicLink()) return;
63
+ }
64
+ fail(
65
+ `Linux global installation requires the real directory ${directory}, but it could not be created: `
66
+ + `${error?.message || String(error)}. `
67
+ + `Create it first with: sudo install -d -m 0755 ${directory}`,
68
+ );
69
+ }
70
+
71
+ const created = fs.lstatSync(directory);
72
+ if (!created.isDirectory() || created.isSymbolicLink()) {
73
+ fail(`Codex managed requirements mountpoint provisioning failed: ${directory} must be a real directory.`);
74
+ }
75
+ process.stdout.write(`[evolcore] Prepared Codex managed requirements mountpoint at ${directory}.\n`);
76
+ }
77
+
78
+ function runLinuxPostinstall() {
79
+ const explicitMountpoint = argument('--mountpoint');
80
+ if (process.platform !== 'linux') return;
81
+ // Local source installs do not launch the Linux Codex guard and must not
82
+ // mutate machine-wide configuration. An explicit path is accepted only for
83
+ // isolated lifecycle behavior tests.
84
+ if (!isGlobalInstall() && !explicitMountpoint) return;
85
+ ensureRealDirectory(explicitMountpoint || '/etc/codex');
86
+ }
87
+
88
+ function tomlString(value) {
89
+ return JSON.stringify(value);
90
+ }
91
+
92
+ function windowsCommandArg(value) {
93
+ // Keep filesystem separators intact; tomlString() performs the required
94
+ // TOML escaping after this Windows command-line quoting step.
95
+ return `"${value.replaceAll('"', '\\"')}"`;
96
+ }
97
+
98
+ function windowsPostinstallNotice() {
99
+ if (process.platform !== 'win32') return;
100
+ process.stderr.write(
101
+ '[evolcore] ec start/restart automatically checks and installs missing Codex managed hooks on Windows.\n'
102
+ + '[evolcore] Accept the Windows administrator (UAC) prompt when installation is needed; no separate setup command is required.\n',
103
+ );
104
+ }
105
+
106
+ function removeManagedBlock(source) {
107
+ const original = parseToml(source);
108
+ if (!source.includes(markerStart) && !source.includes(markerEnd)) return source;
109
+ const unsafe = () => new Error('Ambiguous EvolCore managed Hook markers in requirements.toml. Existing configuration was not modified.');
110
+ const expression = new RegExp(`^${markerStart}\\r?\\n[\\s\\S]*?^${markerEnd}(?:\\r?\\n|$)`, 'gm');
111
+ const matches = [...source.matchAll(expression)];
112
+ if (matches.length !== 1 || source.split(markerStart).length !== 2 || source.split(markerEnd).length !== 2) throw unsafe();
113
+ const block = parseToml(matches[0][0]);
114
+ const groups = block.hooks?.PreToolUse;
115
+ if (!Array.isArray(groups) || groups.length !== 1
116
+ || !isDeepStrictEqual(block, { hooks: { PreToolUse: groups } })) throw unsafe();
117
+ const content = source.replace(matches[0][0], '');
118
+ const retained = parseToml(content);
119
+ const originalGroups = original.hooks?.PreToolUse;
120
+ if (!Array.isArray(originalGroups)) throw unsafe();
121
+ // Markers inside a TOML string are not comments. Prove that removing the
122
+ // block removes only its Hook group, with every other policy unchanged.
123
+ const safe = originalGroups.some((group, index) => {
124
+ if (!isDeepStrictEqual(group, groups[0])) return false;
125
+ const expected = structuredClone(original);
126
+ expected.hooks.PreToolUse.splice(index, 1);
127
+ if (!expected.hooks.PreToolUse.length && !retained.hooks?.PreToolUse) delete expected.hooks.PreToolUse;
128
+ if (!Object.keys(expected.hooks).length && !retained.hooks) delete expected.hooks;
129
+ return isDeepStrictEqual(expected, retained);
130
+ });
131
+ if (!safe) throw unsafe();
132
+ return content;
133
+ }
134
+
135
+ function tableBounds(lines, table) {
136
+ const header = table ? `[${table}]` : null;
137
+ const start = header
138
+ ? lines.findIndex(line => line.trim() === header || line.trim().startsWith(`${header} #`))
139
+ : -1;
140
+ if (table && start < 0) return null;
141
+ const from = table ? start + 1 : 0;
142
+ let to = lines.length;
143
+ for (let index = from; index < lines.length; index += 1) {
144
+ if (/^\s*\[\[?[^\]]+\]\]?\s*(?:#.*)?$/.test(lines[index])) {
145
+ to = index;
146
+ break;
147
+ }
148
+ }
149
+ return { start, from, to };
150
+ }
151
+
152
+ function setTomlKey(source, table, key, value) {
153
+ const lines = source.split('\n');
154
+ let bounds = tableBounds(lines, table);
155
+ if (!bounds) {
156
+ if (table) {
157
+ if (lines.length && lines.at(-1) !== '') lines.push('');
158
+ lines.push(`[${table}]`, `${key} = ${value}`);
159
+ } else {
160
+ let insertAt = lines.findIndex(line => /^\s*\[/.test(line));
161
+ if (insertAt < 0) insertAt = lines.length;
162
+ lines.splice(insertAt, 0, `${key} = ${value}`);
163
+ }
164
+ return lines.join('\n');
165
+ }
166
+ const keyExpression = new RegExp(`^\\s*${key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}\\s*=`);
167
+ const existing = lines.slice(bounds.from, bounds.to).findIndex(line => keyExpression.test(line));
168
+ if (existing >= 0) {
169
+ lines[bounds.from + existing] = `${key} = ${value}`;
170
+ } else {
171
+ lines.splice(bounds.from, 0, `${key} = ${value}`);
172
+ }
173
+ return lines.join('\n');
174
+ }
175
+
176
+ export function managedHookLauncher(packageRoot) {
177
+ // Keep the machine-wide entrypoint stable across npm upgrades. Those
178
+ // upgrades replace the package contents at this stable global path, so
179
+ // this file never needs to be rewritten just because the hook changed.
180
+ const trustedPackageRoot = path.resolve(packageRoot);
181
+ return `#!/usr/bin/env node
182
+ import path from 'node:path';
183
+ import { pathToFileURL } from 'node:url';
184
+
185
+ // EVOLCORE_MANAGED_HOOK_LAUNCHER
186
+ const packageRoot = ${JSON.stringify(trustedPackageRoot)};
187
+
188
+ try {
189
+ await import(pathToFileURL(path.join(packageRoot, 'bin', 'codex-managed-hook.mjs')).href);
190
+ } catch (error) {
191
+ process.stderr.write('[evolcore] failed to load the current managed hook: '
192
+ + (error instanceof Error ? error.message : String(error)) + '\\n');
193
+ process.exit(2);
194
+ }
195
+ `;
196
+ }
197
+
198
+ export function buildManagedRequirements(source, { targetDirectory, nodePath, hookPath }) {
199
+ // Keep the existing text editor, but reject unsupported TOML layouts before
200
+ // writing anything. Parsing also catches duplicate tables/keys on reinstall.
201
+ let content = removeManagedBlock(source);
202
+ const before = parseToml(content);
203
+ content = setTomlKey(content, null, 'allow_managed_hooks_only', 'true');
204
+ content = setTomlKey(content, 'features', 'hooks', 'true');
205
+ content = setTomlKey(content, 'hooks', 'windows_managed_dir', tomlString(path.resolve(targetDirectory)));
206
+ if (!content.endsWith('\n')) content += '\n';
207
+ // Windows hook command must include %EVOLCORE_INSTANCE_SOCKET% so Codex
208
+ // expands it at runtime with the per-daemon socket path
209
+ const command = `${windowsCommandArg(nodePath)} ${windowsCommandArg(hookPath)} %EVOLCORE_INSTANCE_SOCKET%`;
210
+ content += [
211
+ markerStart,
212
+ '[[hooks.PreToolUse]]',
213
+ 'matcher = "*"',
214
+ '',
215
+ '[[hooks.PreToolUse.hooks]]',
216
+ 'type = "command"',
217
+ `command = ${tomlString(command)}`,
218
+ `command_windows = ${tomlString(command)}`,
219
+ // Intentionally omit timeout: Codex applies its documented 600-second
220
+ // default for synchronous PreToolUse hooks. The application pause gate
221
+ // itself has no timeout; Codex remains the outer infrastructure ceiling.
222
+ 'statusMessage = "Checking EvolCore session policy"',
223
+ markerEnd,
224
+ '',
225
+ ].join('\n');
226
+ const after = parseToml(content);
227
+ const expected = {
228
+ ...before,
229
+ allow_managed_hooks_only: true,
230
+ features: { ...before.features, hooks: true },
231
+ hooks: {
232
+ ...before.hooks,
233
+ windows_managed_dir: path.resolve(targetDirectory),
234
+ PreToolUse: [
235
+ ...(before.hooks?.PreToolUse || []),
236
+ { matcher: '*', hooks: [{ type: 'command', command, command_windows: command, statusMessage: 'Checking EvolCore session policy' }] },
237
+ ],
238
+ },
239
+ };
240
+ if (!isDeepStrictEqual(after, expected)) {
241
+ throw new Error('Could not safely update requirements.toml without changing unrelated policy. Existing configuration was not modified.');
242
+ }
243
+ return content;
244
+ }
245
+
246
+ function regularFile(file) {
247
+ try {
248
+ const stat = fs.lstatSync(file);
249
+ if (!stat.isFile() || stat.isSymbolicLink()) return { ok: false, unsafe: true };
250
+ return { ok: true };
251
+ } catch (error) {
252
+ if (error?.code === 'ENOENT') return { ok: false, unsafe: false };
253
+ return { ok: false, unsafe: true, error };
254
+ }
255
+ }
256
+
257
+ function sourceHasManagedMarker(source) {
258
+ return source.includes(markerStart) || source.includes(markerEnd);
259
+ }
260
+
261
+ /** Inspect only the canonical EvolCore managed-hook targets. */
262
+ export function inspectManagedHookInstallation({ requirements, managedDir, packageRoot }) {
263
+ const canonicalRequirements = path.resolve(requirements);
264
+ const canonicalManagedDir = path.resolve(managedDir);
265
+ const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
266
+ for (const directory of [path.dirname(canonicalRequirements), canonicalManagedDir]) {
267
+ try {
268
+ const stat = fs.lstatSync(directory);
269
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
270
+ return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `${directory} must be a real directory` };
271
+ }
272
+ } catch (error) {
273
+ if (error?.code !== 'ENOENT') return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: error?.message || String(error) };
274
+ }
275
+ }
276
+ const req = regularFile(canonicalRequirements);
277
+ const hook = regularFile(hookPath);
278
+ if (req.unsafe || hook.unsafe) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is not a regular file' };
279
+ if (!req.ok && hook.ok) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'canonical launcher exists but requirements.toml is missing' };
280
+ if (req.ok && !hook.ok) {
281
+ // A missing launcher can be repaired only when the requirements file is
282
+ // still an untouched user configuration. If it already contains any
283
+ // EvolCore-managed policy, treat the partial state as drift and fail
284
+ // closed instead of guessing which policy is authoritative.
285
+ try {
286
+ const source = fs.readFileSync(canonicalRequirements, 'utf8');
287
+ const partial = parseToml(source);
288
+ const managedPolicyPresent = sourceHasManagedMarker(source)
289
+ || partial.allow_managed_hooks_only !== undefined
290
+ || partial.hooks?.windows_managed_dir !== undefined
291
+ || partial.hooks?.managed_dir !== undefined;
292
+ if (managedPolicyPresent) {
293
+ return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements contains managed-hook policy but the canonical launcher is missing' };
294
+ }
295
+ } catch (error) {
296
+ return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` };
297
+ }
298
+ }
299
+ if (!req.ok || !hook.ok) return { status: 'missing', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is missing' };
300
+ let parsed;
301
+ try { parsed = parseToml(fs.readFileSync(canonicalRequirements, 'utf8')); }
302
+ catch (error) { return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` }; }
303
+ const configured = parsed.hooks?.windows_managed_dir ?? parsed.hooks?.managed_dir;
304
+ const normalized = value => path.normalize(String(value || '')).toLowerCase();
305
+ const launcher = fs.readFileSync(hookPath, 'utf8');
306
+ const packageMarker = launcher.includes('EVOLCORE_MANAGED_HOOK_LAUNCHER')
307
+ && launcher.toLowerCase().includes(JSON.stringify(path.resolve(packageRoot || process.cwd())).toLowerCase());
308
+ const preToolUse = parsed.hooks?.PreToolUse;
309
+ const canonicalCommand = value => {
310
+ if (typeof value !== 'string' || !value || /[\r\n;&|<>]/.test(value)) return false;
311
+ const withoutSocket = value.replace(/\s+%EVOLCORE_INSTANCE_SOCKET%\s*$/i, '').trim();
312
+ return withoutSocket.replace(/["']+$/, '').toLowerCase().endsWith(normalized(hookPath));
313
+ };
314
+ const loaded = Array.isArray(preToolUse) && preToolUse.some(group => group?.matcher === '*'
315
+ && Array.isArray(group.hooks) && group.hooks.some(handler => handler?.type === 'command'
316
+ && handler.async !== true && typeof handler.command === 'string'
317
+ && canonicalCommand(handler.command)
318
+ && canonicalCommand(handler.command_windows ?? handler.commandWindows)));
319
+ const valid = parsed.allow_managed_hooks_only === true
320
+ && parsed.features?.hooks === true
321
+ && normalized(configured) === normalized(canonicalManagedDir)
322
+ && packageMarker && loaded;
323
+ return valid
324
+ ? { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath }
325
+ : { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'managed-hook policy is missing, altered, or points outside the canonical target' };
326
+ }
327
+
328
+ /** Idempotently repair a missing canonical installation; unsafe edits fail closed. */
329
+ export function repairManagedHookInstallation(options, acl = windowsAcl) {
330
+ const { requirements, managedDir, packageRoot, nodePath = process.execPath } = options;
331
+ const canonicalRequirements = path.resolve(requirements);
332
+ const canonicalManagedDir = path.resolve(managedDir);
333
+ const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
334
+ const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
335
+ const state = inspectManagedHookInstallation({ requirements: canonicalRequirements, managedDir: canonicalManagedDir, packageRoot });
336
+ if (state.status === 'installed') return { ...state, repaired: false, warnings: [] };
337
+ if (state.status === 'unsafe') throw new Error(`Refusing automatic managed-hook repair: ${state.reason}`);
338
+ if (!fs.existsSync(sourceHook)) throw new Error(`Required Hook runtime file was not found: ${sourceHook}`);
339
+ const previousContent = fs.existsSync(canonicalRequirements) ? fs.readFileSync(canonicalRequirements, 'utf8') : '';
340
+ const content = buildManagedRequirements(previousContent, { targetDirectory: canonicalManagedDir, nodePath, hookPath });
341
+ const warnings = provisionManagedFiles({ requirements: canonicalRequirements, hookPath, sourceHook, nodePath, previousContent, content, launcher: managedHookLauncher(packageRoot) }, acl);
342
+ return { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, repaired: true, warnings };
343
+ }
344
+
345
+ export function windowsAcl(action, payload = {}, run = execFileSync) {
346
+ const executable = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
347
+ try {
348
+ const output = run(executable, [
349
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', aclScript,
350
+ '-Request', Buffer.from(JSON.stringify({ action, ...payload })).toString('base64'),
351
+ ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, timeout: 30_000 });
352
+ return JSON.parse(output.replace(/^\uFEFF/, '').trim());
353
+ } catch (error) {
354
+ const detail = error.stderr?.toString().trim() || error.message || String(error);
355
+ throw new Error(`Windows ACL ${action} failed (${payload.path || 'access verification'}, exit=${error.status ?? 'unknown'}): ${detail}`, { cause: error });
356
+ }
357
+ }
358
+
359
+ function existingFile(file, io) {
360
+ try {
361
+ const stat = io.lstatSync(file);
362
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Expected a regular file: ${file}`);
363
+ return stat;
364
+ } catch (error) {
365
+ if (error.code === 'ENOENT') return undefined;
366
+ throw error;
367
+ }
368
+ }
369
+
370
+ function makeReplaceable(file, io) {
371
+ const stat = existingFile(file, io);
372
+ // Windows' readonly attribute prevents replacement even for Administrators.
373
+ // chmod affects that attribute, not the DACL. Restore it on the old inode.
374
+ if (process.platform === 'win32' && stat && !(stat.mode & 0o200)) io.chmodSync(file, 0o600);
375
+ }
376
+
377
+ /** Keep the original inodes (including ACLs) until both replacements validate. */
378
+ export function commitPreparedFiles(entries, verify, io = fs) {
379
+ const records = [];
380
+ try {
381
+ for (const entry of entries) {
382
+ const stat = existingFile(entry.file, io);
383
+ const record = { ...entry, mode: stat?.mode, backup: undefined, installed: false };
384
+ if (stat) {
385
+ const backup = `${entry.file}.evolcore-backup-${randomUUID()}`;
386
+ // A same-directory hard link retains the exact original security
387
+ // descriptor. If unsupported, stop before replacing any live file.
388
+ io.linkSync(entry.file, backup);
389
+ record.backup = backup;
390
+ }
391
+ records.push(record);
392
+ }
393
+ for (const record of records) {
394
+ makeReplaceable(record.file, io);
395
+ io.renameSync(record.temporary, record.file);
396
+ record.installed = true;
397
+ if (record.backup) io.chmodSync(record.backup, record.mode);
398
+ }
399
+ verify();
400
+ } catch (error) {
401
+ const recoveryErrors = [];
402
+ for (const record of records.toReversed()) {
403
+ try {
404
+ if (record.installed) {
405
+ makeReplaceable(record.file, io);
406
+ if (record.backup) io.renameSync(record.backup, record.file);
407
+ else io.unlinkSync(record.file);
408
+ }
409
+ if (record.backup && io.existsSync(record.backup)) {
410
+ makeReplaceable(record.backup, io);
411
+ io.unlinkSync(record.backup);
412
+ }
413
+ if (record.mode !== undefined) io.chmodSync(record.file, record.mode);
414
+ } catch (recoveryError) {
415
+ recoveryErrors.push(`${record.file}: ${recoveryError.message}; original retained at ${record.backup || '(new installation)'}`);
416
+ }
417
+ }
418
+ throw new Error(`${error.message}${recoveryErrors.length
419
+ ? `; rollback incomplete: ${recoveryErrors.join(' | ')}`
420
+ : '; previous files and permissions restored'}`, { cause: error });
421
+ }
422
+ const warnings = [];
423
+ for (const record of records) {
424
+ if (!record.backup) continue;
425
+ try {
426
+ makeReplaceable(record.backup, io);
427
+ io.unlinkSync(record.backup);
428
+ } catch (error) {
429
+ warnings.push(`Installed successfully, but could not remove backup ${record.backup}: ${error.message}`);
430
+ }
431
+ }
432
+ return warnings;
433
+ }
434
+
435
+ /** This transaction is used only by explicit provisioning, never npm upgrades. */
436
+ export function provisionManagedFiles(options, acl = windowsAcl) {
437
+ const { requirements, hookPath, sourceHook, nodePath, content, launcher } = options;
438
+ const directory = path.dirname(hookPath);
439
+ const configDirectory = path.dirname(requirements);
440
+ acl('preflight');
441
+ fs.mkdirSync(configDirectory, { recursive: true });
442
+ const lockPath = path.join(configDirectory, '.evolcore-hooks.install.lock');
443
+ let lock;
444
+ try { lock = fs.openSync(lockPath, 'wx', 0o600); } catch (error) {
445
+ throw new Error(`Cannot acquire installer lock ${lockPath}: ${error.message}. If an installer crashed, confirm it has stopped before removing the lock.`, { cause: error });
446
+ }
447
+ const staged = [];
448
+ let committed = false;
449
+ try {
450
+ fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
451
+ const existing = existingFile(requirements, fs);
452
+ // Detect edits made after configuration generation, including a second
453
+ // installer completing just before this process acquired the lock.
454
+ if ((existing ? fs.readFileSync(requirements, 'utf8') : '') !== options.previousContent) {
455
+ throw new Error(`Configuration changed while preparing installation: ${requirements}. Retry using the latest configuration.`);
456
+ }
457
+ if (fs.existsSync(directory)) {
458
+ const stat = fs.lstatSync(directory);
459
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Expected a real hook directory: ${directory}`);
460
+ } else {
461
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
462
+ acl('prepare', { path: directory, directory: true });
463
+ }
464
+ // Existing directory ACLs are checked below, never rewritten: changing
465
+ // inheritable ACEs could alter the live Hook before the transaction starts.
466
+ for (const [file, value, reference] of [
467
+ [hookPath, launcher, undefined],
468
+ [requirements, content, existing ? requirements : undefined],
469
+ ]) {
470
+ const temporary = `${file}.evolcore-${randomUUID()}.tmp`;
471
+ staged.push({ file, temporary, value });
472
+ fs.writeFileSync(temporary, value, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
473
+ acl('prepare', { path: temporary, reference });
474
+ }
475
+ const readable = [
476
+ { path: configDirectory, execute: true },
477
+ { path: sourceHook },
478
+ { path: nodePath, execute: true },
479
+ ];
480
+ const verify = (temporary) => {
481
+ for (const entry of staged) {
482
+ const target = temporary ? entry.temporary : entry.file;
483
+ if (fs.readFileSync(target, 'utf8') !== entry.value) throw new Error(`Installed content differs: ${target}`);
484
+ }
485
+ return acl('verify', { entries: [
486
+ { path: directory, protected: true, execute: true },
487
+ ...staged.map(entry => ({ path: temporary ? entry.temporary : entry.file, protected: true })),
488
+ ...readable,
489
+ ] });
490
+ };
491
+ verify(true);
492
+ let accessReport;
493
+ const warnings = commitPreparedFiles(staged, () => { accessReport = verify(false); });
494
+ committed = true;
495
+ if ([accessReport].flat().some(entry => entry?.userProbe === 'unavailable')) {
496
+ warnings.push('ACLs verified, but this elevated account has no normal UAC linked token. Verify file reads and Hook execution from the intended non-elevated user before use.');
497
+ }
498
+ return warnings;
499
+ } finally {
500
+ for (const entry of staged) {
501
+ try { fs.rmSync(entry.temporary, { force: true }); } catch (error) {
502
+ process.stderr.write(`[evolcore] Could not clean staging file ${entry.temporary}: ${error.message}\n`);
503
+ }
504
+ }
505
+ fs.closeSync(lock);
506
+ try { fs.unlinkSync(lockPath); } catch (error) {
507
+ process.stderr.write(`[evolcore] ${committed ? 'Installed; ' : ''}could not remove installer lock ${lockPath}: ${error.message}\n`);
508
+ }
509
+ }
510
+ }
511
+
512
+ function main() {
513
+ // An explicit package root selects provisioning, even if the elevated
514
+ // child inherited npm lifecycle variables. Ordinary postinstall skips it.
515
+ if (!argument('--package-root') && (lifecycleEvent() === 'postinstall' || isGlobalInstall())) {
516
+ runLinuxPostinstall();
517
+ windowsPostinstallNotice();
518
+ return;
519
+ }
520
+ if (process.platform === 'linux' && argument('--mountpoint')) {
521
+ runLinuxPostinstall();
522
+ return;
523
+ }
524
+ if (process.platform !== 'win32') fail('Codex managed hook provisioning is only supported on Windows.');
525
+ if (!argument('--package-root')) fail('--package-root is required.');
526
+ const packageRoot = path.resolve(argument('--package-root'));
527
+ const nodePath = path.resolve(argument('--node-path') || process.execPath);
528
+ const requirements = path.resolve(argument('--requirements')
529
+ || path.join(process.env.ProgramData || path.join(os.homedir(), 'ProgramData'), 'OpenAI', 'Codex', 'requirements.toml'));
530
+ const targetDirectory = path.resolve(argument('--managed-dir') || path.join(path.dirname(requirements), 'EvolCore', 'hooks'));
531
+ const hookPath = path.join(targetDirectory, 'pre-tool-use.mjs');
532
+ const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
533
+ for (const file of [sourceHook, nodePath]) {
534
+ if (!fs.statSync(file).isFile()) fail(`Required Hook runtime file was not found: ${file}`);
535
+ }
536
+ if (hasArgument('--repair')) {
537
+ const result = repairManagedHookInstallation({ requirements, managedDir: targetDirectory, packageRoot, nodePath });
538
+ process.stdout.write(`${JSON.stringify(result)}\n`);
539
+ return;
540
+ }
541
+ const previousContent = fs.existsSync(requirements) ? fs.readFileSync(requirements, 'utf8') : '';
542
+ const content = buildManagedRequirements(previousContent, { targetDirectory, nodePath, hookPath });
543
+ const warnings = provisionManagedFiles({
544
+ requirements, hookPath, sourceHook, nodePath, previousContent, content,
545
+ launcher: managedHookLauncher(packageRoot),
546
+ });
547
+ for (const warning of warnings) process.stderr.write(`[evolcore] ${warning}\n`);
548
+ process.stdout.write(`${JSON.stringify({ requirements, managedDir: targetDirectory, hookPath })}\n`);
549
+ }
550
+
551
+ if (process.argv[1] && pathToFileURL(fs.realpathSync(process.argv[1])).href === import.meta.url) {
552
+ try { main(); } catch (error) {
553
+ fail(error instanceof Error ? error.message : String(error));
554
+ }
555
+ }