@aviaratech/ai-delivery 0.3.29 → 0.3.31

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 (54) hide show
  1. package/README.md +43 -4
  2. package/dist/cli.js +11 -6
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cliResult.d.ts +1 -0
  5. package/dist/cliResult.js +8 -0
  6. package/dist/cliResult.js.map +1 -1
  7. package/dist/cliResult.test.js +176 -0
  8. package/dist/cliResult.test.js.map +1 -1
  9. package/dist/errors.d.ts +19 -0
  10. package/dist/errors.js +52 -0
  11. package/dist/errors.js.map +1 -1
  12. package/dist/github/client.d.ts +5 -0
  13. package/dist/github/client.js +142 -6
  14. package/dist/github/client.js.map +1 -1
  15. package/dist/github/machineAuth.test.js +284 -1
  16. package/dist/github/machineAuth.test.js.map +1 -1
  17. package/dist/issue.d.ts +2 -0
  18. package/dist/issue.js +2 -0
  19. package/dist/issue.js.map +1 -1
  20. package/dist/issueInfoReadback.test.d.ts +1 -0
  21. package/dist/issueInfoReadback.test.js +203 -0
  22. package/dist/issueInfoReadback.test.js.map +1 -0
  23. package/dist/lifecycle.test.js +72 -6
  24. package/dist/lifecycle.test.js.map +1 -1
  25. package/dist/pluginAuthProbe.test.js +25 -0
  26. package/dist/pluginAuthProbe.test.js.map +1 -1
  27. package/dist/pluginDoctor.test.js +21 -3
  28. package/dist/pluginDoctor.test.js.map +1 -1
  29. package/dist/pluginInstaller.d.ts +22 -0
  30. package/dist/pluginInstaller.js +378 -57
  31. package/dist/pluginInstaller.js.map +1 -1
  32. package/dist/pluginInstaller.test.js +745 -31
  33. package/dist/pluginInstaller.test.js.map +1 -1
  34. package/dist/pr.d.ts +1 -1
  35. package/dist/pr.js +85 -27
  36. package/dist/pr.js.map +1 -1
  37. package/dist/pr.test.js +223 -5
  38. package/dist/pr.test.js.map +1 -1
  39. package/dist/prAssociation.test.js +509 -2
  40. package/dist/prAssociation.test.js.map +1 -1
  41. package/dist/review.js +11 -0
  42. package/dist/review.js.map +1 -1
  43. package/dist/review.test.js +38 -0
  44. package/dist/review.test.js.map +1 -1
  45. package/dist/setup.test.js +489 -4
  46. package/dist/setup.test.js.map +1 -1
  47. package/dist/targetPolicyLocal.test.js +574 -167
  48. package/dist/targetPolicyLocal.test.js.map +1 -1
  49. package/package.json +1 -1
  50. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  51. package/plugins/ai-delivery/README.md +7 -1
  52. package/plugins/ai-delivery/plugin.json +1 -1
  53. package/plugins/ai-delivery/runtime/dist/cli.js +57 -57
  54. package/plugins/ai-delivery/runtime/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { existsSync, closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
2
+ import { existsSync, constants, fstatSync, closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, dirname, join, resolve } from 'node:path';
5
5
  import { gunzipSync } from 'node:zlib';
@@ -18,7 +18,7 @@ const Version = z
18
18
  .max(128)
19
19
  .regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u);
20
20
  const InputSchema = z.strictObject({
21
- action: z.enum(['install', 'doctor', 'update', 'rollback', 'remove']),
21
+ action: z.enum(['install', 'doctor', 'preview', 'update', 'rollback', 'remove']),
22
22
  host: z.enum(['codex', 'claude-code']),
23
23
  scope: z.enum(['user', 'project', 'local']),
24
24
  version: Version.optional(),
@@ -73,6 +73,171 @@ const Unit = z.strictObject({
73
73
  files: z.record(z.string(), z.string().regex(/^[a-f0-9]{64}$/u)),
74
74
  });
75
75
  const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
76
+ function sourceDiagnostics(input, target) {
77
+ const report = {
78
+ completeness: 'incomplete',
79
+ registrations: [],
80
+ nativeInventory: 'not_checked',
81
+ plannedChanges: [],
82
+ migration: 'refused',
83
+ findings: ['native_session_scope_unverified', 'settings_preservation_unproved', 'native_writer_exclusion_unproved'],
84
+ };
85
+ const text = (path) => {
86
+ let descriptor;
87
+ try {
88
+ assertCanonical(path);
89
+ if (!existsSync(path))
90
+ return undefined;
91
+ const metadata = lstatSync(path);
92
+ if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > 1024 * 1024)
93
+ throw new Error('Unsafe configuration');
94
+ // Nonblocking open also protects against replacement with a FIFO between
95
+ // lstat and open; descriptor validation remains authoritative.
96
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
97
+ const info = fstatSync(descriptor);
98
+ if (!info.isFile() || info.nlink !== 1 || info.size > 1024 * 1024)
99
+ throw new Error('Unsafe configuration');
100
+ const bytes = Buffer.alloc(1024 * 1024 + 1);
101
+ let size = 0;
102
+ while (size < bytes.length) {
103
+ const count = readSync(descriptor, bytes, size, bytes.length - size, null);
104
+ if (count === 0)
105
+ break;
106
+ size += count;
107
+ }
108
+ if (size > 1024 * 1024)
109
+ throw new Error('Configuration exceeded read limit');
110
+ return bytes.subarray(0, size).toString('utf8');
111
+ }
112
+ catch {
113
+ report.findings.push('configuration_unavailable');
114
+ return undefined;
115
+ }
116
+ finally {
117
+ if (descriptor !== undefined)
118
+ closeSync(descriptor);
119
+ }
120
+ };
121
+ const json = (path) => {
122
+ const value = text(path);
123
+ if (value === undefined)
124
+ return undefined;
125
+ try {
126
+ const parsed = JSON.parse(value);
127
+ return z.record(z.string(), z.unknown()).parse(parsed);
128
+ }
129
+ catch {
130
+ report.findings.push('configuration_unavailable');
131
+ return undefined;
132
+ }
133
+ };
134
+ const observe = (scope, servers) => {
135
+ if (typeof servers !== 'object' || servers === null || Array.isArray(servers)) {
136
+ if (servers !== undefined)
137
+ report.findings.push('configuration_unavailable');
138
+ return;
139
+ }
140
+ // Names and launcher text identify candidates, never ownership. Nothing from
141
+ // command arguments, URLs, environments or permission values reaches output.
142
+ const candidate = Object.entries(servers).some(([name, value]) => {
143
+ if (name === 'ai-delivery')
144
+ return true;
145
+ if (typeof value !== 'object' || value === null)
146
+ return false;
147
+ const entry = value;
148
+ return (entry.command === 'ai-delivery' ||
149
+ (Array.isArray(entry.args) &&
150
+ entry.args.some((arg) => typeof arg === 'string' && arg.includes('@aviaratech/ai-delivery'))));
151
+ });
152
+ if (candidate)
153
+ report.registrations.push({
154
+ kind: 'standalone',
155
+ scope,
156
+ ownership: 'unknown',
157
+ source: 'unknown',
158
+ version: null,
159
+ enabled: null,
160
+ });
161
+ };
162
+ if (input.host === 'claude-code') {
163
+ if (process.env.CLAUDE_CONFIG_DIR) {
164
+ report.findings.push('custom_profile_configuration_unverified');
165
+ }
166
+ else {
167
+ const user = json(join(realpathSync(homedir()), '.claude.json'));
168
+ const projects = user?.projects;
169
+ if (typeof projects === 'object' && projects !== null && !Array.isArray(projects)) {
170
+ const local = projects[target.projectRoot];
171
+ if (typeof local === 'object' && local !== null)
172
+ observe('local', local.mcpServers);
173
+ }
174
+ observe('user', user?.mcpServers);
175
+ }
176
+ const project = json(join(target.projectRoot, '.mcp.json'))?.mcpServers;
177
+ const userIndex = report.registrations.findIndex((entry) => entry.scope === 'user');
178
+ observe('project', project);
179
+ if (userIndex !== -1 && report.registrations.at(-1)?.scope === 'project') {
180
+ const entry = report.registrations.pop();
181
+ report.registrations.splice(userIndex, 0, entry);
182
+ }
183
+ }
184
+ else {
185
+ for (const [scope, path] of [
186
+ ['project', join(target.projectRoot, '.codex/config.toml')],
187
+ ['user', join(target.nativeHome, 'config.toml')],
188
+ ]) {
189
+ if (scope === 'project' && path === join(target.nativeHome, 'config.toml'))
190
+ continue;
191
+ const value = text(path);
192
+ if (value === undefined)
193
+ continue;
194
+ // This is a conservative header observation, not a TOML resolver. Quoted
195
+ // strings, profiles, managed and CLI overlays stay explicitly unverified.
196
+ report.findings.push('codex_configuration_not_fully_resolved');
197
+ if (/^\s*\[\s*mcp_servers\.(?:"ai-delivery"|'ai-delivery'|ai-delivery)\s*\]/mu.test(value))
198
+ observe(scope, { 'ai-delivery': {} });
199
+ }
200
+ }
201
+ report.findings = [...new Set(report.findings)];
202
+ return report;
203
+ }
204
+ function observeNativePlugins(result, input, target, entries, verifiedRegistration) {
205
+ const report = result.diagnostics;
206
+ report.nativeInventory = 'observed';
207
+ let count = 0;
208
+ for (const entry of entries) {
209
+ const id = entry.pluginId ?? entry.id;
210
+ if (!(entry.name === 'ai-delivery' || (typeof id === 'string' && id.startsWith('ai-delivery@'))))
211
+ continue;
212
+ if (input.host === 'codex' && entry.installed !== true)
213
+ continue;
214
+ if (input.host === 'claude-code' && (entry.scope === 'project' || entry.scope === 'local')) {
215
+ if (typeof entry.projectPath === 'string' && entry.projectPath !== target.projectRoot)
216
+ continue;
217
+ if (typeof entry.projectPath !== 'string')
218
+ report.findings.push('native_registration_project_unverified');
219
+ }
220
+ if (++count > 256) {
221
+ report.findings.push('native_inventory_truncated');
222
+ break;
223
+ }
224
+ const managed = result.sourceIntegrity === true && entry === verifiedRegistration;
225
+ const version = Version.safeParse(entry.version);
226
+ const scope = input.host === 'codex'
227
+ ? 'user'
228
+ : entry.scope === 'user' || entry.scope === 'project' || entry.scope === 'local'
229
+ ? entry.scope
230
+ : 'unknown';
231
+ report.registrations.push({
232
+ kind: 'plugin',
233
+ scope,
234
+ ownership: managed ? 'managed' : 'external',
235
+ source: managed ? 'managed_archive' : 'unknown',
236
+ version: version.success ? version.data : null,
237
+ enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null,
238
+ });
239
+ }
240
+ }
76
241
  // Native inventory and startup must not inherit the caller's credentials or
77
242
  // runtime injection flags. Install/update/recovery keep their existing owner.
78
243
  function doctorEnvironment() {
@@ -552,32 +717,71 @@ async function stageVersion(target, version, signal, publish, staging) {
552
717
  if (failed)
553
718
  throw failure;
554
719
  }
555
- function catalog(target, version) {
556
- verifiedUnit(target, version);
720
+ function catalogDocuments(target, version) {
557
721
  const source = `./versions/${version}/plugins/ai-delivery`;
558
- writePrivateJsonFileAtomically(join(target.catalog, '.agents/plugins/marketplace.json'), {
559
- name: target.marketplace,
560
- interface: { displayName: 'ai-delivery' },
561
- plugins: [
562
- {
563
- name: 'ai-delivery',
564
- source: { source: 'local', path: source },
565
- policy: { installation: 'AVAILABLE', authentication: 'ON_INSTALL' },
566
- category: 'Productivity',
722
+ return [
723
+ {
724
+ path: join(target.catalog, '.agents/plugins/marketplace.json'),
725
+ value: {
726
+ name: target.marketplace,
727
+ interface: { displayName: 'ai-delivery' },
728
+ plugins: [
729
+ {
730
+ name: 'ai-delivery',
731
+ source: { source: 'local', path: source },
732
+ policy: { installation: 'AVAILABLE', authentication: 'ON_INSTALL' },
733
+ category: 'Productivity',
734
+ },
735
+ ],
567
736
  },
568
- ],
569
- });
570
- writePrivateJsonFileAtomically(join(target.catalog, '.claude-plugin/marketplace.json'), {
571
- name: target.marketplace,
572
- owner: { name: 'AviaraTech' },
573
- plugins: [{ name: 'ai-delivery', source, version }],
737
+ },
738
+ {
739
+ path: join(target.catalog, '.claude-plugin/marketplace.json'),
740
+ value: {
741
+ name: target.marketplace,
742
+ owner: { name: 'AviaraTech' },
743
+ plugins: [{ name: 'ai-delivery', source, version }],
744
+ },
745
+ },
746
+ ];
747
+ }
748
+ function readCatalog(target, version) {
749
+ return catalogDocuments(target, version).map(({ path }) => {
750
+ assertCanonical(path);
751
+ const metadata = lstatSync(path);
752
+ if (!metadata.isFile() || metadata.nlink !== 1 || (metadata.mode & 0o777) !== 0o600 || metadata.size > 1024 ** 2)
753
+ throw new Error('Managed catalog is unsafe.');
754
+ return { path, bytes: readFileSync(path), device: metadata.dev, inode: metadata.ino };
574
755
  });
575
756
  }
576
- async function inventory(input, target, signal, publish) {
757
+ function catalogMatches(snapshot, target, version) {
758
+ return catalogDocuments(target, version).map(({ value }, index) => JSON.stringify(JSON.parse(snapshot[index].bytes.toString())) === JSON.stringify(value));
759
+ }
760
+ function assertCatalogUnchanged(entry) {
761
+ assertCanonical(entry.path);
762
+ const current = lstatSync(entry.path);
763
+ if (!current.isFile() ||
764
+ current.nlink !== 1 ||
765
+ (current.mode & 0o777) !== 0o600 ||
766
+ current.size !== entry.bytes.length ||
767
+ current.dev !== entry.device ||
768
+ current.ino !== entry.inode ||
769
+ !readFileSync(entry.path).equals(entry.bytes))
770
+ throw new Error('Managed catalog changed during this operation.');
771
+ }
772
+ function catalog(target, version, expected) {
773
+ verifiedUnit(target, version);
774
+ for (const [index, document] of catalogDocuments(target, version).entries()) {
775
+ if (expected)
776
+ assertCatalogUnchanged(expected[index]);
777
+ writePrivateJsonFileAtomically(document.path, document.value);
778
+ }
779
+ }
780
+ async function inventory(input, target, signal, publish, allPlugins = false) {
577
781
  const value = JSON.parse(await command(target.tool, [
578
782
  'plugin',
579
783
  'list',
580
- ...(input.host === 'codex' ? ['--marketplace', target.marketplace, '--available'] : []),
784
+ ...(input.host === 'codex' && !allPlugins ? ['--marketplace', target.marketplace, '--available'] : []),
581
785
  '--json',
582
786
  ], target.projectRoot, signal, publish, input.action === 'doctor'));
583
787
  if (input.host === 'claude-code')
@@ -631,6 +835,7 @@ function nativeEntry(input, target, entries) {
631
835
  ? z.object({ source: z.literal('local'), path: z.string() }).parse(entry.source).path
632
836
  : undefined;
633
837
  return {
838
+ registration: entry,
634
839
  version: Version.parse(entry.version),
635
840
  enabled: z.boolean().parse(entry.enabled),
636
841
  ...(typeof entry.installPath === 'string' ? { installedPath: entry.installPath } : {}),
@@ -658,16 +863,20 @@ function claudeCatalogSelection(target) {
658
863
  return entry;
659
864
  }
660
865
  function selectedRoot(input, target, entry, cachePath, sourceVersion = entry.version) {
661
- const unit = verifiedUnit(target, input.host === 'claude-code' ? sourceVersion : entry.version), source = pluginRoot(target, input.host === 'claude-code' ? sourceVersion : entry.version);
866
+ const unit = verifiedUnit(target, entry.version), source = pluginRoot(target, sourceVersion);
867
+ if (sourceVersion !== entry.version)
868
+ verifiedUnit(target, sourceVersion);
662
869
  if (input.host === 'claude-code' && claudeCatalogSelection(target).version !== sourceVersion)
663
870
  throw new Error('Claude catalog version differs from its native selection.');
664
871
  if (input.host === 'codex' && resolve(entry.sourceRoot) !== source)
665
872
  throw new Error('Native plugin source differs from the managed version.');
666
- const root = input.host === 'codex' ? cachePath : source;
873
+ const root = cachePath;
667
874
  if (!root)
668
875
  throw new Error('Native cache path is missing.');
669
- if (input.host === 'codex' &&
670
- resolve(root) !== join(target.nativeHome, 'plugins/cache', target.marketplace, 'ai-delivery', entry.version))
876
+ if (input.host === 'claude-code' &&
877
+ (entry.installedPath === undefined || resolve(entry.installedPath) !== resolve(root)))
878
+ throw new Error('Native cache path differs from the managed native selection.');
879
+ if (resolve(root) !== join(target.nativeHome, 'plugins/cache', target.marketplace, 'ai-delivery', entry.version))
671
880
  throw new Error('Native cache path is outside the managed native selection.');
672
881
  assertCanonical(root);
673
882
  if (JSON.stringify(tree(root)) !== JSON.stringify(unit.files))
@@ -758,12 +967,25 @@ export async function managePlugin(value) {
758
967
  };
759
968
  if (input.dryRun)
760
969
  return result;
970
+ result.diagnostics = sourceDiagnostics(input, target);
971
+ result.activation = { installedVersion: null, startupVersion: null, loadedVersion: null };
972
+ if (input.action === 'preview')
973
+ return result;
761
974
  if (input.action === 'doctor') {
762
- if (!state)
975
+ if (state)
976
+ result.recoveryRequired = state.pending !== undefined;
977
+ if (state?.pending)
763
978
  return result;
764
- result.recoveryRequired = state.pending !== undefined;
765
- if (state.pending || !state.currentVersion)
979
+ if (!state?.currentVersion) {
980
+ try {
981
+ observeNativePlugins(result, input, target, await inventory(input, target, new AbortController().signal, undefined, true));
982
+ }
983
+ catch {
984
+ result.diagnostics.nativeInventory = 'unavailable';
985
+ result.diagnostics.findings.push('native_inventory_unavailable');
986
+ }
766
987
  return result;
988
+ }
767
989
  try {
768
990
  verifiedUnit(target, state.currentVersion);
769
991
  }
@@ -782,8 +1004,16 @@ export async function managePlugin(value) {
782
1004
  result.nativeVersion = state.nativeVersion;
783
1005
  if (!registered || !result.installed) {
784
1006
  result.mcp = { configuration: 'missing', startup: 'not_checked' };
1007
+ try {
1008
+ observeNativePlugins(result, input, target, await inventory(input, target, new AbortController().signal, undefined, true));
1009
+ }
1010
+ catch {
1011
+ result.diagnostics.nativeInventory = 'unavailable';
1012
+ result.diagnostics.findings.push('native_inventory_unavailable');
1013
+ }
785
1014
  return result;
786
1015
  }
1016
+ result.activation.installedVersion = state.currentVersion;
787
1017
  try {
788
1018
  result.nativePluginRoot = selectedRoot(input, target, entry, state.installedPath);
789
1019
  result.sourceIntegrity = true;
@@ -802,6 +1032,20 @@ export async function managePlugin(value) {
802
1032
  : (error instanceof Error ? error.message : String(error)).slice(0, 2000),
803
1033
  };
804
1034
  }
1035
+ observeNativePlugins(result, input, target, entries, entry.registration);
1036
+ if (input.host === 'codex') {
1037
+ try {
1038
+ const global = await inventory(input, target, new AbortController().signal, undefined, true);
1039
+ const selectedIds = new Set(entries.flatMap((entry) => (typeof entry.pluginId === 'string' ? [entry.pluginId] : [])));
1040
+ observeNativePlugins(result, input, target, global.filter((entry) => typeof entry.pluginId !== 'string' || !selectedIds.has(entry.pluginId)));
1041
+ }
1042
+ catch {
1043
+ result.diagnostics.nativeInventory = 'unavailable';
1044
+ result.diagnostics.findings.push('native_inventory_unavailable');
1045
+ }
1046
+ }
1047
+ if (result.mcp?.startup === 'ready')
1048
+ result.activation.startupVersion = result.mcp.version ?? null;
805
1049
  if (result.authProbe && result.sourceIntegrity && result.enabled && result.mcp?.startup === 'ready') {
806
1050
  delete result.authProbe.reason;
807
1051
  await checkAuthentication(input, result.nativePluginRoot, result.authProbe);
@@ -821,6 +1065,34 @@ export async function managePlugin(value) {
821
1065
  },
822
1066
  operation: async () => {
823
1067
  state = readState(input, target);
1068
+ if (input.action === 'rollback') {
1069
+ if (!state?.currentVersion)
1070
+ throw new Error('Preserving rollback requires a current managed selection; it cannot reinstall a removed plugin.');
1071
+ if (state.previousVersion !== result.version)
1072
+ throw new Error('Managed rollback target changed before acquiring its ownership lock.');
1073
+ }
1074
+ let expectedState = existsSync(target.statePath)
1075
+ ? { bytes: readFileSync(target.statePath), metadata: lstatSync(target.statePath) }
1076
+ : undefined;
1077
+ // Guard the cooperative owned record; this is not a native-settings CAS.
1078
+ const persist = () => {
1079
+ assertCanonical(target.statePath);
1080
+ if (expectedState) {
1081
+ readState(input, target);
1082
+ const current = lstatSync(target.statePath);
1083
+ if (current.dev !== expectedState.metadata.dev ||
1084
+ current.ino !== expectedState.metadata.ino ||
1085
+ (current.mode & 0o777) !== 0o600 ||
1086
+ current.mode !== expectedState.metadata.mode ||
1087
+ !readFileSync(target.statePath).equals(expectedState.bytes))
1088
+ throw new Error('Managed state changed during this operation.');
1089
+ }
1090
+ else if (existsSync(target.statePath)) {
1091
+ throw new Error('Managed state appeared during this operation.');
1092
+ }
1093
+ writePrivateJsonFileAtomically(target.statePath, state);
1094
+ expectedState = { bytes: readFileSync(target.statePath), metadata: lstatSync(target.statePath) };
1095
+ };
824
1096
  const resuming = state?.pending !== undefined;
825
1097
  if (state?.pending) {
826
1098
  await recover(state.pending);
@@ -846,8 +1118,7 @@ export async function managePlugin(value) {
846
1118
  if (state.pending.action !== input.action || state.pending.targetVersion !== result.version)
847
1119
  throw new Error('Resume the interrupted original plugin command before selecting a different operation.');
848
1120
  }
849
- if ((input.action === 'update' || input.action === 'rollback') &&
850
- (!state || (input.action === 'update' && !state.currentVersion)))
1121
+ if (input.action === 'update' && !state?.currentVersion)
851
1122
  throw new Error('Install a managed plugin before updating or rolling it back.');
852
1123
  const version = input.action === 'remove' ? null : result.version;
853
1124
  if (version === null && input.action !== 'remove')
@@ -874,14 +1145,14 @@ export async function managePlugin(value) {
874
1145
  producerDigest: retainedWorktreeTransitionProducerDigest(dirname(fileURLToPath(import.meta.url))),
875
1146
  command: { phase: 'idle' },
876
1147
  };
877
- writePrivateJsonFileAtomically(target.statePath, state);
1148
+ persist();
878
1149
  const controller = new AbortController();
879
1150
  const cancel = () => controller.abort();
880
1151
  process.once('SIGINT', cancel);
881
1152
  process.once('SIGTERM', cancel);
882
1153
  const publish = (command) => {
883
1154
  state.pending.command = command;
884
- writePrivateJsonFileAtomically(target.statePath, state);
1155
+ persist();
885
1156
  };
886
1157
  const native = (args) => command(target.tool, args, target.projectRoot, controller.signal, publish);
887
1158
  const selector = `ai-delivery@${target.marketplace}`;
@@ -890,10 +1161,31 @@ export async function managePlugin(value) {
890
1161
  : ['plugin', 'uninstall', selector, '--scope', input.scope, '--keep-data'];
891
1162
  const installArgs = input.host === 'codex'
892
1163
  ? ['plugin', 'add', selector, '--json']
893
- : ['plugin', 'install', selector, '--scope', input.scope];
1164
+ : ['plugin', prior ? 'update' : 'install', selector, '--scope', input.scope];
894
1165
  let selectionStarted = false;
895
1166
  try {
896
1167
  state.nativeVersion = (await native(['--version'])).trim();
1168
+ if (prior && version) {
1169
+ if (input.host === 'claude-code') {
1170
+ // Qualified against this native binary in an isolated USER profile,
1171
+ // including unknown settings, unrelated selections and a catalog path change.
1172
+ const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u;
1173
+ if (state.nativeVersion !== '2.1.296 (Claude Code)' ||
1174
+ input.scope !== 'user' ||
1175
+ !stable.test(prior) ||
1176
+ !stable.test(version) ||
1177
+ (version
1178
+ .split('.')
1179
+ .map(BigInt)
1180
+ .map((part, index) => part - BigInt(prior.split('.')[index]))
1181
+ .find((part) => part !== 0n) ?? 0n) < 0n)
1182
+ throw new Error('Claude preserving replacement is unqualified; no catalog or native selection was changed.');
1183
+ }
1184
+ // Only this pinned native source has a qualified preserving-add footprint.
1185
+ // This does not establish exclusion of concurrent, unrelated native writers.
1186
+ if (input.host === 'codex' && state.nativeVersion !== 'codex-cli 0.162.1')
1187
+ throw new Error('This native version has no qualified preserving replacement route.');
1188
+ }
897
1189
  if (input.host === 'claude-code' && !(await native(['plugin', 'uninstall', '--help'])).includes('--keep-data'))
898
1190
  throw new Error('This Claude Code version cannot preserve plugin data; upgrade the native tool first.');
899
1191
  process.stderr.write(`ai-delivery.plugin ${JSON.stringify({ action: input.action, host: input.host, scope: input.scope, stage: version ? 'prepare_version' : 'native_remove', version })}\n`);
@@ -907,21 +1199,56 @@ export async function managePlugin(value) {
907
1199
  if (recoverySourceVersion !== prior && recoverySourceVersion !== version)
908
1200
  throw new Error('Interrupted native selection has an incompatible catalog version.');
909
1201
  }
1202
+ if (current && version && !current.enabled)
1203
+ throw new Error('Native plugin selection is disabled; preserving replacement cannot enable it.');
1204
+ let catalogBefore;
1205
+ let reuseSelection = false;
1206
+ if (prior && version) {
1207
+ if (!registered || !current || (current.version !== prior && !(resuming && current.version === version)))
1208
+ throw new Error('Managed native selection changed; replacement ownership is unresolved.');
1209
+ catalogBefore = readCatalog(target, prior);
1210
+ const priorMatches = catalogMatches(catalogBefore, target, prior);
1211
+ const targetMatches = catalogMatches(catalogBefore, target, version);
1212
+ const priorCatalog = priorMatches.every(Boolean), targetCatalog = targetMatches.every(Boolean);
1213
+ const partialCatalog = resuming && targetMatches[0] && priorMatches[1];
1214
+ if (!priorCatalog && !targetCatalog && !partialCatalog)
1215
+ throw new Error('Managed catalog differs from the owned prior or target publication.');
1216
+ // The installed cache and the host-specific catalog source are separate observations.
1217
+ recoverySourceVersion = targetMatches[input.host === 'codex' ? 0 : 1] ? version : prior;
1218
+ if (current.version === version) {
1219
+ if (!targetCatalog)
1220
+ throw new Error('Selected target has an incompatible managed catalog.');
1221
+ reuseSelection = true;
1222
+ }
1223
+ else if (targetCatalog) {
1224
+ throw new Error('Interrupted replacement is ambiguous; native selection will not be repeated.');
1225
+ }
1226
+ }
1227
+ else if (version && current && resuming) {
1228
+ catalogBefore = readCatalog(target, version);
1229
+ if (!catalogMatches(catalogBefore, target, version).every(Boolean))
1230
+ throw new Error('Selected target has an incompatible managed catalog.');
1231
+ reuseSelection = current.version === version;
1232
+ }
1233
+ let observedRoot;
910
1234
  if (current)
911
- selectedRoot(input, target, current, current.version === prior
912
- ? state.installedPath
913
- : join(target.nativeHome, 'plugins/cache', target.marketplace, 'ai-delivery', current.version), recoverySourceVersion);
1235
+ observedRoot = selectedRoot(input, target, current, current.installedPath ??
1236
+ (current.version === prior
1237
+ ? state.installedPath
1238
+ : join(target.nativeHome, 'plugins/cache', target.marketplace, 'ai-delivery', current.version)), recoverySourceVersion);
914
1239
  if (version) {
915
1240
  await stageVersion(target, version, controller.signal, publish, (allocation) => {
916
1241
  if (allocation)
917
1242
  state.pending.staging = allocation;
918
1243
  else
919
1244
  delete state.pending.staging;
920
- writePrivateJsonFileAtomically(target.statePath, state);
1245
+ persist();
921
1246
  });
922
- selectionStarted = true;
923
- catalog(target, version);
924
- if (!registered)
1247
+ if (!reuseSelection) {
1248
+ selectionStarted = true;
1249
+ catalog(target, version, catalogBefore);
1250
+ }
1251
+ if (!registered && !reuseSelection)
925
1252
  await native([
926
1253
  'plugin',
927
1254
  'marketplace',
@@ -930,12 +1257,14 @@ export async function managePlugin(value) {
930
1257
  ...(input.host === 'codex' ? ['--json'] : ['--scope', input.scope]),
931
1258
  ]);
932
1259
  }
933
- if (current && (current.version !== version || input.action === 'remove')) {
1260
+ if (current && input.action === 'remove') {
934
1261
  selectionStarted = true;
935
1262
  await native(removeArgs);
936
1263
  }
937
- let installedPath = state.installedPath;
938
- if (version) {
1264
+ let installedPath = reuseSelection
1265
+ ? (current?.installedPath ?? observedRoot ?? state.installedPath)
1266
+ : state.installedPath;
1267
+ if (version && !reuseSelection) {
939
1268
  const installed = await native(installArgs);
940
1269
  if (input.host === 'codex')
941
1270
  installedPath = z.object({ installedPath: z.string() }).parse(JSON.parse(installed)).installedPath;
@@ -956,14 +1285,13 @@ export async function managePlugin(value) {
956
1285
  state.previousVersion = prior;
957
1286
  state.installedPath = version ? (readback?.installedPath ?? installedPath) : null;
958
1287
  delete state.pending;
959
- writePrivateJsonFileAtomically(target.statePath, state);
1288
+ persist();
960
1289
  result.version = version;
961
1290
  result.changed = prior !== version;
962
1291
  result.installed = version !== null;
963
- result.restartRequired = true;
1292
+ result.activation = { installedVersion: version, startupVersion: null, loadedVersion: null };
964
1293
  if (version)
965
- result.nativePluginRoot =
966
- input.host === 'codex' ? (state.installedPath ?? pluginRoot(target, version)) : pluginRoot(target, version);
1294
+ result.nativePluginRoot = state.installedPath ?? pluginRoot(target, version);
967
1295
  return result;
968
1296
  }
969
1297
  catch (error) {
@@ -974,21 +1302,14 @@ export async function managePlugin(value) {
974
1302
  state.pending.staging === undefined) {
975
1303
  delete state.pending;
976
1304
  try {
977
- writePrivateJsonFileAtomically(target.statePath, state);
1305
+ persist();
978
1306
  }
979
1307
  catch (recoveryError) {
980
1308
  throw new AggregateError([error, recoveryError], 'Plugin preparation failed and pending-state cleanup also failed.');
981
1309
  }
982
1310
  }
983
- // Preserve recovery after selection and restore the prior catalog when possible.
984
- if (selectionStarted && prior) {
985
- try {
986
- catalog(target, prior);
987
- }
988
- catch {
989
- /* Keep the original failure and pending intent. */
990
- }
991
- }
1311
+ // A failed acknowledgement may follow a successful selection. Retain the
1312
+ // catalog and pending intent for exact postimage reconciliation, not rollback.
992
1313
  throw error;
993
1314
  }
994
1315
  finally {