specpi 0.19.0 → 0.20.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.
@@ -0,0 +1,228 @@
1
+ import path from "node:path";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { Type } from "typebox";
4
+ import { StringEnum } from "@earendil-works/pi-ai";
5
+ import { getAgentDir } from "../browser/core.mjs";
6
+ import { LANGUAGES, SearchError, normalizeSearch, structuralSearch } from "./core.mjs";
7
+ import { readIntegrations } from "./config.mjs";
8
+
9
+ type Policy = { mode: string; generation: number; action: string };
10
+ export default function registerStructuralSearch(pi: ExtensionAPI) {
11
+ const agentDir = getAgentDir(import.meta.url);
12
+ let enabled = false;
13
+ try {
14
+ enabled = readIntegrations(agentDir).structuralSearch.enabled;
15
+ } catch {
16
+ // Malformed configuration never enables code execution.
17
+ }
18
+
19
+ if (!enabled) {
20
+ return;
21
+ }
22
+
23
+ let lifecycle = new AbortController();
24
+ let cleanupFailed = false;
25
+ let pending = 0;
26
+ let tail: Promise<unknown> = Promise.resolve();
27
+ const invalidate = () => {
28
+ lifecycle.abort();
29
+ lifecycle = new AbortController();
30
+ };
31
+
32
+ const unsubscribe = pi.events.on("specpi:guard-policy-changed", invalidate);
33
+ pi.on("session_start", invalidate);
34
+ pi.on("session_tree", invalidate);
35
+ pi.on("session_shutdown", () => {
36
+ invalidate();
37
+ unsubscribe();
38
+ });
39
+ function policy(): Policy {
40
+ let states = 0;
41
+ const replies: Policy[] = [];
42
+ pi.events.emit("specpi:guard-state", {
43
+ reply() {
44
+ states += 1;
45
+ },
46
+ });
47
+ pi.events.emit("specpi:structural-admission", {
48
+ reply(value: Policy) {
49
+ replies.push(value);
50
+ },
51
+ });
52
+ if (states === 0 && replies.length === 0) {
53
+ return { mode: "absent", generation: 0, action: "allow" };
54
+ }
55
+
56
+ const value = replies[0];
57
+ if (
58
+ states !== 1 ||
59
+ replies.length !== 1 ||
60
+ !["guard", "strict", "off", "locked"].includes(value?.mode) ||
61
+ !Number.isSafeInteger(value.generation) ||
62
+ !["allow", "ask", "deny"].includes(value.action)
63
+ ) {
64
+ throw new SearchError("denied", "Structural search policy unavailable or ambiguous.");
65
+ }
66
+
67
+ return value;
68
+ }
69
+
70
+ pi.registerTool({
71
+ name: "structural_search",
72
+ label: "Structural Search",
73
+ description:
74
+ "Read-only ast-grep patterns over explicit selected source files. Use literal search for filenames/comments; results do not resolve types or symbols. No rewrite or custom config.",
75
+ parameters: Type.Object(
76
+ {
77
+ language: StringEnum(Object.keys(LANGUAGES)),
78
+ pattern: Type.String(),
79
+ paths: Type.Array(Type.String()),
80
+ maxResults: Type.Optional(Type.Integer()),
81
+ timeoutMs: Type.Optional(Type.Integer()),
82
+ },
83
+ { additionalProperties: false },
84
+ ),
85
+ executionMode: "sequential",
86
+ async execute(_id, input, originalSignal, _update, ctx) {
87
+ const spec = normalizeSearch(input);
88
+ const cwd = path.resolve(ctx.cwd);
89
+ if (pending >= 2) {
90
+ throw new SearchError("denied", "Structural search queue is full.");
91
+ }
92
+
93
+ pending += 1;
94
+ let started = false;
95
+ const controller = new AbortController();
96
+ const signal = AbortSignal.any([
97
+ controller.signal,
98
+ lifecycle.signal,
99
+ ...(originalSignal ? [originalSignal] : []),
100
+ ]);
101
+ const deadline = Date.now() + spec.timeoutMs;
102
+ const timer = setTimeout(() => controller.abort(), spec.timeoutMs);
103
+ const run = async () => {
104
+ started = true;
105
+ if (cleanupFailed) {
106
+ throw new SearchError(
107
+ "cleanup_failed",
108
+ "Previous parser cleanup failed; resolve it before reloading.",
109
+ );
110
+ }
111
+
112
+ if (!readIntegrations(agentDir).structuralSearch.enabled || signal.aborted) {
113
+ throw new SearchError("denied", "Structural search disabled or cancelled.");
114
+ }
115
+
116
+ const granted = policy();
117
+ if (granted.action === "deny") {
118
+ throw new SearchError("denied", "Command Guard denied structural search.");
119
+ }
120
+
121
+ if (granted.action === "ask") {
122
+ if (!ctx.hasUI) {
123
+ throw new SearchError("denied", "Strict structural search requires approval UI.");
124
+ }
125
+
126
+ const prompt = ctx.ui.select(
127
+ `Read-only structural search ${JSON.stringify({ cwd, language: spec.language, paths: spec.paths, pattern: spec.pattern }).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/gu, "_")}`,
128
+ ["Deny", "Allow once"],
129
+ // RPC forwards timeout to clients but does not forward signal-driven dismissal.
130
+ { signal, timeout: Math.max(1, deadline - Date.now()) },
131
+ );
132
+ let cancelApproval: (() => void) | undefined;
133
+ let answer;
134
+ try {
135
+ answer = await Promise.race([
136
+ prompt,
137
+ new Promise<undefined>((resolve) => {
138
+ cancelApproval = () => resolve(undefined);
139
+ signal.addEventListener("abort", cancelApproval, { once: true });
140
+ if (signal.aborted) {
141
+ cancelApproval();
142
+ }
143
+ }),
144
+ ]);
145
+ } finally {
146
+ if (cancelApproval) {
147
+ signal.removeEventListener("abort", cancelApproval);
148
+ }
149
+ }
150
+
151
+ if (answer !== "Allow once") {
152
+ throw new SearchError("denied", "Structural search was not approved.");
153
+ }
154
+ }
155
+
156
+ const admit = async () => {
157
+ const current = policy();
158
+ if (
159
+ signal.aborted ||
160
+ path.resolve(ctx.cwd) !== cwd ||
161
+ current.action === "deny" ||
162
+ current.generation !== granted.generation ||
163
+ current.mode !== granted.mode ||
164
+ !readIntegrations(agentDir).structuralSearch.enabled
165
+ ) {
166
+ throw new SearchError("denied", "Structural search policy changed or request cancelled.");
167
+ }
168
+ };
169
+
170
+ return structuralSearch(spec, {
171
+ cwd,
172
+ runtimeDir: path.join(agentDir, "specpi", "structural-runtime"),
173
+ signal,
174
+ admit,
175
+ });
176
+ };
177
+
178
+ const operation = tail.then(run, run);
179
+ tail = operation
180
+ .catch(() => {})
181
+ .finally(() => {
182
+ pending -= 1;
183
+ });
184
+ let cancelQueued: (() => void) | undefined;
185
+ try {
186
+ const queuedAbort = new Promise<never>((_resolve, reject) => {
187
+ cancelQueued = () => {
188
+ if (!started) {
189
+ reject(new SearchError("cancelled", "Queued structural search cancelled."));
190
+ }
191
+ };
192
+
193
+ signal.addEventListener("abort", cancelQueued, { once: true });
194
+ if (signal.aborted) {
195
+ cancelQueued();
196
+ }
197
+ });
198
+ const value = await Promise.race([operation, queuedAbort]);
199
+
200
+ return { content: [{ type: "text", text: JSON.stringify(value) }], details: {} };
201
+ } catch (error) {
202
+ cleanupFailed ||= error instanceof SearchError && error.status === "cleanup_failed";
203
+ const status = controller.signal.aborted
204
+ ? "timed_out"
205
+ : signal.aborted
206
+ ? "cancelled"
207
+ : error instanceof SearchError
208
+ ? error.status
209
+ : "denied";
210
+ const reason =
211
+ error instanceof SearchError
212
+ ? error.message
213
+ : "Source selection or runtime unavailable; check the explicit files and configuration.";
214
+
215
+ return {
216
+ content: [{ type: "text", text: JSON.stringify({ status, reason }) }],
217
+ details: {},
218
+ isError: true,
219
+ };
220
+ } finally {
221
+ clearTimeout(timer);
222
+ if (cancelQueued) {
223
+ signal.removeEventListener("abort", cancelQueued);
224
+ }
225
+ }
226
+ },
227
+ });
228
+ }
@@ -0,0 +1,23 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import assert from "node:assert/strict";
5
+ import { parseSource, resolveBinary } from "./core.mjs";
6
+
7
+ const runtime = path.resolve(process.argv[2]);
8
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "specpi-structural-smoke-"));
9
+ try {
10
+ fs.writeFileSync(path.join(directory, "sgconfig.yml"), "ruleDirs: []\n");
11
+ const matches = await parseSource(
12
+ resolveBinary(runtime),
13
+ directory,
14
+ { language: "typescript", pattern: "target($A)" },
15
+ Buffer.from('target(42); "target(9)";'),
16
+ AbortSignal.timeout(10000),
17
+ );
18
+ assert.equal(matches.length, 1);
19
+ assert.equal(matches[0].text, "target(42)");
20
+ console.log("STRUCTURAL_SEARCH_SMOKE=passed");
21
+ } finally {
22
+ fs.rmSync(directory, { recursive: true, force: true });
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "specpi",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "An explicit, privacy-conscious, self-improving harness for the Pi coding agent",
5
5
  "author": "Tanner Middleton",
6
6
  "repository": {
@@ -27,7 +27,11 @@
27
27
  "scripts/specpi.mjs",
28
28
  "scripts/lib.mjs",
29
29
  "scripts/lock.mjs",
30
- "browser-runtime",
30
+ "scripts/structural-runtime.mjs",
31
+ "browser-runtime/package.json",
32
+ "browser-runtime/package-lock.json",
33
+ "structural-runtime/package.json",
34
+ "structural-runtime/package-lock.json",
31
35
  "templates",
32
36
  "extensions",
33
37
  "skills",
@@ -36,6 +40,7 @@
36
40
  "README.md",
37
41
  "docs/delegation",
38
42
  "docs/browser-testing.md",
43
+ "docs/structural-search.md",
39
44
  "site/logo.svg",
40
45
  "SECURITY.md",
41
46
  "SECURITY_MODEL.md",
@@ -89,6 +94,8 @@
89
94
  "check:syntax": "node scripts/check-syntax.mjs",
90
95
  "check:types": "tsc -p tsconfig.browser.json",
91
96
  "setup:browser": "node scripts/setup-browser-tests.mjs",
97
+ "setup:structural": "node scripts/setup-structural-tests.mjs",
98
+ "test:structural": "node scripts/run-structural-tests.mjs",
92
99
  "test:browser": "node scripts/run-browser-tests.mjs extension",
93
100
  "test:site:browser": "node scripts/run-browser-tests.mjs site",
94
101
  "check:package": "node scripts/check-package.mjs",
@@ -27,6 +27,8 @@ import { runValidator } from "../extensions/tool-wishlist/validators.mjs";
27
27
  import { acquireSpecPiLock } from "./lock.mjs";
28
28
  import { COMMAND_GUARD_MANAGED_FILES } from "../extensions/command-guard/managed-files.mjs";
29
29
  import { DELEGATION_MANAGED_FILES } from "../extensions/delegation/managed-files.mjs";
30
+ import { integrationsFile, readIntegrations, serializeIntegrations } from "../extensions/structural-search/config.mjs";
31
+ import { changeStructuralRuntime, structuralRuntimeStatus } from "./structural-runtime.mjs";
30
32
 
31
33
  const scriptDir = path.dirname(fileURLToPath(import.meta.url));
32
34
  const repoRoot = path.resolve(scriptDir, "..");
@@ -46,6 +48,15 @@ const browserRuntimeSourceDir = path.join(repoRoot, "browser-runtime");
46
48
  const browserRuntimeDir = path.join(stateDir, "browser-runtime");
47
49
  const browserRuntimeMarker = path.join(browserRuntimeDir, "specpi-runtime.json");
48
50
  const browserSmokePath = path.join(agentDir, "extensions", "browser", "smoke.mjs");
51
+ const structuralSourceDir = path.join(repoRoot, "structural-runtime");
52
+ const integrationsPath = integrationsFile(agentDir);
53
+ const structuralFiles = ["index.ts", "core.mjs", "config.mjs", "smoke.mjs"];
54
+ function smokeStructuralRuntime(directory) {
55
+ return run(process.execPath, [path.join(repoRoot, "extensions", "structural-search", "smoke.mjs"), directory], {
56
+ capture: true,
57
+ });
58
+ }
59
+
49
60
  const backgroundFiles = ["index.ts", "core.mjs", "supervisor.mjs", "smoke.mjs"];
50
61
  const backgroundRoot = path.join(agentDir, "extensions", "background-tasks");
51
62
  const capabilityRegistryPath = path.join(agentDir, "extensions", "tool-wishlist", "capabilities.json");
@@ -91,9 +102,10 @@ Usage:
91
102
  Options:
92
103
  --yes Do not ask for confirmation; attempt all missing optional tools.
93
104
  --force Replace locally modified SpecPi-managed files during update.
94
- --skip-package-install Do not bootstrap Pi or install external Pi packages (also skips the browser runtime).
105
+ --skip-package-install Do not bootstrap Pi or install external Pi packages (also skips browser/structural runtime acquisition).
95
106
  --skip-browser-install Install browser tools but skip the managed Playwright/Chromium runtime.
96
- --skip-tool-install Do not offer or install the optional DonSeTch CLI.
107
+ --skip-tool-install Skip DonSeTch and structural-search runtime acquisition.
108
+ --structural-search=on|off Opt in to structural search or disable/remove its private runtime; omission preserves the choice.
97
109
  --skip-shell Do not install shell profile functions or edit a shell rc file.
98
110
 
99
111
  Environment:
@@ -110,6 +122,8 @@ function parseArgs(argv) {
110
122
  "--skip-browser-install",
111
123
  "--skip-tool-install",
112
124
  "--skip-shell",
125
+ "--structural-search=on",
126
+ "--structural-search=off",
113
127
  ]);
114
128
  for (const arg of argv.slice(1)) {
115
129
  if (!known.has(arg)) {
@@ -117,8 +131,24 @@ function parseArgs(argv) {
117
131
  }
118
132
  }
119
133
 
134
+ if (argv.includes("--structural-search=on") && argv.includes("--structural-search=off")) {
135
+ throw new Error("Choose one structural-search mode.");
136
+ }
137
+
138
+ if (
139
+ argv.some((arg) => arg.startsWith("--structural-search=")) &&
140
+ !["plan", "install", "update"].includes(command)
141
+ ) {
142
+ throw new Error("Structural-search selection is supported by plan/install/update only.");
143
+ }
144
+
120
145
  return {
121
146
  command,
147
+ structuralSearch: argv.includes("--structural-search=on")
148
+ ? true
149
+ : argv.includes("--structural-search=off")
150
+ ? false
151
+ : undefined,
122
152
  yes: argv.includes("--yes"),
123
153
  force: argv.includes("--force"),
124
154
  skipPackageInstall: argv.includes("--skip-package-install"),
@@ -490,9 +520,13 @@ function browserRuntimeStatus() {
490
520
 
491
521
  function smokeBrowserRuntime(directory) {
492
522
  try {
493
- return run(process.execPath, [path.join(repoRoot, "extensions", "browser", "smoke.mjs"), directory], {
494
- capture: true,
495
- });
523
+ return run(
524
+ process.execPath,
525
+ [path.join(repoRoot, "extensions", "browser", "smoke.mjs"), directory, "--accessibility"],
526
+ {
527
+ capture: true,
528
+ },
529
+ );
496
530
  } catch (error) {
497
531
  throw new Error(
498
532
  `${error.message}\nChromium could not launch. Verify the host satisfies Playwright Chromium system dependencies; SpecPi does not install Playwright system dependencies.`,
@@ -754,6 +788,16 @@ function desiredSettingsOperations() {
754
788
 
755
789
  function managedFiles(includeShell) {
756
790
  const files = [
791
+ ...structuralFiles.map((name) => [
792
+ path.join(repoRoot, "extensions", "structural-search", name),
793
+ path.join(agentDir, "extensions", "structural-search", name),
794
+ 0o644,
795
+ ]),
796
+ [
797
+ path.join(repoRoot, "extensions", "browser", "accessibility.ts"),
798
+ path.join(agentDir, "extensions", "browser", "accessibility.ts"),
799
+ 0o644,
800
+ ],
757
801
  ...backgroundFiles.map((name) => [
758
802
  path.join(repoRoot, "extensions", "background-tasks", name),
759
803
  path.join(backgroundRoot, name),
@@ -1141,6 +1185,11 @@ async function confirm(message, yes) {
1141
1185
 
1142
1186
  function assertSources() {
1143
1187
  const required = [
1188
+ "scripts/structural-runtime.mjs",
1189
+ "structural-runtime/package.json",
1190
+ "structural-runtime/package-lock.json",
1191
+ ...structuralFiles.map((name) => `extensions/structural-search/${name}`),
1192
+ "extensions/browser/accessibility.ts",
1144
1193
  ...backgroundFiles.map((name) => `extensions/background-tasks/${name}`),
1145
1194
  "extensions/spec.ts",
1146
1195
  "extensions/spec/core.mjs",
@@ -1189,7 +1238,45 @@ function assertSources() {
1189
1238
  readJson(settingsPath, {});
1190
1239
  }
1191
1240
 
1241
+ // An explicit selection may rewrite an unparseable owned file; its prior bytes go to the operation backup.
1242
+ // Omission fails closed rather than silently discarding unrelated fields nobody can read.
1243
+ function readIntegrationsForOperation(selection) {
1244
+ try {
1245
+ return readIntegrations(agentDir);
1246
+ } catch (error) {
1247
+ if (!error.corruptIntegrations) {
1248
+ throw error;
1249
+ }
1250
+
1251
+ if (selection === undefined) {
1252
+ throw new Error(
1253
+ `${error.message}\nRepair or remove it, or rerun with --structural-search=on or --structural-search=off to rewrite it.`,
1254
+ );
1255
+ }
1256
+
1257
+ return { schema: 1, structuralSearch: { enabled: selection } };
1258
+ }
1259
+ }
1260
+
1192
1261
  function printPlan(options) {
1262
+ let structuralEnabled = options.structuralSearch;
1263
+ let structuralNote;
1264
+ try {
1265
+ const current = readIntegrations(agentDir).structuralSearch.enabled;
1266
+ structuralEnabled ??= current;
1267
+ } catch (error) {
1268
+ if (!error.corruptIntegrations) {
1269
+ throw error;
1270
+ }
1271
+
1272
+ // plan stays non-mutating and still reports: a repairable owned file must not abort the preview.
1273
+ structuralNote =
1274
+ structuralEnabled === undefined
1275
+ ? `${error.message}\n Repair or remove it, or rerun with --structural-search=on or --structural-search=off to rewrite it.`
1276
+ : `${error.message}\n The selection above replaces it during install or update.`;
1277
+ structuralEnabled ??= false;
1278
+ }
1279
+
1193
1280
  const shellRc = detectShellRc();
1194
1281
  const manageShell = !options.skipShell && Boolean(shellRc);
1195
1282
  console.log(`SpecPi ${VERSION} installation plan
@@ -1210,6 +1297,17 @@ Managed files:`);
1210
1297
  }
1211
1298
 
1212
1299
  console.log(` ${manifestPath}`);
1300
+ console.log(
1301
+ `\nStructural search: ${structuralEnabled ? "enabled (ast-grep 0.45.3; private runtime; no global PATH change)" : "disabled"}`,
1302
+ );
1303
+ console.log(` ${integrationsPath} (owned enablement; existing unrelated fields preserved)`);
1304
+ if (structuralNote) {
1305
+ console.log(` ${structuralNote}`);
1306
+ }
1307
+
1308
+ if (structuralEnabled && (options.skipPackageInstall || options.skipToolInstall)) {
1309
+ console.log(" structural runtime acquisition skipped by explicit flag");
1310
+ }
1213
1311
 
1214
1312
  console.log("\nSettings ownership:");
1215
1313
  console.log(" theme defaults to specpi-spec; existing valid user choices are preserved");
@@ -1364,11 +1462,25 @@ async function installOrUpdate(options, update) {
1364
1462
  let piBootstrapAttempted = false;
1365
1463
  let piInstalledByOperation = false;
1366
1464
  let browserRuntimeTransaction;
1465
+ let structuralTransaction;
1367
1466
  let optionalToolTransaction;
1368
1467
  let backupDir;
1369
1468
  const preservedRetiredTools = [];
1370
1469
  try {
1371
1470
  const previousManifest = readManifest(update);
1471
+ const integrations = readIntegrationsForOperation(options.structuralSearch);
1472
+ const structuralEnabled = options.structuralSearch ?? integrations.structuralSearch.enabled;
1473
+ // Bound the output before any runtime/configuration mutation, not only when reading the input.
1474
+ const integrationsText =
1475
+ options.structuralSearch !== undefined || fs.existsSync(integrationsPath)
1476
+ ? serializeIntegrations(
1477
+ {
1478
+ ...integrations,
1479
+ structuralSearch: { ...integrations.structuralSearch, enabled: structuralEnabled },
1480
+ },
1481
+ integrationsPath,
1482
+ )
1483
+ : undefined;
1372
1484
  if (!update && previousManifest) {
1373
1485
  throw new Error(`SpecPi is already installed. Run ${CLI} update.`);
1374
1486
  }
@@ -1393,6 +1505,7 @@ async function installOrUpdate(options, update) {
1393
1505
  optionalToolTransaction = await installOptionalTools(selectedOptionalTools);
1394
1506
 
1395
1507
  const watched = [
1508
+ integrationsPath,
1396
1509
  settingsPath,
1397
1510
  ...(previousManifest?.subagentConfigChanges ? [retiredSubagentConfigPath] : []),
1398
1511
  agentsPath,
@@ -1409,6 +1522,31 @@ async function installOrUpdate(options, update) {
1409
1522
 
1410
1523
  const settingsBeforeOperation = readJson(settingsPath, {});
1411
1524
  const warnings = [...optionalToolTransaction.warnings];
1525
+ if (!structuralEnabled || (!options.skipPackageInstall && !options.skipToolInstall)) {
1526
+ structuralTransaction = changeStructuralRuntime({
1527
+ stateDir,
1528
+ sourceDir: structuralSourceDir,
1529
+ enabled: structuralEnabled,
1530
+ run,
1531
+ smoke: smokeStructuralRuntime,
1532
+ warnings,
1533
+ });
1534
+ } else if (!structuralRuntimeStatus(stateDir, structuralSourceDir).installed) {
1535
+ warnings.push(
1536
+ "Structural search is enabled but runtime acquisition was skipped; it is unavailable until setup completes.",
1537
+ );
1538
+ }
1539
+
1540
+ if (integrationsText !== undefined) {
1541
+ // Back up the owned configuration only, never a whole Pi settings/profile store.
1542
+ if (fs.existsSync(integrationsPath)) {
1543
+ fs.copyFileSync(integrationsPath, path.join(backupDir, "tool-integrations.json"));
1544
+ }
1545
+
1546
+ atomicWrite(integrationsPath, integrationsText, 0o600);
1547
+ }
1548
+
1549
+ injectTestFailure("after-structural-runtime");
1412
1550
  const blockFiles = structuredClone(previousManifest?.blockFiles || {});
1413
1551
  blockFiles.agents ||= { existed: pathExists(agentsPath) };
1414
1552
  if (shellRc) {
@@ -1517,6 +1655,7 @@ async function installOrUpdate(options, update) {
1517
1655
  packageChanges,
1518
1656
  settingsChanges,
1519
1657
  browserRuntime: browserRuntimeStatus(),
1658
+ structuralRuntime: structuralRuntimeStatus(stateDir, structuralSourceDir),
1520
1659
  piBootstrap: piInstalledByOperation
1521
1660
  ? {
1522
1661
  package: PI_PACKAGE,
@@ -1536,6 +1675,7 @@ async function installOrUpdate(options, update) {
1536
1675
  }
1537
1676
 
1538
1677
  browserRuntimeTransaction?.commit();
1678
+ structuralTransaction?.commit();
1539
1679
  console.log(`\nSpecPi ${update ? "updated" : "installed"} successfully.`);
1540
1680
  console.log(`Manifest: ${manifestPath}`);
1541
1681
  for (const warning of warnings) {
@@ -1549,6 +1689,12 @@ async function installOrUpdate(options, update) {
1549
1689
  );
1550
1690
  } catch (error) {
1551
1691
  const rollbackErrors = [];
1692
+ try {
1693
+ rollbackErrors.push(...(structuralTransaction?.rollback() || []));
1694
+ } catch (rollbackError) {
1695
+ rollbackErrors.push(`structural runtime rollback: ${rollbackError.message}`);
1696
+ }
1697
+
1552
1698
  try {
1553
1699
  rollbackErrors.push(...(browserRuntimeTransaction?.rollback() || []));
1554
1700
  } catch (rollbackError) {
@@ -1674,6 +1820,7 @@ async function uninstall(options) {
1674
1820
  const releaseLock = acquireLock();
1675
1821
  let transaction;
1676
1822
  let retiredBrowserRuntime;
1823
+ let structuralTransaction;
1677
1824
  const preservedManagedTools = [];
1678
1825
  try {
1679
1826
  const manifest = readManifest(true);
@@ -1696,6 +1843,14 @@ async function uninstall(options) {
1696
1843
 
1697
1844
  transaction = snapshot(watched);
1698
1845
  const warnings = [];
1846
+ structuralTransaction = changeStructuralRuntime({
1847
+ stateDir,
1848
+ sourceDir: structuralSourceDir,
1849
+ enabled: false,
1850
+ run,
1851
+ smoke: smokeStructuralRuntime,
1852
+ warnings,
1853
+ });
1699
1854
 
1700
1855
  const settings = readJson(settingsPath, {});
1701
1856
  restoreSettingChanges(settings, manifest.settingsChanges || [], warnings);
@@ -1778,6 +1933,7 @@ async function uninstall(options) {
1778
1933
  }
1779
1934
 
1780
1935
  retiredBrowserRuntime = undefined;
1936
+ structuralTransaction?.commit();
1781
1937
  console.log("SpecPi configuration, managed optional tools, and managed browser runtime uninstalled.");
1782
1938
  console.log(
1783
1939
  "Externally installed Pi, optional tools, browser artifacts, downloaded Pi package caches, and local wishlist state/archives were preserved. Experiment metadata and exported patches were also preserved.",
@@ -1796,6 +1952,12 @@ async function uninstall(options) {
1796
1952
  }
1797
1953
  }
1798
1954
 
1955
+ try {
1956
+ rollbackErrors.push(...(structuralTransaction?.rollback() || []));
1957
+ } catch (rollbackError) {
1958
+ rollbackErrors.push(`structural runtime rollback: ${rollbackError.message}`);
1959
+ }
1960
+
1799
1961
  if (transaction) {
1800
1962
  try {
1801
1963
  restoreSnapshot(transaction);
@@ -1968,6 +2130,42 @@ async function doctor() {
1968
2130
  }
1969
2131
  }
1970
2132
 
2133
+ try {
2134
+ const enabled = readIntegrations(agentDir).structuralSearch.enabled;
2135
+ const status = structuralRuntimeStatus(stateDir, structuralSourceDir);
2136
+ const dependencies = [
2137
+ ...structuralFiles.map((name) => path.join(agentDir, "extensions", "structural-search", name)),
2138
+ ...["snapshot.mjs", "errors.mjs"].map((name) => path.join(agentDir, "extensions", "delegation", name)),
2139
+ ];
2140
+ const intact = dependencies.every(
2141
+ (target) =>
2142
+ manifest.files?.[target] &&
2143
+ fs.existsSync(target) &&
2144
+ sha256(fs.readFileSync(target)) === manifest.files[target].installedHash,
2145
+ );
2146
+ if (!enabled) {
2147
+ console.log("STRUCTURAL_SEARCH=disabled");
2148
+ } else if (!intact || !commandGuardIntegrity) {
2149
+ errors.push("Structural search smoke skipped: installed source/Guard integrity failed.");
2150
+ } else if (!status.installed) {
2151
+ (manifest.structuralRuntime?.installed ? errors : warnings).push(
2152
+ `Structural search unavailable: ${status.reason}`,
2153
+ );
2154
+ } else {
2155
+ const smoke = run(
2156
+ process.execPath,
2157
+ [
2158
+ path.join(agentDir, "extensions", "structural-search", "smoke.mjs"),
2159
+ path.join(stateDir, "structural-runtime"),
2160
+ ],
2161
+ { capture: true },
2162
+ );
2163
+ console.log(smoke.stdout.trim());
2164
+ }
2165
+ } catch (error) {
2166
+ errors.push(error?.corruptIntegrations ? error.message : "Structural search configuration or smoke failed.");
2167
+ }
2168
+
1971
2169
  const runtimeStatus = browserRuntimeStatus();
1972
2170
  let browserSmoke;
1973
2171
  if (!runtimeStatus.installed) {