omnicell-router 0.1.0 → 0.2.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 (212) hide show
  1. package/RELEASING.md +238 -238
  2. package/RELEASING.zh-CN.md +230 -230
  3. package/backend/dist/capture/recorder.js +2 -1
  4. package/backend/dist/cli/clients/base.js +8 -16
  5. package/backend/dist/cli/clients/dsh.js +8 -16
  6. package/backend/dist/cli/clients/pi.js +16 -9
  7. package/backend/dist/cli/types.d.ts +5 -0
  8. package/backend/dist/config/env.js +2 -1
  9. package/backend/dist/config/index.js +2 -0
  10. package/backend/dist/config/types.d.ts +23 -0
  11. package/backend/dist/harness/adapters/amp.d.ts +2 -0
  12. package/backend/dist/harness/adapters/amp.js +7 -0
  13. package/backend/dist/harness/adapters/claude.d.ts +2 -0
  14. package/backend/dist/harness/adapters/claude.js +7 -0
  15. package/backend/dist/harness/adapters/cline.d.ts +2 -0
  16. package/backend/dist/harness/adapters/cline.js +6 -0
  17. package/backend/dist/harness/adapters/codex.d.ts +2 -0
  18. package/backend/dist/harness/adapters/codex.js +6 -0
  19. package/backend/dist/harness/adapters/cursor.d.ts +5 -0
  20. package/backend/dist/harness/adapters/cursor.js +10 -0
  21. package/backend/dist/harness/adapters/declarative.d.ts +62 -0
  22. package/backend/dist/harness/adapters/declarative.js +202 -0
  23. package/backend/dist/harness/adapters/dsh.d.ts +5 -0
  24. package/backend/dist/harness/adapters/dsh.js +6 -0
  25. package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
  26. package/backend/dist/harness/adapters/gemini-cli.js +7 -0
  27. package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
  28. package/backend/dist/harness/adapters/github-copilot.js +10 -0
  29. package/backend/dist/harness/adapters/index.d.ts +44 -0
  30. package/backend/dist/harness/adapters/index.js +99 -0
  31. package/backend/dist/harness/adapters/opencode.d.ts +2 -0
  32. package/backend/dist/harness/adapters/opencode.js +55 -0
  33. package/backend/dist/harness/adapters/pi.d.ts +1 -0
  34. package/backend/dist/harness/adapters/pi.js +22 -0
  35. package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
  36. package/backend/dist/harness/adapters/skills-paths.js +17 -0
  37. package/backend/dist/harness/adapters/types.d.ts +174 -0
  38. package/backend/dist/harness/adapters/types.js +12 -0
  39. package/backend/dist/harness/adapters/universal.d.ts +6 -0
  40. package/backend/dist/harness/adapters/universal.js +10 -0
  41. package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
  42. package/backend/dist/harness/adapters/windsurf.js +10 -0
  43. package/backend/dist/harness/adapters/zed.d.ts +2 -0
  44. package/backend/dist/harness/adapters/zed.js +6 -0
  45. package/backend/dist/harness/awesome-opencode.d.ts +40 -0
  46. package/backend/dist/harness/awesome-opencode.js +75 -0
  47. package/backend/dist/harness/browse.d.ts +202 -0
  48. package/backend/dist/harness/browse.js +1214 -0
  49. package/backend/dist/harness/catalog-npm.d.ts +59 -0
  50. package/backend/dist/harness/catalog-npm.js +145 -0
  51. package/backend/dist/harness/clawhub.d.ts +212 -0
  52. package/backend/dist/harness/clawhub.js +426 -0
  53. package/backend/dist/harness/config-file.d.ts +29 -0
  54. package/backend/dist/harness/config-file.js +35 -0
  55. package/backend/dist/harness/detail.d.ts +74 -0
  56. package/backend/dist/harness/detail.js +330 -0
  57. package/backend/dist/harness/discover.d.ts +118 -0
  58. package/backend/dist/harness/discover.js +507 -0
  59. package/backend/dist/harness/drift.d.ts +21 -0
  60. package/backend/dist/harness/drift.js +25 -0
  61. package/backend/dist/harness/hash.d.ts +10 -0
  62. package/backend/dist/harness/hash.js +63 -0
  63. package/backend/dist/harness/hosts.d.ts +18 -0
  64. package/backend/dist/harness/hosts.js +15 -0
  65. package/backend/dist/harness/install.d.ts +88 -0
  66. package/backend/dist/harness/install.js +301 -0
  67. package/backend/dist/harness/inventory.d.ts +10 -0
  68. package/backend/dist/harness/inventory.js +198 -0
  69. package/backend/dist/harness/ledger.d.ts +39 -0
  70. package/backend/dist/harness/ledger.js +83 -0
  71. package/backend/dist/harness/maintenance.d.ts +115 -0
  72. package/backend/dist/harness/maintenance.js +603 -0
  73. package/backend/dist/harness/manifest.d.ts +31 -0
  74. package/backend/dist/harness/manifest.js +234 -0
  75. package/backend/dist/harness/net.d.ts +86 -0
  76. package/backend/dist/harness/net.js +113 -0
  77. package/backend/dist/harness/opencode-cafe.d.ts +40 -0
  78. package/backend/dist/harness/opencode-cafe.js +85 -0
  79. package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
  80. package/backend/dist/harness/opencode-ecosystem.js +246 -0
  81. package/backend/dist/harness/pi-dev.d.ts +81 -0
  82. package/backend/dist/harness/pi-dev.js +187 -0
  83. package/backend/dist/harness/probe.d.ts +33 -0
  84. package/backend/dist/harness/probe.js +85 -0
  85. package/backend/dist/harness/registry.d.ts +2 -0
  86. package/backend/dist/harness/registry.js +26 -0
  87. package/backend/dist/harness/scopes.d.ts +21 -0
  88. package/backend/dist/harness/scopes.js +22 -0
  89. package/backend/dist/harness/skill-md.d.ts +18 -0
  90. package/backend/dist/harness/skill-md.js +71 -0
  91. package/backend/dist/harness/skills-sh.d.ts +109 -0
  92. package/backend/dist/harness/skills-sh.js +178 -0
  93. package/backend/dist/harness/smithery.d.ts +64 -0
  94. package/backend/dist/harness/smithery.js +146 -0
  95. package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
  96. package/backend/dist/harness/sources/awesome-opencode.js +39 -0
  97. package/backend/dist/harness/sources/clawhub.d.ts +2 -0
  98. package/backend/dist/harness/sources/clawhub.js +83 -0
  99. package/backend/dist/harness/sources/github.d.ts +9 -0
  100. package/backend/dist/harness/sources/github.js +202 -0
  101. package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
  102. package/backend/dist/harness/sources/mcp-official.js +110 -0
  103. package/backend/dist/harness/sources/npm.d.ts +2 -0
  104. package/backend/dist/harness/sources/npm.js +152 -0
  105. package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
  106. package/backend/dist/harness/sources/opencode-cafe.js +41 -0
  107. package/backend/dist/harness/sources/smithery.d.ts +2 -0
  108. package/backend/dist/harness/sources/smithery.js +81 -0
  109. package/backend/dist/harness/spi.d.ts +98 -0
  110. package/backend/dist/harness/spi.js +8 -0
  111. package/backend/dist/harness/stars.d.ts +70 -0
  112. package/backend/dist/harness/stars.js +202 -0
  113. package/backend/dist/harness/translation.d.ts +142 -0
  114. package/backend/dist/harness/translation.js +567 -0
  115. package/backend/dist/harness/tree.d.ts +13 -0
  116. package/backend/dist/harness/tree.js +19 -0
  117. package/backend/dist/harness/types.d.ts +286 -0
  118. package/backend/dist/harness/types.js +8 -0
  119. package/backend/dist/harness/writers/extension.d.ts +116 -0
  120. package/backend/dist/harness/writers/extension.js +219 -0
  121. package/backend/dist/harness/writers/mcp.d.ts +72 -0
  122. package/backend/dist/harness/writers/mcp.js +195 -0
  123. package/backend/dist/harness/writers/skill.d.ts +60 -0
  124. package/backend/dist/harness/writers/skill.js +146 -0
  125. package/backend/dist/opencode/agents.d.ts +5 -0
  126. package/backend/dist/opencode/agents.js +10 -1
  127. package/backend/dist/opencode/catalog/cache.js +2 -1
  128. package/backend/dist/opencode/catalog/logos.js +2 -1
  129. package/backend/dist/opencode/catalog/ocr-store.js +2 -1
  130. package/backend/dist/opencode/catalog/overrides-store.js +2 -1
  131. package/backend/dist/opencode/credentials/factory.js +10 -27
  132. package/backend/dist/opencode/credentials/ocr-store.js +2 -1
  133. package/backend/dist/opencode/provider-defs.js +2 -1
  134. package/backend/dist/opencode/user-config.js +8 -16
  135. package/backend/dist/providers/registry.d.ts +15 -4
  136. package/backend/dist/providers/registry.js +29 -5
  137. package/backend/dist/providers/virtual-meta.d.ts +13 -0
  138. package/backend/dist/providers/virtual-meta.js +18 -0
  139. package/backend/dist/quota/store.js +2 -1
  140. package/backend/dist/resilience/breaker-state.js +2 -1
  141. package/backend/dist/resilience/credential-state.js +2 -1
  142. package/backend/dist/routes/console.js +137 -15
  143. package/backend/dist/routes/harness.d.ts +2 -0
  144. package/backend/dist/routes/harness.js +622 -0
  145. package/backend/dist/server.js +4 -0
  146. package/backend/dist/session/session-manager.js +2 -1
  147. package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
  148. package/backend/dist/surfaces/systemone-probe.js +74 -0
  149. package/backend/dist/utils/atomic-write.d.ts +12 -0
  150. package/backend/dist/utils/atomic-write.js +29 -0
  151. package/bin/ocr.js +2 -2
  152. package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
  153. package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
  154. package/frontend/dist/index.html +2 -2
  155. package/package.json +87 -87
  156. package/backend/dist/budget/budget-manager.d.ts +0 -25
  157. package/backend/dist/budget/budget-manager.js +0 -54
  158. package/backend/dist/config/governance-limits.d.ts +0 -68
  159. package/backend/dist/config/governance-limits.js +0 -261
  160. package/backend/dist/flywheel/collector.d.ts +0 -74
  161. package/backend/dist/flywheel/collector.js +0 -235
  162. package/backend/dist/flywheel/dataset.d.ts +0 -130
  163. package/backend/dist/flywheel/dataset.js +0 -638
  164. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  165. package/backend/dist/flywheel/decision-capture.js +0 -85
  166. package/backend/dist/flywheel/prune.d.ts +0 -133
  167. package/backend/dist/flywheel/prune.js +0 -495
  168. package/backend/dist/flywheel/schema.d.ts +0 -108
  169. package/backend/dist/flywheel/schema.js +0 -117
  170. package/backend/dist/flywheel/trainer.d.ts +0 -84
  171. package/backend/dist/flywheel/trainer.js +0 -198
  172. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  173. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  174. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  175. package/backend/dist/opencode/credentials/push.js +0 -116
  176. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  177. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  178. package/backend/dist/opencode/sync.d.ts +0 -29
  179. package/backend/dist/opencode/sync.js +0 -186
  180. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  181. package/backend/dist/pipeline/account-selection.js +0 -112
  182. package/backend/dist/providers/systemone.d.ts +0 -29
  183. package/backend/dist/providers/systemone.js +0 -170
  184. package/backend/dist/ratelimit/duration.d.ts +0 -24
  185. package/backend/dist/ratelimit/duration.js +0 -43
  186. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  187. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  188. package/backend/dist/ratelimit/index.d.ts +0 -4
  189. package/backend/dist/ratelimit/index.js +0 -4
  190. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  191. package/backend/dist/ratelimit/limiter.js +0 -244
  192. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  193. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  194. package/backend/dist/ratelimit/subject.d.ts +0 -26
  195. package/backend/dist/ratelimit/subject.js +0 -28
  196. package/backend/dist/resilience/account-state.d.ts +0 -84
  197. package/backend/dist/resilience/account-state.js +0 -228
  198. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  199. package/backend/dist/router/layer1-classifier.js +0 -467
  200. package/backend/dist/router/layer2-judge.d.ts +0 -111
  201. package/backend/dist/router/layer2-judge.js +0 -373
  202. package/backend/dist/router/retry-escalation.d.ts +0 -89
  203. package/backend/dist/router/retry-escalation.js +0 -99
  204. package/backend/dist/routes/flywheel.d.ts +0 -3
  205. package/backend/dist/routes/flywheel.js +0 -268
  206. package/backend/dist/routes/systemone.d.ts +0 -3
  207. package/backend/dist/routes/systemone.js +0 -90
  208. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  209. package/backend/dist/surfaces/governance-envelope.js +0 -47
  210. package/backend/dist/utils/token-estimator.d.ts +0 -7
  211. package/backend/dist/utils/token-estimator.js +0 -20
  212. package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
@@ -0,0 +1,603 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { getOcrHomeDir } from '../cli/paths.js';
5
+ import { resolveEnvName } from '../config/env.js';
6
+ import { readConfigJson, writeConfigJson } from './config-file.js';
7
+ import { parseExtensionSpec } from './discover.js';
8
+ import { HOST_ADAPTERS, adapterFor, isExtensionHost, isMcpHost } from './adapters/index.js';
9
+ import { skillRoots } from './inventory.js';
10
+ import { claimOwner, readManifest, releaseClaim, writeManifest } from './manifest.js';
11
+ import { recordApply } from './ledger.js';
12
+ import { copyDrift } from './drift.js';
13
+ const PLAN_TTL_MS = 10 * 60_000;
14
+ const plans = new Map();
15
+ /**
16
+ * Match a requested target against a recorded copy.
17
+ *
18
+ * An `external` copy's `path` is an identity token (`<canonicalKey>#<harness>`), NOT a location:
19
+ * `path.resolve` would prepend the process cwd and turn the match into a cwd-dependent guess — the
20
+ * same plan would prune the record from one directory and refuse it from another. Tokens are
21
+ * therefore compared verbatim; real paths keep the resolved comparison (both sides normalized).
22
+ */
23
+ function matchesCopy(copy, targetPath) {
24
+ return copy.external === true ? copy.path === targetPath : path.resolve(copy.path) === path.resolve(targetPath);
25
+ }
26
+ /** Recorded form of a copy path: token as-is, real path resolved — the single key for `removed`. */
27
+ function copyKey(copy) {
28
+ return copy.external === true ? copy.path : path.resolve(copy.path);
29
+ }
30
+ function trashRoot() {
31
+ return path.join(getOcrHomeDir(), 'harness', 'trash');
32
+ }
33
+ /**
34
+ * Directories a `trash-path` removal may touch: the known skills roots plus every extension loose
35
+ * directory the host catalog declares.
36
+ *
37
+ * The descriptor arrives from the console, so it cannot be trusted on its own — without this guard a
38
+ * crafted request could name any path on disk and move it. It is a containment rule, not a
39
+ * provenance rule: both roots accept a copy the manifest has never heard of.
40
+ */
41
+ function removableRoots(projectRoot = process.cwd()) {
42
+ const out = new Set(skillRoots(projectRoot).map((r) => path.resolve(r.root)));
43
+ // Every extension loose directory the adapters declare, for BOTH scopes and every spelling in a
44
+ // host's version ladder (opencode v2 `plugins/`, v1 `plugin/`) — a discovered loose file is
45
+ // removable only when its directory is one of these.
46
+ //
47
+ // BOTH scopes stay in this guard while project INSTALL is disabled (ADR-0015 §D2 "Scope"): a copy
48
+ // that landed inside a repo before that gate existed is still recorded in the manifest, and losing
49
+ // the ability to remove it would strand real state on disk.
50
+ const ctx = { projectRoot };
51
+ for (const adapter of HOST_ADAPTERS) {
52
+ if (!isExtensionHost(adapter))
53
+ continue;
54
+ for (const scope of ['global', 'project']) {
55
+ for (const dir of adapter.looseDirs(ctx, scope))
56
+ out.add(path.resolve(dir));
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+ function fingerprint(abs) {
62
+ try {
63
+ const stat = fs.statSync(abs);
64
+ return { mtimeMs: stat.mtimeMs, bytes: stat.size };
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ function pruneExpired() {
71
+ const now = Date.now();
72
+ for (const [id, plan] of plans) {
73
+ if (now - plan.createdAt > PLAN_TTL_MS)
74
+ plans.delete(id);
75
+ }
76
+ }
77
+ /**
78
+ * Where a tracked copy actually landed, when that landing is a CONFIG FILE rather than a path of our
79
+ * own.
80
+ *
81
+ * Answered from the KIND + the host adaptation, never by re-resolving the landing against this
82
+ * process's cwd: `adapter.configPath` / `adapter.writeTarget` answer for the CURRENT working directory,
83
+ * while the copy was written under whatever root the install named — comparing them would mark a
84
+ * project-scope copy as "not a config" and trash the runtime's whole configuration.
85
+ *
86
+ * By construction every MCP copy and every non-`external` extension copy IS a config member: the
87
+ * writers have no other landing for those shapes.
88
+ */
89
+ function configLanding(copy, artifact) {
90
+ const abs = path.resolve(copy.path);
91
+ if (artifact.kind === 'mcp') {
92
+ // The MCP writer merges the artifact's name as the server key inside the adapter's container.
93
+ const adapter = adapterFor(copy.host);
94
+ return { file: abs, containers: [isMcpHost(adapter) ? adapter.container : 'mcp'], serverKey: artifact.name };
95
+ }
96
+ if (artifact.kind === 'extension') {
97
+ // A package-manager landing is recorded `external` (a token, handled before this point); a
98
+ // non-external extension copy can only be a config-array member. Every container spelling the
99
+ // host's adapter declares is tried: the copy may predate a key rename (`plugin` → `plugins`).
100
+ const adapter = adapterFor(copy.host);
101
+ const containers = isExtensionHost(adapter) ? adapter.containers() : [];
102
+ if (containers.length === 0)
103
+ return null;
104
+ return { file: abs, containers };
105
+ }
106
+ return null;
107
+ }
108
+ /**
109
+ * The declaration files a package-manager landing reads (pi's `settings.json`), when the adapter
110
+ * names any. The first EXISTING file wins: a version ladder may list a v2 path and a legacy fallback.
111
+ */
112
+ function declaredFile(host) {
113
+ const adapter = adapterFor(host);
114
+ const declarations = isExtensionHost(adapter) ? adapter.declarations() : [];
115
+ if (declarations.length === 0)
116
+ return null;
117
+ const chosen = declarations.find((d) => fs.existsSync(d.file)) ?? declarations[0];
118
+ return { file: chosen.file, container: chosen.key };
119
+ }
120
+ /**
121
+ * Array members that still carry this artifact.
122
+ *
123
+ * The exact rule is the canonicalKey. It cannot be the only rule: a `manual:` artifact's key names
124
+ * the package the way the operator typed it, while the array holds the grammar the runtime writes
125
+ * (`npm:<name>`), so the recorded display NAME is the fallback — and it only applies when no exact
126
+ * match exists, so two scoped packages that share a short name are never both removed.
127
+ *
128
+ * Empty = the runtime already forgot the install, so the record is all that is left to prune;
129
+ * `null` = the file cannot be parsed, and a JSON rewrite would be lossy — refused, never guessed.
130
+ */
131
+ function matchingEntries(file, containers, artifact) {
132
+ if (!fs.existsSync(file))
133
+ return [];
134
+ const parsed = readConfigJson(file);
135
+ if (!parsed.ok)
136
+ return null;
137
+ const found = [];
138
+ for (const container of containers) {
139
+ const arr = parsed.config[container];
140
+ if (!Array.isArray(arr))
141
+ continue;
142
+ const entries = arr.filter((entry) => typeof entry === 'string');
143
+ const exact = entries.filter((entry) => parseExtensionSpec(entry)?.canonicalKey === artifact.canonicalKey);
144
+ const chosen = exact.length > 0
145
+ ? exact
146
+ : entries.filter((entry) => {
147
+ const spec = parseExtensionSpec(entry);
148
+ return entry === artifact.name || spec?.name === artifact.name;
149
+ });
150
+ if (chosen.length > 0)
151
+ found.push({ container, entries: chosen });
152
+ }
153
+ return found;
154
+ }
155
+ /** Build a dry-run removal plan over one or more artifacts. Writes nothing. */
156
+ export function planRemove(items) {
157
+ pruneExpired();
158
+ const manifest = readManifest();
159
+ const roots = new Set(skillRoots().map((r) => path.resolve(r.root)));
160
+ const envName = resolveEnvName();
161
+ const actions = [];
162
+ const blocked = [];
163
+ const warnings = [];
164
+ const external = [];
165
+ const artifactIds = new Set();
166
+ for (const item of items) {
167
+ const artifact = item.artifactId
168
+ ? manifest.artifacts.find((a) => a.id === item.artifactId)
169
+ : undefined;
170
+ if (item.artifactId && !artifact) {
171
+ blocked.push({ path: '', code: 'not-found', message: `unknown artifact '${item.artifactId}'` });
172
+ continue;
173
+ }
174
+ if (artifact)
175
+ artifactIds.add(artifact.id);
176
+ // A discovered row: the runtime's own record IS the target, so the descriptor decides the op and
177
+ // there is no copy of ours to reconcile.
178
+ if (item.removal) {
179
+ const removal = item.removal;
180
+ if (removal.op === 'trash-path') {
181
+ const abs = path.resolve(removal.path);
182
+ if (!removableRoots().has(path.dirname(abs))) {
183
+ blocked.push({ path: abs, code: 'not-found', message: 'not directly under a known artifact root' });
184
+ continue;
185
+ }
186
+ const owner = claimOwner(abs);
187
+ if (owner && owner !== envName) {
188
+ blocked.push({ path: abs, code: 'foreign', message: `owned by environment '${owner}'` });
189
+ continue;
190
+ }
191
+ if (!fs.existsSync(abs)) {
192
+ blocked.push({ path: abs, code: 'not-found', message: 'file does not exist' });
193
+ continue;
194
+ }
195
+ actions.push({
196
+ op: 'move-to-trash',
197
+ path: abs,
198
+ host: item.copies[0]?.host ?? '',
199
+ artifactId: null,
200
+ dirty: false,
201
+ exists: true,
202
+ });
203
+ continue;
204
+ }
205
+ const parsed = fs.existsSync(removal.file) ? readConfigJson(removal.file) : null;
206
+ if (parsed === null) {
207
+ blocked.push({ path: removal.file, code: 'not-found', message: 'config file does not exist' });
208
+ continue;
209
+ }
210
+ if (!parsed.ok) {
211
+ blocked.push({ path: removal.file, code: 'unreadable', message: parsed.reason });
212
+ continue;
213
+ }
214
+ // Two config shapes, one rule: the descriptor names the member and the container it was ACTUALLY
215
+ // found in. `drop-entry` empties an array slot; `drop-server` drops an object member (an MCP
216
+ // server key), and its siblings keep their place.
217
+ const container = parsed.config[removal.container];
218
+ const isServer = removal.op === 'drop-server';
219
+ const present = isServer
220
+ ? !!container && typeof container === 'object' && !Array.isArray(container) && removal.entry in container
221
+ : Array.isArray(container) && container.includes(removal.entry);
222
+ if (!present) {
223
+ blocked.push({
224
+ path: removal.file,
225
+ code: 'not-found',
226
+ message: `'${removal.entry}' is no longer in ${removal.container}${isServer ? '' : '[]'}`,
227
+ });
228
+ continue;
229
+ }
230
+ actions.push({
231
+ op: removal.op,
232
+ path: path.resolve(removal.file),
233
+ file: removal.file,
234
+ container: removal.container,
235
+ entry: removal.entry,
236
+ host: item.copies[0]?.host ?? '',
237
+ artifactId: null,
238
+ dirty: false,
239
+ exists: true,
240
+ });
241
+ continue;
242
+ }
243
+ for (const target of item.copies) {
244
+ // Identity-token copies are matched VERBATIM (before any `path.resolve`), so the plan never
245
+ // depends on the process cwd — see `matchesCopy`.
246
+ const copy = artifact?.copies.find((c) => matchesCopy(c, target.path));
247
+ if (artifact && !copy) {
248
+ blocked.push({ path: target.path, code: 'unknown-copy', message: 'not a copy recorded for this artifact' });
249
+ continue;
250
+ }
251
+ // Package-manager-owned copy: `path` is an identity token and no claim exists. Its real undo is
252
+ // the runtime's own declaration (`settings.json` `packages[]`), so the plan drops that entry
253
+ // when the host catalog names the file — the same op a discovered row of the same package gets.
254
+ if (copy?.external === true) {
255
+ const declared = declaredFile(copy.host);
256
+ const keys = declared && artifact ? matchingEntries(declared.file, [declared.container], artifact) : null;
257
+ if (declared && keys === null && artifact) {
258
+ blocked.push({ path: declared.file, code: 'unreadable', message: `cannot parse ${declared.file}; refusing a lossy rewrite` });
259
+ continue;
260
+ }
261
+ if (declared && keys && keys.length > 0 && artifact) {
262
+ for (const group of keys) {
263
+ for (const entry of group.entries) {
264
+ actions.push({
265
+ op: 'drop-entry',
266
+ path: copy.path,
267
+ file: declared.file,
268
+ container: group.container,
269
+ entry,
270
+ host: copy.host,
271
+ artifactId: item.artifactId ?? null,
272
+ dirty: false,
273
+ // The token is not a location: nothing to stat, and the apply must not fingerprint it.
274
+ exists: false,
275
+ });
276
+ }
277
+ }
278
+ external.push({ path: copy.path, host: copy.host });
279
+ continue;
280
+ }
281
+ actions.push({
282
+ op: 'prune-record',
283
+ path: copy.path,
284
+ host: copy.host,
285
+ artifactId: item.artifactId ?? null,
286
+ dirty: false,
287
+ exists: false,
288
+ });
289
+ external.push({ path: copy.path, host: copy.host });
290
+ continue;
291
+ }
292
+ const abs = path.resolve(target.path);
293
+ if (!artifact && !roots.has(path.dirname(abs))) {
294
+ blocked.push({ path: abs, code: 'not-found', message: 'not directly under a known skills root' });
295
+ continue;
296
+ }
297
+ const owner = claimOwner(abs);
298
+ if (owner && owner !== envName) {
299
+ blocked.push({ path: abs, code: 'foreign', message: `owned by environment '${owner}'` });
300
+ continue;
301
+ }
302
+ // A config landing is edited member-by-member: trashing the file would take every other
303
+ // server/plugin recorded in it with it (ADR-0015 §D5).
304
+ const landing = copy && artifact ? configLanding(copy, artifact) : null;
305
+ if (landing && artifact) {
306
+ // The file is gone: nothing to edit, so the record is all that is left.
307
+ if (!fs.existsSync(landing.file)) {
308
+ actions.push({
309
+ op: 'prune-only',
310
+ path: abs,
311
+ host: copy.host,
312
+ artifactId: item.artifactId ?? null,
313
+ beforeHash: copy.contentHash,
314
+ dirty: false,
315
+ exists: false,
316
+ });
317
+ continue;
318
+ }
319
+ if (landing.serverKey) {
320
+ const parsed = readConfigJson(landing.file);
321
+ if (!parsed.ok) {
322
+ blocked.push({ path: landing.file, code: 'unreadable', message: parsed.reason });
323
+ continue;
324
+ }
325
+ const container = parsed.config[landing.containers[0]];
326
+ const present = !!container && typeof container === 'object' && !Array.isArray(container) &&
327
+ landing.serverKey in container;
328
+ actions.push({
329
+ op: present ? 'drop-server' : 'prune-only',
330
+ path: abs,
331
+ file: landing.file,
332
+ container: landing.containers[0],
333
+ entry: landing.serverKey,
334
+ host: copy.host,
335
+ artifactId: item.artifactId ?? null,
336
+ beforeHash: copy.contentHash,
337
+ dirty: false,
338
+ // `prune-only` moves NOTHING (apply would rename anything marked `exists`), so only the
339
+ // drop op keeps the true flag — it needs it for the stale check, not for a move.
340
+ exists: present,
341
+ });
342
+ continue;
343
+ }
344
+ const keys = matchingEntries(landing.file, landing.containers, artifact);
345
+ if (keys === null) {
346
+ blocked.push({ path: landing.file, code: 'unreadable', message: `cannot parse ${landing.file}; refusing a lossy rewrite` });
347
+ continue;
348
+ }
349
+ if (keys.length === 0) {
350
+ // The runtime's array no longer holds this spec (hand-removed, or version drift): the only
351
+ // thing left is our record, and `prune-only` is exactly that claim. `exists: false` because
352
+ // a prune performs no filesystem op — the config file must survive untouched.
353
+ actions.push({
354
+ op: 'prune-only',
355
+ path: abs,
356
+ host: copy.host,
357
+ artifactId: item.artifactId ?? null,
358
+ beforeHash: copy.contentHash,
359
+ dirty: false,
360
+ exists: false,
361
+ });
362
+ continue;
363
+ }
364
+ for (const group of keys) {
365
+ for (const entry of group.entries) {
366
+ actions.push({
367
+ op: 'drop-entry',
368
+ path: abs,
369
+ file: landing.file,
370
+ container: group.container,
371
+ entry,
372
+ host: copy.host,
373
+ artifactId: item.artifactId ?? null,
374
+ beforeHash: copy.contentHash,
375
+ dirty: false,
376
+ exists: true,
377
+ });
378
+ }
379
+ }
380
+ continue;
381
+ }
382
+ const exists = fs.existsSync(abs);
383
+ if (!exists && !copy) {
384
+ blocked.push({ path: abs, code: 'not-found', message: 'directory does not exist' });
385
+ continue;
386
+ }
387
+ let dirty = false;
388
+ if (exists && copy) {
389
+ try {
390
+ // `copyDrift` picks the hash the WRITER used for this copy's shape (file vs directory);
391
+ // hashing a config file as a tree would report every MCP/plugin copy as edited.
392
+ dirty = copyDrift(copy, abs);
393
+ }
394
+ catch {
395
+ dirty = true;
396
+ }
397
+ }
398
+ actions.push({
399
+ op: exists ? 'move-to-trash' : 'prune-only',
400
+ path: abs,
401
+ host: copy?.host ?? target.host,
402
+ artifactId: item.artifactId ?? null,
403
+ beforeHash: copy?.contentHash,
404
+ dirty,
405
+ exists,
406
+ });
407
+ if (dirty)
408
+ warnings.push({ code: 'dirty-copy', message: 'copy has local edits', path: abs });
409
+ }
410
+ }
411
+ if (actions.length === 0)
412
+ return { error: blocked[0]?.message ?? 'nothing to remove' };
413
+ const planId = crypto
414
+ .createHash('sha256')
415
+ .update(`${[...artifactIds].join(',')}|${actions.map((a) => a.path).join('|')}|${Date.now()}`)
416
+ .digest('hex')
417
+ .slice(0, 24);
418
+ const plan = {
419
+ planId,
420
+ action: 'remove',
421
+ artifactIds: [...artifactIds],
422
+ actions,
423
+ external,
424
+ blocked,
425
+ warnings,
426
+ createdAt: Date.now(),
427
+ };
428
+ plans.set(planId, plan);
429
+ return plan;
430
+ }
431
+ /** Remove one string from a JSON array, refusing anything a JSON round-trip would mangle. */
432
+ function applyDropEntry(file, container, entry) {
433
+ const parsed = readConfigJson(file);
434
+ if (!parsed.ok)
435
+ return { ok: false, reason: parsed.reason };
436
+ const arr = parsed.config[container];
437
+ if (!Array.isArray(arr))
438
+ return { ok: false, reason: `${container} is not an array in ${file}` };
439
+ const next = arr.filter((value) => value !== entry);
440
+ if (next.length === arr.length)
441
+ return { ok: false, reason: `'${entry}' is no longer in ${container}[]` };
442
+ parsed.config[container] = next;
443
+ return writeConfigJson(file, parsed.config);
444
+ }
445
+ /** Delete one member of a JSON object (an MCP server inside `mcp`). */
446
+ function applyDropServer(file, container, serverKey) {
447
+ const parsed = readConfigJson(file);
448
+ if (!parsed.ok)
449
+ return { ok: false, reason: parsed.reason };
450
+ const obj = parsed.config[container];
451
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
452
+ return { ok: false, reason: `${container} is not an object in ${file}` };
453
+ }
454
+ if (!(serverKey in obj)) {
455
+ return { ok: false, reason: `'${serverKey}' is no longer in ${container}` };
456
+ }
457
+ delete obj[serverKey];
458
+ return writeConfigJson(file, parsed.config);
459
+ }
460
+ /**
461
+ * Honest wording shared by the apply result and the ledger row.
462
+ *
463
+ * `declared` distinguishes the two real outcomes: the runtime's own declaration was edited (the
464
+ * package stops loading, the bytes stay), or no declaration file exists and only this gateway's
465
+ * record could be dropped. Neither is "uninstalled from disk", and naming a `pi uninstall` / `npm
466
+ * uninstall` command would invent a contract this gateway does not own.
467
+ */
468
+ function externalPruneMessage(count, declared) {
469
+ return declared
470
+ ? `removed ${count} package declaration(s) from the runtime's own config; the package bytes stay in its store`
471
+ : `pruned ${count} package-manager-owned record(s); no declaration file was found, so the package is untouched`;
472
+ }
473
+ /**
474
+ * Execute a removal plan. The manifest is written only after every filesystem write succeeded, so a
475
+ * failure leaves the artifacts recorded rather than orphaned.
476
+ *
477
+ * `drop-entry` / `drop-server` edit a runtime's config file through `createBackup` + `safeWriteJson`
478
+ * — the same discipline that wrote the member — and never release the path's claim: the file still
479
+ * exists and commonly holds other artifacts' members.
480
+ */
481
+ export function applyRemove(planId, opts = {}) {
482
+ pruneExpired();
483
+ const plan = plans.get(planId);
484
+ if (!plan)
485
+ return { ok: false, code: 'plan_unknown', message: 'plan expired or never existed' };
486
+ for (const action of plan.actions) {
487
+ if (!action.exists)
488
+ continue;
489
+ const fp = fingerprint(action.path);
490
+ if (!fp)
491
+ return { ok: false, code: 'plan_stale', message: `${action.path} disappeared after planning` };
492
+ }
493
+ if (plan.warnings.length > 0 && !opts.discardLocalEdits) {
494
+ return {
495
+ ok: false,
496
+ code: 'dirty_copy',
497
+ message: 'copies have local edits — resend with discardLocalEdits to move them to trash anyway',
498
+ };
499
+ }
500
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
501
+ const trashDir = path.join(trashRoot(), `${stamp}-${plan.planId.slice(0, 8)}`);
502
+ const removed = [];
503
+ let moved = false;
504
+ let dropEntryCount = 0;
505
+ let dropServerCount = 0;
506
+ for (const action of plan.actions) {
507
+ if (action.op === 'drop-entry' || action.op === 'drop-server') {
508
+ const result = action.op === 'drop-entry'
509
+ ? applyDropEntry(action.file, action.container, action.entry)
510
+ : applyDropServer(action.file, action.container, action.entry);
511
+ if (!result.ok) {
512
+ // Earlier moves stay in the trash (recoverable) and the manifest is NOT pruned, so the record
513
+ // still points at what happened — the same failure discipline the move path already had.
514
+ return { ok: false, code: 'apply_failed', message: `${action.file}: ${result.reason}` };
515
+ }
516
+ if (action.op === 'drop-entry')
517
+ dropEntryCount += 1;
518
+ else
519
+ dropServerCount += 1;
520
+ removed.push(action.path);
521
+ continue;
522
+ }
523
+ if (action.op !== 'prune-record') {
524
+ if (action.exists) {
525
+ fs.mkdirSync(trashDir, { recursive: true });
526
+ // The host label is caller-shaped (a discovered row's descriptor carries it), so it is
527
+ // flattened to a safe file-name token before it joins the trash path — a `../` in it would
528
+ // otherwise land the moved directory outside the trash.
529
+ const hostTag = action.host.replace(/[^\w.-]+/g, '-') || 'unknown';
530
+ const dest = path.join(trashDir, `${hostTag}-${path.basename(action.path)}`);
531
+ try {
532
+ fs.renameSync(action.path, dest);
533
+ }
534
+ catch {
535
+ // Cross-device or locked target: copy then remove, still reversible via trash.
536
+ fs.cpSync(action.path, dest, { recursive: true });
537
+ fs.rmSync(action.path, { recursive: true, force: true });
538
+ }
539
+ moved = true;
540
+ }
541
+ // The claim belongs to the PATH, so it is released only when the path itself was destroyed.
542
+ // A config member edit leaves the file in place (and it usually holds other artifacts), and a
543
+ // prune touches nothing at all.
544
+ if (action.op === 'move-to-trash')
545
+ releaseClaim(action.path);
546
+ }
547
+ removed.push(action.path);
548
+ }
549
+ const manifest = readManifest();
550
+ // Snapshot the records BEFORE pruning: the ledger row needs kind/name, which the pruned manifest
551
+ // no longer carries.
552
+ const applied = plan.artifactIds
553
+ .map((id) => manifest.artifacts.find((artifact) => artifact.id === id))
554
+ .filter((artifact) => artifact !== undefined);
555
+ const prunedArtifacts = [];
556
+ manifest.artifacts = manifest.artifacts
557
+ .map((artifact) => {
558
+ if (!plan.artifactIds.includes(artifact.id))
559
+ return artifact;
560
+ // `removed` holds the same key form as the recorded copies: a resolved path for a real copy,
561
+ // the identity token verbatim for a config / `prune-record` action — so an external copy drops
562
+ // out of the record the same way, with no cwd dependency on either side.
563
+ const remaining = artifact.copies.filter((copy) => !removed.includes(copyKey(copy)));
564
+ if (remaining.length === 0) {
565
+ prunedArtifacts.push(artifact.id);
566
+ return { ...artifact, copies: [] };
567
+ }
568
+ return { ...artifact, copies: remaining };
569
+ })
570
+ .filter((artifact) => artifact.copies.length > 0);
571
+ writeManifest(manifest);
572
+ plans.delete(planId);
573
+ for (const artifact of applied) {
574
+ const touched = plan.actions.filter((action) => action.artifactId === artifact.id);
575
+ if (touched.length === 0)
576
+ continue;
577
+ const ops = new Set(touched.map((action) => action.op));
578
+ const message = ops.size === 1 && ops.has('prune-record')
579
+ ? externalPruneMessage(touched.length, false)
580
+ : ops.size === 1 && (ops.has('drop-entry') || ops.has('drop-server'))
581
+ ? `removed ${touched.length} config member(s)`
582
+ : `removed ${touched.length} copy record(s)`;
583
+ recordApply({
584
+ action: 'remove',
585
+ kind: artifact.kind,
586
+ artifactId: artifact.id,
587
+ name: artifact.name,
588
+ hosts: [...new Set(touched.map((action) => action.host))],
589
+ outcome: 'ok',
590
+ message,
591
+ });
592
+ }
593
+ const parts = [];
594
+ if (dropEntryCount + dropServerCount > 0) {
595
+ parts.push(`removed ${dropEntryCount + dropServerCount} config member(s); the file keeps its other entries`);
596
+ }
597
+ if (plan.external.length > 0) {
598
+ const declared = plan.actions.some((action) => action.op === 'drop-entry' && action.exists === false);
599
+ parts.push(externalPruneMessage(plan.external.length, declared));
600
+ }
601
+ const message = parts.length > 0 ? parts.join('; ') : undefined;
602
+ return { ok: true, removed, trashDir: moved ? trashDir : null, prunedArtifacts, ...(message ? { message } : {}) };
603
+ }
@@ -0,0 +1,31 @@
1
+ import type { ArtifactRecord, ClaimsFile, ManifestFile } from './types.js';
2
+ export declare function harnessEnvDir(): string;
3
+ export declare function manifestPath(): string;
4
+ /** Retirement file for v1 extension records that carry no host (see `migrateV1`). */
5
+ export declare function orphansPath(): string;
6
+ /** One retired record plus when it was retired — the append-only audit trail behind the migration. */
7
+ export interface ManifestOrphan {
8
+ migratedAt: string;
9
+ record: ArtifactRecord;
10
+ }
11
+ export declare function claimsPath(): string;
12
+ export declare function readManifest(): ManifestFile;
13
+ export declare function writeManifest(data: ManifestFile): void;
14
+ export declare function readClaims(): ClaimsFile;
15
+ export declare function writeClaims(data: ClaimsFile): void;
16
+ export type ClaimVerdict = {
17
+ ok: true;
18
+ } | {
19
+ ok: false;
20
+ reason: 'foreign';
21
+ env: string;
22
+ artifactId: string;
23
+ };
24
+ /** Can the active environment own this path? */
25
+ export declare function canClaim(absPath: string, envName?: string): ClaimVerdict;
26
+ /** Register a claim; refuses to steal another environment's path. */
27
+ export declare function claimPath(absPath: string, artifactId: string, envName?: string): ClaimVerdict;
28
+ export declare function releaseClaim(absPath: string, envName?: string): void;
29
+ /** Environment a path is claimed by, if any. */
30
+ export declare function claimOwner(absPath: string): string | null;
31
+ export declare function findArtifact(artifactId: string): ArtifactRecord | undefined;