@dailephd/my-centcom 0.2.0 → 0.3.0

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 (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,738 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync, spawn } from 'node:child_process';
3
+ import { createHash, generateKeyPairSync, randomBytes } from 'node:crypto';
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { request } from 'node:http';
6
+ import { dirname, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { NATIVE_HOST_NAME, NativeResponseV1Schema, newCorrelationId, redactText } from '../../../../packages/contracts/dist/index.js';
9
+ import { startSecureDaemon } from './secureMain.js';
10
+ import { assertOrInitializePrivateDataRoot } from './privateDataRoot.js';
11
+ import { CHROME_NATIVE_HOSTS_KEY, HOST_VERSION, HostConfigV1Schema, builtExtensionId, configMac, daemonTreeDigest, extensionIdFromPublicKeyDer, extensionSourceId, extensionTreeDigest, hostLauncherCmd, hostManifestJson, installPaths, macMatches, sha256File, } from './installLayout.js';
12
+ import { windowsDpapi } from '../storage/protectedSecrets.js';
13
+ import { findGit } from '../runtime/provisionedExecution.js';
14
+ import { stageAgentBuild, StagingError } from '../runtime/trustedAgentStaging.js';
15
+ import { CaBundleError, stageCaBundle } from '../runtime/trustedCaBundle.js';
16
+ import { DatabaseSync } from 'node:sqlite';
17
+ import { LEDGER_SCHEMA_VERSION, SqliteLedger } from '../storage/sqliteLedger.js';
18
+ import { ExecutionTelemetry } from '../storage/executionTelemetry.js';
19
+ import { SECURE_DB_FILE_NAME } from './secureMain.js';
20
+ const REG = () => join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'reg.exe');
21
+ const ICACLS = () => join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'icacls.exe');
22
+ export const windowsRegistry = {
23
+ query(key) {
24
+ try {
25
+ const out = execFileSync(REG(), ['query', key, '/ve'], { windowsHide: true, shell: false, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
26
+ const m = /REG_SZ\s+(.+)\s*$/m.exec(out);
27
+ return m ? m[1].trim() : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ },
33
+ set(key, value) { execFileSync(REG(), ['add', key, '/ve', '/t', 'REG_SZ', '/d', value, '/f'], { windowsHide: true, shell: false, stdio: 'ignore' }); },
34
+ remove(key) { try {
35
+ execFileSync(REG(), ['delete', key, '/f'], { windowsHide: true, shell: false, stdio: 'ignore' });
36
+ }
37
+ catch { /* absent */ } },
38
+ };
39
+ export const productionSetupDeps = () => ({ dpapi: windowsDpapi, registry: windowsRegistry, out: (l) => process.stdout.write(`${l}\n`), now: Date.now });
40
+ export class SetupError extends Error {
41
+ code;
42
+ action;
43
+ constructor(code, action) {
44
+ super(code);
45
+ this.code = code;
46
+ this.action = action;
47
+ this.name = 'SetupError';
48
+ }
49
+ }
50
+ const HOST_KEY = `${CHROME_NATIVE_HOSTS_KEY}\\${NATIVE_HOST_NAME}`;
51
+ const BENIGN_PLUGIN = 'plugin.benign-smoke';
52
+ const BENIGN_OPERATION = 'op.echo';
53
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
54
+ const iso = (ms) => new Date(ms).toISOString();
55
+ export function projectRootFromHere() {
56
+ return realpathSync.native(resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..'));
57
+ }
58
+ function grantRestrictedRead(dir) {
59
+ // S-1-5-12 = RESTRICTED: the restricted execution identity needs read access to the project it runs in and to the pinned benign script. Project-local only.
60
+ execFileSync(ICACLS(), [dir, '/grant', '*S-1-5-12:(OI)(CI)(RX)'], { windowsHide: true, shell: false, stdio: 'ignore' });
61
+ }
62
+ /** A disposable Git project for the benign smoke operation, inside the project's runtime data (never the user's real repositories). */
63
+ export function createScratchProject(dir, opts = {}) {
64
+ mkdirSync(dir, { recursive: true });
65
+ const git = findGit();
66
+ const g = (...a) => execFileSync(git, a, { cwd: dir, windowsHide: true, shell: false, stdio: 'ignore' });
67
+ if (!existsSync(join(dir, '.git'))) {
68
+ g('init', '-q');
69
+ writeFileSync(join(dir, 'README.txt'), 'my-centcom disposable project for the benign read-only smoke operation. Contains no secrets.\n');
70
+ g('add', 'README.txt');
71
+ g('-c', 'user.name=my-centcom-setup', '-c', 'user.email=setup@my-centcom.invalid', '-c', 'commit.gpgsign=false', 'commit', '-q', '-m', 'disposable project');
72
+ }
73
+ // SW-077: fixtures that must prove the run-scoped view boundary create the project WITHOUT the restricted read grant (default unchanged: existing operators keep their behaviour).
74
+ if (opts.grantRestrictedRead !== false)
75
+ grantRestrictedRead(dir);
76
+ return realpathSync.native(dir);
77
+ }
78
+ export function stageBenignScript(root, targetDir) {
79
+ mkdirSync(targetDir, { recursive: true });
80
+ const src = join(root, 'apps', 'daemon', 'src', 'runtime', 'benign', 'referenceEcho.mjs');
81
+ const dst = join(targetDir, 'referenceEcho.mjs');
82
+ copyFileSync(src, dst);
83
+ grantRestrictedRead(targetDir);
84
+ return realpathSync.native(dst);
85
+ }
86
+ function requireBuilt(p) {
87
+ for (const f of [p.daemonEntry, p.nativeHostEntry, join(p.projectRoot, 'packages', 'contracts', 'dist', 'index.js')]) {
88
+ if (!existsSync(f))
89
+ throw new SetupError('BUILD_MISSING', 'Run `npm run build` first.');
90
+ }
91
+ }
92
+ /** The extension key pair is generated once per installation; only the PUBLIC key is kept (an unpacked extension needs no private key). */
93
+ function loadOrCreateExtensionKey(p) {
94
+ const f = join(p.installDir, 'extension-key.json');
95
+ if (existsSync(f)) {
96
+ const k = JSON.parse(readFileSync(f, 'utf8'));
97
+ if (extensionIdFromPublicKeyDer(Buffer.from(k.publicKeyB64, 'base64')) !== k.extensionId)
98
+ throw new SetupError('EXTENSION_KEY_INVALID', 'Remove the install directory and run install again.');
99
+ return k;
100
+ }
101
+ const { publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
102
+ const der = publicKey.export({ type: 'spki', format: 'der' });
103
+ const k = { publicKeyB64: der.toString('base64'), extensionId: extensionIdFromPublicKeyDer(der) };
104
+ writeFileSync(f, JSON.stringify(k, null, 2), { flag: 'wx' });
105
+ return k;
106
+ }
107
+ function buildInstalledExtension(p, publicKeyB64, outDir) {
108
+ // outDir (API only, tests): a directory under .switchyard-dev/cache so a test never replaces the user's installed extension
109
+ const target = outDir ? ['--secure', `--out-dir=${outDir}`, `--manifest-key=${publicKeyB64}`] : ['--secure', `--manifest-key=${publicKeyB64}`, '--install'];
110
+ execFileSync(process.execPath, [join(p.projectRoot, 'apps', 'extension', 'scripts', 'build.mjs'), ...target], { windowsHide: true, shell: false, stdio: 'ignore' });
111
+ return extensionTreeDigest(outDir ?? p.extensionDir);
112
+ }
113
+ function readHostConfig(p) {
114
+ if (!existsSync(p.hostConfig))
115
+ return undefined;
116
+ const c = HostConfigV1Schema.safeParse(JSON.parse(readFileSync(p.hostConfig, 'utf8')));
117
+ if (!c.success)
118
+ throw new SetupError('HOST_CONFIG_INVALID', 'Run uninstall, then install again.');
119
+ return c.data;
120
+ }
121
+ export function writeHostFiles(p, cfg, secret) {
122
+ mkdirSync(p.installDir, { recursive: true });
123
+ mkdirSync(p.nativeHostDir, { recursive: true });
124
+ const full = { ...cfg, configMac: configMac(secret, cfg) };
125
+ writeFileSync(p.hostConfig, `${JSON.stringify(full, null, 2)}\n`);
126
+ writeFileSync(p.hostLauncher, hostLauncherCmd(cfg.nodeExe, p.nativeHostEntry, p.hostConfig));
127
+ writeFileSync(p.hostManifest, hostManifestJson(NATIVE_HOST_NAME, p.hostLauncher, cfg.extensionId));
128
+ return full;
129
+ }
130
+ function runtimeRecord(dataRoot) {
131
+ try {
132
+ const r = JSON.parse(readFileSync(join(dataRoot, 'run', 'daemon.json'), 'utf8'));
133
+ process.kill(r.pid, 0);
134
+ return r;
135
+ }
136
+ catch {
137
+ return undefined;
138
+ }
139
+ }
140
+ /** install and update share this path; `update` requires an existing installation and never creates a new one. */
141
+ export async function install(root, o, deps, mode = 'install') {
142
+ const p = installPaths(root, o.dataRoot);
143
+ requireBuilt(p);
144
+ if (runtimeRecord(p.dataRoot))
145
+ throw new SetupError('DAEMON_RUNNING', 'Stop it first: npm run centcom -- stop');
146
+ const existing = readHostConfig(p);
147
+ if (mode === 'update' && !existing)
148
+ throw new SetupError('NOT_INSTALLED', 'Run npm run centcom -- install first.');
149
+ mkdirSync(join(root, '.switchyard-data'), { recursive: true });
150
+ assertOrInitializePrivateDataRoot({ projectRoot: root, dataRoot: p.dataRoot });
151
+ mkdirSync(p.installDir, { recursive: true });
152
+ const devSmoke = o.devSmokeBenign === true || existing?.devSmokeProfiles === true;
153
+ let approved = existing?.approvedProject ?? null;
154
+ if (o.createScratchProject)
155
+ approved = { projectId: o.projectId ?? 'project.scratch', root: createScratchProject(join(root, '.switchyard-data', 'scratch-project')) };
156
+ else if (o.approvedProjectRoot)
157
+ approved = { projectId: o.projectId ?? 'project.primary', root: realpathSync.native(o.approvedProjectRoot) };
158
+ if (mode === 'install' && !approved)
159
+ throw new SetupError('APPROVED_PROJECT_REQUIRED', 'Pass --approved-project-root <git repo> or --create-scratch-project.');
160
+ const key = loadOrCreateExtensionKey(p);
161
+ const origin = `chrome-extension://${key.extensionId}`;
162
+ const extDigest = buildInstalledExtension(p, key.publicKeyB64, o.extensionOutDir);
163
+ deps.out(`EXTENSION built at ${o.extensionOutDir ?? p.extensionDir} id=${key.extensionId} files-sha256=${extDigest.slice(0, 16)}...`);
164
+ let daemon;
165
+ let installationId;
166
+ let secret;
167
+ try {
168
+ daemon = await startSecureDaemon({ projectRoot: root, dataRoot: p.dataRoot, ...(approved ? { approvedProject: approved } : {}), devSmokeProfiles: devSmoke, port: 0, dpapi: deps.dpapi });
169
+ if (existing) {
170
+ secret = deps.dpapi.unprotect(Buffer.from(existing.protectedSecretB64, 'base64')).toString('utf8');
171
+ if (!macMatches(secret, existing))
172
+ throw new SetupError('HOST_CONFIG_TAMPERED', 'Investigate the install directory; run uninstall then install.');
173
+ const inst = daemon.ledger.getInstallation(existing.installationId);
174
+ if (!inst || inst.revokedAt !== null || inst.extensionOrigin !== origin)
175
+ throw new SetupError('INSTALLATION_MISMATCH', 'Run uninstall, then install again.');
176
+ installationId = existing.installationId;
177
+ deps.out(`INSTALLATION kept ${installationId} (grants unchanged)`);
178
+ }
179
+ else {
180
+ const created = daemon.authority.createInstallation(origin);
181
+ installationId = created.installationId;
182
+ secret = created.secret;
183
+ deps.out(`INSTALLATION created ${installationId}`);
184
+ }
185
+ const inst = daemon.ledger.getInstallation(installationId);
186
+ const ops = [...o.operations];
187
+ if (o.devSmokeBenign) {
188
+ const script = stageBenignScript(root, join(root, '.switchyard-data', 'benign'));
189
+ try {
190
+ await daemon.provisionedActions?.provisionOperation({ pluginId: BENIGN_PLUGIN, operationId: BENIGN_OPERATION, profileId: 'reference-script-stdin', executablePath: realpathSync.native(process.execPath), codeInputPath: script });
191
+ deps.out(`PROVISIONED benign smoke ${BENIGN_PLUGIN}/${BENIGN_OPERATION} (dev-smoke reference script; no model, no network)`);
192
+ }
193
+ catch (e) {
194
+ if (!/ALREADY_PROVISIONED/.test(String(e.message)))
195
+ throw e;
196
+ deps.out(`PROVISIONED benign smoke already present`);
197
+ }
198
+ ops.push({ pluginId: BENIGN_PLUGIN, operationId: BENIGN_OPERATION });
199
+ }
200
+ if (approved) {
201
+ const expires = new Date(deps.now() + (o.grantDays ?? 30) * 86_400_000);
202
+ for (const op of ops) {
203
+ try {
204
+ daemon.authority.grantOperation(inst.principalId, approved.projectId, op.pluginId, op.operationId, 'read', expires, true, 'RUN_CLICK');
205
+ deps.out(`GRANT ${approved.projectId} ${op.pluginId}/${op.operationId} effect=read consent=RUN_CLICK expires=${expires.toISOString()}`);
206
+ }
207
+ catch (e) {
208
+ throw new SetupError('GRANT_REFUSED', `The operation ${op.pluginId}/${op.operationId} is not a verified read operation (${String(e.message).slice(0, 60)}).`);
209
+ }
210
+ }
211
+ }
212
+ }
213
+ finally {
214
+ await daemon?.close();
215
+ }
216
+ const now = iso(deps.now());
217
+ const cfg = {
218
+ schemaVersion: 1, hostVersion: HOST_VERSION, installationId, extensionId: key.extensionId, extensionOrigin: origin, projectRoot: root, dataRoot: p.dataRoot,
219
+ nodeExe: realpathSync.native(process.execPath), nodeSha256: sha256File(realpathSync.native(process.execPath)), daemonEntry: p.daemonEntry, daemonTreeSha256: daemonTreeDigest(root),
220
+ approvedProject: approved, devSmokeProfiles: devSmoke, protectedSecretB64: deps.dpapi.protect(Buffer.from(secret, 'utf8')).toString('base64'),
221
+ createdAt: existing?.createdAt ?? now, updatedAt: now,
222
+ };
223
+ writeHostFiles(p, cfg, secret);
224
+ deps.out(`NATIVE HOST manifest ${p.hostManifest} allowed_origins=[${origin}/]`);
225
+ let registered = false;
226
+ if (o.registerNativeHost && o.consent) {
227
+ deps.registry.set(HOST_KEY, p.hostManifest);
228
+ registered = deps.registry.query(HOST_KEY) === p.hostManifest;
229
+ deps.out(`REGISTRY ${registered ? 'SET' : 'FAILED'} ${HOST_KEY}`);
230
+ }
231
+ else {
232
+ deps.out(`REGISTRY NOT_CHANGED (needs --register-native-host --consent). It would run: reg add "${HOST_KEY}" /ve /t REG_SZ /d "${p.hostManifest}" /f`);
233
+ }
234
+ return { extensionId: key.extensionId, installationId, extensionDir: o.extensionOutDir ?? p.extensionDir, registered };
235
+ }
236
+ export async function uninstall(root, o, deps) {
237
+ const p = installPaths(root, o.dataRoot);
238
+ if (runtimeRecord(p.dataRoot))
239
+ throw new SetupError('DAEMON_RUNNING', 'Stop it first: npm run centcom -- stop');
240
+ const cfg = readHostConfig(p);
241
+ if (cfg) {
242
+ const d = await startSecureDaemon({ projectRoot: root, dataRoot: p.dataRoot, port: 0, dpapi: deps.dpapi, devSmokeProfiles: cfg.devSmokeProfiles });
243
+ try {
244
+ deps.out(`INSTALLATION ${d.authority.revokeInstallation(cfg.installationId) ? 'REVOKED' : 'ALREADY_REVOKED'} ${cfg.installationId}`);
245
+ }
246
+ finally {
247
+ await d.close();
248
+ }
249
+ }
250
+ for (const f of [p.hostConfig, p.hostManifest, p.hostLauncher])
251
+ rmSync(f, { force: true });
252
+ deps.out('HOST FILES removed (the ledger, logs and the extension key are kept as user data)');
253
+ if (o.consent) {
254
+ deps.registry.remove(HOST_KEY);
255
+ deps.out(`REGISTRY ${deps.registry.query(HOST_KEY) === undefined ? 'REMOVED' : 'STILL_PRESENT'} ${HOST_KEY}`);
256
+ }
257
+ else
258
+ deps.out(`REGISTRY NOT_CHANGED (needs --consent). It would run: reg delete "${HOST_KEY}" /f`);
259
+ }
260
+ export function status(root, deps, dataRoot) {
261
+ const p = installPaths(root, dataRoot);
262
+ const s = {};
263
+ let cfg;
264
+ try {
265
+ cfg = readHostConfig(p);
266
+ }
267
+ catch (e) {
268
+ s.hostConfig = e.code;
269
+ }
270
+ s.installed = cfg ? 'YES' : 'NO';
271
+ if (cfg) {
272
+ s.installationId = cfg.installationId;
273
+ s.extensionId = cfg.extensionId;
274
+ s.hostVersion = cfg.hostVersion;
275
+ s.devSmokeProfiles = String(cfg.devSmokeProfiles);
276
+ s.approvedProject = cfg.approvedProject ? cfg.approvedProject.projectId : 'NONE';
277
+ s.daemonPinned = daemonTreeDigest(root) === cfg.daemonTreeSha256 ? 'MATCH' : 'CHANGED_RUN_UPDATE';
278
+ s.nodePinned = existsSync(cfg.nodeExe) && sha256File(cfg.nodeExe) === cfg.nodeSha256 ? 'MATCH' : 'CHANGED';
279
+ }
280
+ const reg = deps.registry.query(HOST_KEY);
281
+ s.registry = reg === undefined ? 'NOT_REGISTERED' : reg === p.hostManifest ? 'REGISTERED' : 'REGISTERED_ELSEWHERE';
282
+ s.hostManifest = existsSync(p.hostManifest) ? 'PRESENT' : 'ABSENT';
283
+ // SW-065: PRESENT alone let a stale build pass for the current one. CURRENT = the installed files were built from this source tree; Chrome still runs
284
+ // what it last LOADED, so after `update` the extension must be reloaded in chrome://extensions (the panel shows the build it is running).
285
+ const mf = join(p.extensionDir, 'manifest.json');
286
+ if (!existsSync(mf))
287
+ s.extensionBuild = 'ABSENT';
288
+ else {
289
+ const built = builtExtensionId(readFileSync(mf, 'utf8'));
290
+ s.extensionBuild = built === extensionSourceId(root) ? `CURRENT build=${built}` : `STALE_RUN_UPDATE installed=${built ?? 'UNSTAMPED'} source=${extensionSourceId(root)}`;
291
+ }
292
+ const rt = runtimeRecord(p.dataRoot);
293
+ s.daemon = rt ? `RUNNING port=${rt.port}` : 'NOT_RUNNING';
294
+ return s;
295
+ }
296
+ export function stop(root, deps, dataRoot) {
297
+ const rt = runtimeRecord(installPaths(root, dataRoot).dataRoot);
298
+ if (!rt) {
299
+ deps.out('DAEMON NOT_RUNNING');
300
+ return false;
301
+ }
302
+ try {
303
+ process.kill(rt.pid);
304
+ }
305
+ catch { /* gone */ }
306
+ deps.out(`DAEMON STOPPED pid=${rt.pid}`);
307
+ return true;
308
+ }
309
+ function httpJson(port, path, body, headers = {}, timeoutMs = 30000) {
310
+ return new Promise((resolveP, reject) => {
311
+ const data = Buffer.from(JSON.stringify(body));
312
+ const req = request({ host: '127.0.0.1', port, path, method: 'POST', headers: { 'content-type': 'application/json', 'content-length': data.length, ...headers }, timeout: timeoutMs }, (res) => {
313
+ const c = [];
314
+ res.on('data', (d) => c.push(d));
315
+ res.on('end', () => { try {
316
+ resolveP({ status: res.statusCode ?? 0, json: JSON.parse(Buffer.concat(c).toString('utf8')) });
317
+ }
318
+ catch (e) {
319
+ reject(e);
320
+ } });
321
+ });
322
+ req.on('timeout', () => req.destroy(new Error('TIMEOUT')));
323
+ req.on('error', reject);
324
+ req.end(data);
325
+ });
326
+ }
327
+ /** Runs the REAL native host process exactly as Chrome does: launcher arguments + the caller origin, one framed message on stdin, one framed reply. */
328
+ export function callNativeHost(hostEntry, configPath, callerOrigin, message, timeoutMs = 60000) {
329
+ return new Promise((resolveP, reject) => {
330
+ const child = spawn(process.execPath, [hostEntry, '--config', configPath, `${callerOrigin}/`, '--parent-window=0'], { windowsHide: true, shell: false, stdio: ['pipe', 'pipe', 'ignore'] });
331
+ let buf = Buffer.alloc(0);
332
+ const t = setTimeout(() => { child.kill(); reject(new Error('HOST_TIMEOUT')); }, timeoutMs);
333
+ child.stdout.on('data', (d) => {
334
+ buf = Buffer.concat([buf, d]);
335
+ if (buf.length >= 4 && buf.length >= 4 + buf.readUInt32LE(0)) {
336
+ clearTimeout(t);
337
+ try {
338
+ resolveP(JSON.parse(buf.subarray(4, 4 + buf.readUInt32LE(0)).toString('utf8')));
339
+ }
340
+ catch (e) {
341
+ reject(e);
342
+ }
343
+ }
344
+ });
345
+ child.on('error', (e) => { clearTimeout(t); reject(e); });
346
+ const body = Buffer.from(JSON.stringify(message));
347
+ const h = Buffer.alloc(4);
348
+ h.writeUInt32LE(body.length, 0);
349
+ child.stdin.end(Buffer.concat([h, body]));
350
+ });
351
+ }
352
+ export async function selftest(root, deps, o = {}) {
353
+ const corr = newCorrelationId();
354
+ const stages = [];
355
+ const stage = async (name, fn) => {
356
+ const t0 = Date.now();
357
+ let r;
358
+ try {
359
+ r = await fn();
360
+ }
361
+ catch (e) {
362
+ r = ['FAIL', e instanceof SetupError ? e.code : e?.name === 'SetupError' ? String(e.message) : `ERROR ${redactText(String(e?.message ?? e)).slice(0, 120)}`];
363
+ }
364
+ stages.push({ stage: name, status: r[0], detail: r[1], ms: Date.now() - t0 });
365
+ deps.out(`SELFTEST ${name} ${r[0]} ${r[1]}`);
366
+ return r[0] !== 'FAIL';
367
+ };
368
+ const p = installPaths(root, o.dataRoot);
369
+ // ---- Part 1: the real installation (read-only checks) ----
370
+ let cfg;
371
+ await stage('INSTALL_RECORD', () => {
372
+ cfg = readHostConfig(p);
373
+ if (!cfg)
374
+ return ['INFO', 'NOT_INSTALLED (run install; the isolated checks below still run)'];
375
+ const secret = deps.dpapi.unprotect(Buffer.from(cfg.protectedSecretB64, 'base64')).toString('utf8');
376
+ return macMatches(secret, cfg) ? ['PASS', `installation=${cfg.installationId} extension=${cfg.extensionId}`] : ['FAIL', 'HOST_CONFIG_TAMPERED'];
377
+ });
378
+ if (cfg) {
379
+ const c = cfg;
380
+ await stage('HOST_MANIFEST', () => {
381
+ const m = JSON.parse(readFileSync(p.hostManifest, 'utf8'));
382
+ const ok = m.name === NATIVE_HOST_NAME && m.type === 'stdio' && m.path === p.hostLauncher && m.allowed_origins.length === 1 && m.allowed_origins[0] === `${c.extensionOrigin}/`;
383
+ const launcherOk = readFileSync(p.hostLauncher, 'utf8') === hostLauncherCmd(c.nodeExe, p.nativeHostEntry, p.hostConfig);
384
+ return ok && launcherOk ? ['PASS', 'exactly one allowed origin; launcher pinned'] : ['FAIL', `HOST_FILES_MISMATCH manifest=${ok} launcher=${launcherOk}`];
385
+ });
386
+ await stage('REGISTRY', () => {
387
+ const v = deps.registry.query(HOST_KEY);
388
+ return v === p.hostManifest ? ['PASS', 'HKCU value points at the pinned manifest'] : v === undefined ? ['INFO', 'NOT_REGISTERED (install --register-native-host --consent)'] : ['FAIL', 'REGISTERED_ELSEWHERE'];
389
+ });
390
+ await stage('EXTENSION_BUILD', () => {
391
+ const raw = readFileSync(join(p.extensionDir, 'manifest.json'), 'utf8');
392
+ const m = JSON.parse(raw);
393
+ const id = m.key ? extensionIdFromPublicKeyDer(Buffer.from(m.key, 'base64')) : '';
394
+ if (!(id === c.extensionId && m.permissions?.includes('nativeMessaging')))
395
+ return ['FAIL', 'EXTENSION_ID_MISMATCH'];
396
+ // SW-065: an installed build older than the source tree is exactly how a fix can be "accepted" without ever running. Fail loudly.
397
+ const built = builtExtensionId(raw);
398
+ const src = extensionSourceId(root);
399
+ return built === src ? ['PASS', `id=${id} build=${built}`] : ['FAIL', `EXTENSION_STALE installed=${built ?? 'UNSTAMPED'} source=${src} (run update, then Reload in chrome://extensions)`];
400
+ });
401
+ await stage('DAEMON_PINNED', () => (daemonTreeDigest(root) === c.daemonTreeSha256 ? ['PASS', 'daemon files match the installation'] : ['FAIL', 'UPDATE_REQUIRES_RECONSENT (run update)']));
402
+ await stage('INSTALLED_HOST_PING', async () => {
403
+ const r = NativeResponseV1Schema.parse(await callNativeHost(p.nativeHostEntry, p.hostConfig, c.extensionOrigin, { v: 1, type: 'PING' }));
404
+ return r.ok ? ['PASS', 'host answers the pinned origin'] : ['FAIL', r.code];
405
+ });
406
+ await stage('INSTALLED_HOST_FOREIGN_ORIGIN', async () => {
407
+ const r = NativeResponseV1Schema.parse(await callNativeHost(p.nativeHostEntry, p.hostConfig, `chrome-extension://${'b'.repeat(32)}`, { v: 1, type: 'PING' }));
408
+ return !r.ok && r.code === 'HOST_ORIGIN_MISMATCH' ? ['PASS', 'a different extension id is refused'] : ['FAIL', 'FOREIGN_ORIGIN_ACCEPTED'];
409
+ });
410
+ }
411
+ // ---- Part 2: isolated end-to-end through the REAL native host and a REAL daemon process (benign reference operation, own private test root) ----
412
+ const id = randomBytes(5).toString('hex');
413
+ const stParent = join(root, '.switchyard-data', 'selftest');
414
+ mkdirSync(stParent, { recursive: true });
415
+ const testData = join(stParent, `run-${id}`);
416
+ const tp = installPaths(root, testData);
417
+ const fakeOrigin = `chrome-extension://${'m'.repeat(32)}`;
418
+ let port = 0;
419
+ let bearer = '';
420
+ let daemonPid = 0;
421
+ let captureId = '';
422
+ let runId = '';
423
+ const auth = () => ({ origin: fakeOrigin, authorization: `Bearer ${bearer}`, 'x-centcom-correlation-id': corr });
424
+ const text = `my-centcom self-test ${corr}\nline two\ttab`;
425
+ const expected = `${text}\n`;
426
+ let alive = await stage('TEST_ROOT', () => { assertOrInitializePrivateDataRoot({ projectRoot: root, dataRoot: testData }); return ['PASS', 'private test data root (exact DACL)']; });
427
+ if (alive)
428
+ alive = await stage('TEST_PROVISION', async () => {
429
+ const project = createScratchProject(join(stParent, `project-${id}`));
430
+ const script = stageBenignScript(root, join(stParent, `benign-${id}`));
431
+ const d = await startSecureDaemon({ projectRoot: root, dataRoot: testData, approvedProject: { projectId: 'project.selftest', root: project }, devSmokeProfiles: true, port: 0, dpapi: deps.dpapi });
432
+ try {
433
+ await d.provisionedActions.provisionOperation({ pluginId: BENIGN_PLUGIN, operationId: BENIGN_OPERATION, profileId: 'reference-script-stdin', executablePath: realpathSync.native(process.execPath), codeInputPath: script });
434
+ const inst = d.authority.createInstallation(fakeOrigin);
435
+ d.authority.grantOperation(inst.principalId, 'project.selftest', BENIGN_PLUGIN, BENIGN_OPERATION, 'read', new Date(deps.now() + 3_600_000), true, 'RUN_CLICK');
436
+ const now = iso(deps.now());
437
+ writeHostFiles(tp, {
438
+ schemaVersion: 1, hostVersion: HOST_VERSION, installationId: inst.installationId, extensionId: 'm'.repeat(32), extensionOrigin: fakeOrigin, projectRoot: root, dataRoot: testData,
439
+ nodeExe: realpathSync.native(process.execPath), nodeSha256: sha256File(realpathSync.native(process.execPath)), daemonEntry: tp.daemonEntry, daemonTreeSha256: daemonTreeDigest(root),
440
+ approvedProject: { projectId: 'project.selftest', root: project }, devSmokeProfiles: true, protectedSecretB64: deps.dpapi.protect(Buffer.from(inst.secret, 'utf8')).toString('base64'), createdAt: now, updatedAt: now,
441
+ }, inst.secret);
442
+ }
443
+ finally {
444
+ await d.close();
445
+ }
446
+ return ['PASS', 'benign reference operation provisioned; test installation + RUN_CLICK grant'];
447
+ });
448
+ if (alive)
449
+ alive = await stage('NATIVE_CONNECT_STARTS_DAEMON', async () => {
450
+ const r = NativeResponseV1Schema.parse(await callNativeHost(tp.nativeHostEntry, tp.hostConfig, fakeOrigin, { v: 1, type: 'CONNECT' }));
451
+ if (!r.ok || r.type !== 'CONNECTED')
452
+ return ['FAIL', r.ok ? 'UNEXPECTED' : r.code];
453
+ port = r.port;
454
+ bearer = r.bearerToken;
455
+ daemonPid = runtimeRecord(testData)?.pid ?? 0;
456
+ return [r.daemonStarted ? 'PASS' : 'FAIL', `daemonStarted=${r.daemonStarted} port=${port}`];
457
+ });
458
+ if (alive)
459
+ alive = await stage('CAPTURE_STORE', async () => {
460
+ const r = await httpJson(port, '/v1/captures', { schemaVersion: 1, text, sha256: createHash('sha256').update(text).digest('hex'), bytes: Buffer.byteLength(text), fidelity: 'CAPTURED_RENDERED_TEXT', binding: { tabId: 1, windowId: 1, frameId: 0, documentId: 'SELFTESTDOC', nonce: 'selftest-nonce', sourceUrl: 'https://chatgpt.com/c/selftest' } }, auth());
461
+ captureId = String(r.json.captureId ?? '');
462
+ return r.status === 201 ? ['PASS', 'encrypted capture stored'] : ['FAIL', `HTTP ${r.status} ${JSON.stringify(r.json.error ?? {})}`];
463
+ });
464
+ if (alive)
465
+ alive = await stage('RUN_CLICK', async () => {
466
+ const r = await httpJson(port, `/v1/captures/${captureId}/run`, { schemaVersion: 1, projectId: 'project.selftest', pluginId: BENIGN_PLUGIN, operationId: BENIGN_OPERATION }, auth());
467
+ runId = String(r.json.runId ?? '');
468
+ return r.status === 202 && r.json.consent === 'RUN_CLICK' && r.json.lifecycleState === 'QUEUED' ? ['PASS', 'one click: queued without any code'] : ['FAIL', `HTTP ${r.status} state=${String(r.json.lifecycleState)} consent=${String(r.json.consent)}`];
469
+ });
470
+ if (alive)
471
+ alive = await stage('RUN_COMPLETES', async () => {
472
+ let since = null;
473
+ const end = Date.now() + 90_000;
474
+ const seen = [];
475
+ while (Date.now() < end) {
476
+ const r = await httpJson(port, `/v1/runs/${runId}/wait`, { schemaVersion: 1, sinceUpdatedAt: since, timeoutMs: 15000 }, auth());
477
+ const st = String(r.json.lifecycleState);
478
+ since = String(r.json.updatedAt);
479
+ if (seen.at(-1) !== st)
480
+ seen.push(st);
481
+ if (['COMPLETED', 'FAILED', 'UNKNOWN', 'CANCELLED'].includes(st))
482
+ return st === 'COMPLETED' ? ['PASS', seen.join('>')] : ['FAIL', seen.join('>')];
483
+ }
484
+ return ['FAIL', `TIMEOUT ${seen.join('>')}`];
485
+ });
486
+ if (alive)
487
+ alive = await stage('RETURN_SNAPSHOT', async () => {
488
+ const r = await httpJson(port, `/v1/runs/${runId}/return`, { schemaVersion: 1 }, auth());
489
+ const ok = (r.status === 201 || r.status === 200) && r.json.text === expected && r.json.sha256 === createHash('sha256').update(expected).digest('hex');
490
+ return ok ? ['PASS', `immutable snapshot ${String(r.json.bytes)} bytes, digest verified`] : ['FAIL', `HTTP ${r.status}`];
491
+ });
492
+ if (alive)
493
+ alive = await stage('RETURN_READY_DURABLE', async () => {
494
+ const r = await httpJson(port, '/v1/workflow/current', { schemaVersion: 1 }, auth());
495
+ const ret = r.json.ret;
496
+ return ret?.state === 'RETURN_READY' ? ['PASS', 'return target recorded in the daemon (survives worker restart)'] : ['FAIL', `ret=${JSON.stringify(ret)?.slice(0, 60)}`];
497
+ });
498
+ if (alive)
499
+ await stage('RECONNECT_NO_REPAIR', async () => {
500
+ const r = NativeResponseV1Schema.parse(await callNativeHost(tp.nativeHostEntry, tp.hostConfig, fakeOrigin, { v: 1, type: 'CONNECT' }));
501
+ if (!r.ok || r.type !== 'CONNECTED')
502
+ return ['FAIL', r.ok ? 'UNEXPECTED' : r.code];
503
+ const old = await httpJson(port, '/v1/workflow/current', { schemaVersion: 1 }, auth());
504
+ bearer = r.bearerToken;
505
+ const cur = await httpJson(port, '/v1/workflow/current', { schemaVersion: 1 }, auth());
506
+ return !r.daemonStarted && old.status === 401 && cur.status === 200 ? ['PASS', 'silent re-session; the previous bearer is rotated out'] : ['FAIL', `started=${r.daemonStarted} old=${old.status} new=${cur.status}`];
507
+ });
508
+ stages.push({ stage: 'LIVE_CHATGPT_INSERT', status: 'NOT_RUN', detail: 'by design: the self-test never touches chatgpt.com or a real composer', ms: 0 });
509
+ // cleanup (task-owned only)
510
+ if (daemonPid) {
511
+ try {
512
+ process.kill(daemonPid);
513
+ }
514
+ catch { /* gone */ }
515
+ }
516
+ await sleep(1500);
517
+ for (const d of [testData, join(stParent, `project-${id}`), join(stParent, `benign-${id}`)]) {
518
+ try {
519
+ rmSync(d, { recursive: true, force: true, maxRetries: 6, retryDelay: 300 });
520
+ }
521
+ catch { /* reported below */ }
522
+ }
523
+ const ok = stages.every((s) => s.status !== 'FAIL');
524
+ const reportPath = join(stParent, 'selftest-report.txt');
525
+ const lines = [
526
+ `my-centcom self-test report (redacted: no secrets, bearer, codes, prompts or personal URLs)`,
527
+ `result=${ok ? 'PASS' : 'FAIL'} correlationId=${corr} at=${iso(deps.now())} hostVersion=${HOST_VERSION}`,
528
+ ...stages.map((s) => `${s.stage.padEnd(30)} ${s.status.padEnd(7)} ${s.ms}ms ${redactText(s.detail)}`),
529
+ `firstFailure=${stages.find((s) => s.status === 'FAIL')?.stage ?? 'NONE'}`,
530
+ ];
531
+ writeFileSync(reportPath, `${lines.join('\n')}\n`);
532
+ return { correlationId: corr, stages, ok, reportPath };
533
+ }
534
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
535
+ // confirm (attended terminal only)
536
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
537
+ export async function confirm(root, deps, ask, dataRoot) {
538
+ const p = installPaths(root, dataRoot);
539
+ const cfg = readHostConfig(p);
540
+ if (!cfg)
541
+ throw new SetupError('NOT_INSTALLED');
542
+ const rt = runtimeRecord(p.dataRoot);
543
+ if (!rt)
544
+ throw new SetupError('DAEMON_NOT_RUNNING', 'Open the my-centcom panel once so the daemon starts, then retry.');
545
+ const secret = deps.dpapi.unprotect(Buffer.from(cfg.protectedSecretB64, 'base64')).toString('utf8');
546
+ const base = { schemaVersion: 1, installationId: cfg.installationId, secret };
547
+ const pend = await httpJson(rt.port, '/v1/bootstrap/pending', base);
548
+ const list = pend.json.pending ?? [];
549
+ if (list.length === 0) {
550
+ deps.out('NOTHING_PENDING');
551
+ return 0;
552
+ }
553
+ let n = 0;
554
+ for (const r of list) {
555
+ deps.out(`PENDING run=${r.runId} project=${r.projectId} operation=${r.pluginId}/${r.operationId} effect=${r.effectClass} input=${r.promptBytes} bytes`);
556
+ if ((await ask('Allow this run to start? Type yes to confirm: ')).trim() !== 'yes') {
557
+ deps.out('NOT_CONFIRMED');
558
+ continue;
559
+ }
560
+ const c = await httpJson(rt.port, '/v1/bootstrap/confirm', { ...base, runId: r.runId });
561
+ deps.out(c.status === 200 ? `CONFIRMED ${r.runId} ${String(c.json.lifecycleState)}` : `REFUSED HTTP ${c.status}`);
562
+ if (c.status === 200)
563
+ n += 1;
564
+ }
565
+ return n;
566
+ }
567
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
568
+ // CLI
569
+ // ---------------------------------------------------------------------------------------------------------------------------------------------
570
+ function parseOps(argv) {
571
+ const out = [];
572
+ for (let i = 0; i < argv.length; i += 1)
573
+ if (argv[i] === '--operation') {
574
+ const m = /^([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})$/.exec(argv[i + 1] ?? '');
575
+ if (!m)
576
+ throw new SetupError('BAD_ARGUMENT', '--operation <plugin-id>/<operation-id>');
577
+ out.push({ pluginId: m[1], operationId: m[2] });
578
+ }
579
+ return out;
580
+ }
581
+ const val = (argv, n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; };
582
+ export async function cli(argv, deps = productionSetupDeps()) {
583
+ const root = projectRootFromHere();
584
+ const cmd = argv[0] && !argv[0].startsWith('--') ? argv[0] : 'plan';
585
+ const flags = new Set(argv.filter((a) => a.startsWith('--')));
586
+ try {
587
+ switch (cmd) {
588
+ case 'plan': {
589
+ const p = installPaths(root);
590
+ for (const l of [
591
+ 'PLAN (nothing is changed by this command):',
592
+ ` 1. build the installed extension with a pinned key into ${p.extensionDir}`,
593
+ ` 2. create a revocable installation record and protect its secret with Windows DPAPI (CurrentUser) in ${p.installDir}`,
594
+ ` 3. write the native host manifest (exactly one allowed extension origin) and its launcher into ${p.nativeHostDir}`,
595
+ ' 4. register the approved project and RUN_CLICK read-only grants for the operations you name',
596
+ ` 5. ONLY with --register-native-host --consent: reg add "${HOST_KEY}" /ve /t REG_SZ /d "${p.hostManifest}" /f`,
597
+ 'Example: npm run centcom -- install --create-scratch-project --dev-smoke-benign --register-native-host --consent',
598
+ ])
599
+ deps.out(l);
600
+ return 0;
601
+ }
602
+ case 'install':
603
+ case 'update': {
604
+ const r = await install(root, {
605
+ ...(val(argv, '--approved-project-root') ? { approvedProjectRoot: val(argv, '--approved-project-root') } : {}), ...(val(argv, '--project-id') ? { projectId: val(argv, '--project-id') } : {}),
606
+ createScratchProject: flags.has('--create-scratch-project'), operations: parseOps(argv), devSmokeBenign: flags.has('--dev-smoke-benign'),
607
+ ...(val(argv, '--grant-days') ? { grantDays: Math.min(365, Math.max(1, Number(val(argv, '--grant-days')))) } : {}),
608
+ registerNativeHost: flags.has('--register-native-host'), consent: flags.has('--consent'),
609
+ }, deps, cmd);
610
+ deps.out(`DONE ${cmd}: load the extension once from ${r.extensionDir} (chrome://extensions -> Developer mode -> Load unpacked); its id must be ${r.extensionId}.`);
611
+ return 0;
612
+ }
613
+ case 'status':
614
+ for (const [k, v] of Object.entries(status(root, deps)))
615
+ deps.out(`${k}=${v}`);
616
+ return 0;
617
+ case 'diagnose': {
618
+ // SW-068: the ONE predictable place for a failed execution's evidence. `npm run centcom -- diagnose [<run-id>|<corr.id>|latest]` prints the category and correlation id and
619
+ // writes the redacted, shareable export to .switchyard-data/diagnostics/<correlation-id>.json. Nothing raw is stored anywhere, so nothing raw can be exported.
620
+ const key = argv[1] && !argv[1].startsWith('--') ? argv[1] : 'latest';
621
+ // --data-root <dir> reads another data root (a copy, a test ledger). The ledger is NEVER migrated by this command: opening a ledger would apply pending schema changes, and an
622
+ // installed daemon that has not been updated would then refuse its own database. An older ledger is reported and left untouched (run `update` first).
623
+ const dataRootArg = val(argv, '--data-root');
624
+ const dbFile = join(dataRootArg ? resolve(dataRootArg) : installPaths(root).dataRoot, SECURE_DB_FILE_NAME);
625
+ if (!existsSync(dbFile)) {
626
+ deps.out('DIAGNOSE_NO_LEDGER');
627
+ return 1;
628
+ }
629
+ const peek = new DatabaseSync(dbFile, { readOnly: true });
630
+ let version = 0;
631
+ try {
632
+ version = Number(peek.prepare('PRAGMA user_version').get().user_version);
633
+ }
634
+ finally {
635
+ peek.close();
636
+ }
637
+ if (version !== LEDGER_SCHEMA_VERSION) {
638
+ deps.out(`DIAGNOSE_LEDGER_VERSION ${version} (this build reads ${LEDGER_SCHEMA_VERSION}); nothing was changed. Run: npm run centcom -- update`);
639
+ return 1;
640
+ }
641
+ const ledger = new SqliteLedger(dbFile);
642
+ try {
643
+ const tel = new ExecutionTelemetry(ledger);
644
+ const runId = key === 'latest' ? ledger.findExecutionEvidenceRun() : key.startsWith('corr.') ? ledger.findExecutionEvidenceRun(key) : key;
645
+ if (!runId || !ledger.getExecutionEvidence(runId)) {
646
+ deps.out('DIAGNOSE_NO_EVIDENCE');
647
+ return 1;
648
+ }
649
+ const ev = ledger.getRunEvidence(runId).lifecycle;
650
+ const state = ev.length > 0 ? ev[ev.length - 1].state : 'UNKNOWN';
651
+ const exp = tel.exportEvidence({ runId }, state);
652
+ if (!exp) {
653
+ deps.out('DIAGNOSE_NO_EVIDENCE');
654
+ return 1;
655
+ }
656
+ const dir = join(root, '.switchyard-data', 'diagnostics');
657
+ mkdirSync(dir, { recursive: true });
658
+ const file = join(dir, `${exp.correlationId}.json`);
659
+ writeFileSync(file, JSON.stringify(exp, null, 2));
660
+ const c = exp.classification;
661
+ deps.out(`DIAGNOSE correlationId=${exp.correlationId} run=${exp.runId} state=${state} category=${c?.category ?? 'NONE'} basis=${c?.basis ?? '-'} causeDetermined=${c?.causeDetermined ?? false} lastStage=${exp.lastStage} events=${exp.events.length}`);
662
+ deps.out(`EXPORT ${file}`);
663
+ return 0;
664
+ }
665
+ finally {
666
+ ledger.close();
667
+ }
668
+ }
669
+ case 'stage-ca': {
670
+ // SW-069: writes the REVIEWED Mozilla root bundle of the RUNNING Node to an immutable, digest-pinned file the restricted identity can read but never modify. It refuses (writes
671
+ // nothing) unless this Node is exactly the reviewed release and its bundle is exactly the reviewed digest: a Node update needs a reviewed new entry, never a silent regeneration.
672
+ try {
673
+ const r = stageCaBundle({ stagingRoot: join(root, '.switchyard-data', 'agents'), id: 'mozilla-node-v24.20.0-win-x64' });
674
+ deps.out(`STAGED_CA ${r.reused ? 'REUSED_VERIFIED' : 'NEW'} certs=${r.certCount} file=${r.path}`);
675
+ return 0;
676
+ }
677
+ catch (e) {
678
+ deps.out(`STAGE_CA_FAILED ${e instanceof CaBundleError ? e.message : 'UNEXPECTED'}`);
679
+ return 1;
680
+ }
681
+ }
682
+ case 'stage-codex': {
683
+ // SW-067: copy the REVIEWED Codex build (every file digest-checked) to an immutable project-local directory the restricted identity can execute. Nothing is run.
684
+ const appData = process.env.APPDATA;
685
+ const source = val(argv, '--source') ?? (appData ? join(appData, 'npm', 'node_modules', '@openai', 'codex', 'node_modules', '@openai', 'codex-win32-x64', 'vendor', 'x86_64-pc-windows-msvc') : '');
686
+ try {
687
+ const r = stageAgentBuild({ sourceDir: source, stagingRoot: join(root, '.switchyard-data', 'agents'), buildId: 'codex-0.167.0-win32-x64' });
688
+ deps.out(`STAGED ${r.reused ? 'REUSED_VERIFIED' : 'NEW'} entrypoint=${r.entrypoint}`);
689
+ return 0;
690
+ }
691
+ catch (e) {
692
+ deps.out(`STAGE_FAILED ${e instanceof StagingError ? e.message : 'UNEXPECTED'}`);
693
+ return 1;
694
+ }
695
+ }
696
+ case 'stop':
697
+ stop(root, deps);
698
+ return 0;
699
+ case 'uninstall':
700
+ await uninstall(root, { consent: flags.has('--consent') }, deps);
701
+ return 0;
702
+ case 'selftest': {
703
+ const r = await selftest(root, deps);
704
+ deps.out(`SELFTEST ${r.ok ? 'PASS' : 'FAIL'} correlationId=${r.correlationId} report=${r.reportPath}`);
705
+ return r.ok ? 0 : 1;
706
+ }
707
+ case 'confirm': {
708
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
709
+ throw new SetupError('TTY_REQUIRED', 'Run it in an interactive terminal.');
710
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
711
+ try {
712
+ await confirm(root, deps, (q) => rl.question(q));
713
+ }
714
+ finally {
715
+ rl.close();
716
+ }
717
+ return 0;
718
+ }
719
+ default: throw new SetupError('UNKNOWN_COMMAND', 'Commands: plan | install | update | status | selftest | confirm | stop | uninstall');
720
+ }
721
+ }
722
+ catch (e) {
723
+ const code = e instanceof SetupError ? e.code : 'SETUP_FAILED';
724
+ deps.out(`ERROR ${code}${e instanceof SetupError && e.action ? ` -> ${e.action}` : ''}`);
725
+ if (!(e instanceof SetupError))
726
+ deps.out(`DETAIL ${redactText(String(e?.message ?? e))}`);
727
+ return 1;
728
+ }
729
+ }
730
+ const isDirect = (() => { try {
731
+ return realpathSync(fileURLToPath(import.meta.url)).toLowerCase() === realpathSync(process.argv[1] ?? '').toLowerCase();
732
+ }
733
+ catch {
734
+ return false;
735
+ } })();
736
+ if (isDirect)
737
+ cli(process.argv.slice(2)).then((code) => process.exit(code), () => process.exit(1));
738
+ //# sourceMappingURL=setup.js.map