@aviaratech/ai-delivery 0.3.30 → 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 (45) hide show
  1. package/dist/cli.js +2 -5
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cliResult.d.ts +1 -0
  4. package/dist/cliResult.js +8 -0
  5. package/dist/cliResult.js.map +1 -1
  6. package/dist/cliResult.test.js +176 -0
  7. package/dist/cliResult.test.js.map +1 -1
  8. package/dist/errors.d.ts +19 -0
  9. package/dist/errors.js +52 -0
  10. package/dist/errors.js.map +1 -1
  11. package/dist/github/client.d.ts +5 -0
  12. package/dist/github/client.js +142 -6
  13. package/dist/github/client.js.map +1 -1
  14. package/dist/github/machineAuth.test.js +284 -1
  15. package/dist/github/machineAuth.test.js.map +1 -1
  16. package/dist/lifecycle.test.js +72 -6
  17. package/dist/lifecycle.test.js.map +1 -1
  18. package/dist/pluginAuthProbe.test.js +25 -0
  19. package/dist/pluginAuthProbe.test.js.map +1 -1
  20. package/dist/pluginDoctor.test.js +1 -1
  21. package/dist/pluginDoctor.test.js.map +1 -1
  22. package/dist/pluginInstaller.js +169 -49
  23. package/dist/pluginInstaller.js.map +1 -1
  24. package/dist/pluginInstaller.test.js +526 -25
  25. package/dist/pluginInstaller.test.js.map +1 -1
  26. package/dist/pr.d.ts +1 -1
  27. package/dist/pr.js +85 -27
  28. package/dist/pr.js.map +1 -1
  29. package/dist/pr.test.js +223 -5
  30. package/dist/pr.test.js.map +1 -1
  31. package/dist/prAssociation.test.js +509 -2
  32. package/dist/prAssociation.test.js.map +1 -1
  33. package/dist/review.js +11 -0
  34. package/dist/review.js.map +1 -1
  35. package/dist/review.test.js +38 -0
  36. package/dist/review.test.js.map +1 -1
  37. package/dist/setup.test.js +489 -4
  38. package/dist/setup.test.js.map +1 -1
  39. package/dist/targetPolicyLocal.test.js +574 -167
  40. package/dist/targetPolicyLocal.test.js.map +1 -1
  41. package/package.json +1 -1
  42. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  43. package/plugins/ai-delivery/plugin.json +1 -1
  44. package/plugins/ai-delivery/runtime/dist/cli.js +57 -57
  45. package/plugins/ai-delivery/runtime/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { EventEmitter } from 'node:events';
4
- import { existsSync, cpSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync, } from 'node:fs';
4
+ import { existsSync, chmodSync, cpSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync, } from 'node:fs';
5
5
  import { execFileSync, spawn, spawnSync } from 'node:child_process';
6
6
  import { tmpdir } from 'node:os';
7
7
  import { dirname, join } from 'node:path';
@@ -16,6 +16,7 @@ const fixture = vi.hoisted(() => ({
16
16
  commandArguments: [],
17
17
  realCommands: false,
18
18
  responses: [],
19
+ respond: undefined,
19
20
  packArchive: '',
20
21
  }));
21
22
  vi.mock('node:child_process', async (original) => {
@@ -35,7 +36,7 @@ vi.mock('node:child_process', async (original) => {
35
36
  stderr: new PassThrough(),
36
37
  kill: () => true,
37
38
  });
38
- const queued = fixture.responses.shift();
39
+ const queued = fixture.responses.shift() ?? fixture.respond;
39
40
  let response = typeof queued === 'function' ? queued(commandArguments) : queued;
40
41
  if (binary === '/bin/sh' && args?.[3] === 'npm' && fixture.packArchive) {
41
42
  const destination = args[args.indexOf('--pack-destination') + 1];
@@ -255,6 +256,7 @@ beforeEach(() => {
255
256
  fixture.commandArguments = [];
256
257
  fixture.realCommands = false;
257
258
  fixture.responses = [];
259
+ fixture.respond = undefined;
258
260
  fixture.packArchive = '';
259
261
  });
260
262
  afterEach(() => {
@@ -324,6 +326,35 @@ function doctorFixture(enabled, host = 'codex') {
324
326
  currentVersion: version,
325
327
  installedPath: cache,
326
328
  }, host);
329
+ for (const [relative, content] of [
330
+ [
331
+ '.agents/plugins/marketplace.json',
332
+ {
333
+ name: 'ai-delivery-user',
334
+ interface: { displayName: 'ai-delivery' },
335
+ plugins: [
336
+ {
337
+ name: 'ai-delivery',
338
+ source: { source: 'local', path: `./versions/${version}/plugins/ai-delivery` },
339
+ policy: { installation: 'AVAILABLE', authentication: 'ON_INSTALL' },
340
+ category: 'Productivity',
341
+ },
342
+ ],
343
+ },
344
+ ],
345
+ [
346
+ '.claude-plugin/marketplace.json',
347
+ {
348
+ name: 'ai-delivery-user',
349
+ owner: { name: 'AviaraTech' },
350
+ plugins: [{ name: 'ai-delivery', source: `./versions/${version}/plugins/ai-delivery`, version }],
351
+ },
352
+ ],
353
+ ]) {
354
+ const path = join(catalog, relative);
355
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
356
+ writeFileSync(path, JSON.stringify(content), { mode: 0o600 });
357
+ }
327
358
  if (host === 'codex') {
328
359
  fixture.responses.push(JSON.stringify({
329
360
  installed: [
@@ -345,12 +376,6 @@ function doctorFixture(enabled, host = 'codex') {
345
376
  writeFileSync(path, JSON.stringify({
346
377
  'ai-delivery-user': { source: { source: 'directory', path: catalog }, installLocation: catalog },
347
378
  }), { mode: 0o600 });
348
- const published = join(catalog, '.claude-plugin/marketplace.json');
349
- mkdirSync(dirname(published), { recursive: true, mode: 0o700 });
350
- writeFileSync(published, JSON.stringify({
351
- name: 'ai-delivery-user',
352
- plugins: [{ name: 'ai-delivery', version, source: `./versions/${version}/plugins/ai-delivery` }],
353
- }), { mode: 0o600 });
354
379
  fixture.responses.push(JSON.stringify([
355
380
  {
356
381
  id: 'ai-delivery@ai-delivery-user',
@@ -432,7 +457,7 @@ function installationFixture(action, readback = (entry) => [entry]) {
432
457
  source: { source: 'local', path: source },
433
458
  marketplaceSource: { sourceType: 'local', source: catalog },
434
459
  };
435
- fixture.responses.push('codex-cli 0.153.0', oversizedCatalogue(previous), '', '0.3.22', '{}', (args) => {
460
+ fixture.responses.push('codex-cli 0.162.1', oversizedCatalogue(previous), '', '0.3.22', ...(action === 'install' ? ['{}'] : []), (args) => {
436
461
  assert.deepEqual(args, ['codex', 'plugin', 'add', 'ai-delivery@ai-delivery-user', '--json']);
437
462
  mkdirSync(dirname(cache), { recursive: true, mode: 0o700 });
438
463
  cpSync(source, cache, { recursive: true });
@@ -440,6 +465,475 @@ function installationFixture(action, readback = (entry) => [entry]) {
440
465
  }, oversizedCatalogue(readback(entry)));
441
466
  return { entry, cache, catalog, source };
442
467
  }
468
+ function replacementFixture(preferences = { issue_info: { approval: 'fictional-explicit-allow' } }) {
469
+ const { entry, cache, catalog } = installationFixture('update');
470
+ fixture.responses = [];
471
+ const selector = 'ai-delivery@ai-delivery-user';
472
+ const policy = {
473
+ [selector]: { enabled: true, preferences },
474
+ 'private-unrelated@other': { sentinel: 'fictional-private-value', enabled: false },
475
+ };
476
+ const before = structuredClone(policy);
477
+ const native = {
478
+ selected: [
479
+ {
480
+ ...entry,
481
+ version: '0.3.21',
482
+ source: { source: 'local', path: join(catalog, 'versions/0.3.21/plugins/ai-delivery') },
483
+ },
484
+ ],
485
+ version: 'codex-cli 0.162.1',
486
+ selectionCalls: 0,
487
+ loseAck: false,
488
+ failSelection: false,
489
+ };
490
+ fixture.respond = (args) => {
491
+ if (args[0] === 'npm')
492
+ return '';
493
+ if (args[0] === process.execPath)
494
+ return '0.3.22';
495
+ if (args[1] === '--version')
496
+ return native.version;
497
+ if (args[2] === 'list') {
498
+ let offeredPath;
499
+ try {
500
+ const offered = JSON.parse(readFileSync(join(catalog, '.agents/plugins/marketplace.json'), 'utf8'));
501
+ offeredPath = offered.plugins[0].source.path;
502
+ }
503
+ catch {
504
+ return undefined;
505
+ }
506
+ // Pinned list takes installed version from cache and source from the current catalog.
507
+ return JSON.stringify({
508
+ installed: native.selected.map((plugin) => ({
509
+ ...plugin,
510
+ source: { source: 'local', path: join(catalog, offeredPath) },
511
+ })),
512
+ available: [],
513
+ });
514
+ }
515
+ if (args[2] === 'marketplace')
516
+ return '{}';
517
+ if (args[2] === 'remove') {
518
+ // Pinned Codex remove clears the complete qualified plugin table.
519
+ delete policy[selector];
520
+ native.selected = [];
521
+ return '{}';
522
+ }
523
+ if (args[2] === 'add') {
524
+ assert.deepEqual(args, ['codex', 'plugin', 'add', selector, '--json']);
525
+ native.selectionCalls++;
526
+ if (native.failSelection)
527
+ return undefined;
528
+ // Pinned add retains existing fields but can evict older native caches.
529
+ policy[selector] = { ...policy[selector], enabled: true };
530
+ const offered = JSON.parse(readFileSync(join(catalog, '.agents/plugins/marketplace.json'), 'utf8'));
531
+ const offeredPath = offered.plugins[0].source.path;
532
+ const version = /^\.\/versions\/([^/]+)\/plugins\/ai-delivery$/u.exec(offeredPath)[1];
533
+ const selectedCache = join(dirname(cache), version);
534
+ mkdirSync(dirname(selectedCache), { recursive: true, mode: 0o700 });
535
+ cpSync(join(catalog, offeredPath), selectedCache, { recursive: true });
536
+ for (const old of readdirSync(dirname(cache)))
537
+ if (old !== version)
538
+ rmSync(join(dirname(cache), old), { recursive: true });
539
+ native.selected = [{ ...entry, version, source: { source: 'local', path: join(catalog, offeredPath) } }];
540
+ return native.loseAck ? undefined : JSON.stringify({ installedPath: selectedCache });
541
+ }
542
+ return undefined;
543
+ };
544
+ return { catalog, policy, before, native };
545
+ }
546
+ test.each([
547
+ { issue_info: { approval: 'fictional-explicit-allow' }, unknown: { nested: ['retain', null] } },
548
+ { unknown: { nested: ['retain', null] } },
549
+ { issue_info: null, unknown: { nested: ['retain', null] } },
550
+ ])('managed replacement preserves fictional tool preferences %j without clearing the plugin entry', async (preferences) => {
551
+ const { policy, before } = replacementFixture(preferences);
552
+ const result = await managePlugin({ ...input(), action: 'update', version: '0.3.22' });
553
+ assert.equal(result.version, '0.3.22');
554
+ assert.deepEqual(policy, before);
555
+ assert.equal(fixture.commandArguments.some((args) => ['remove', 'uninstall'].includes(args[2] ?? '')), false);
556
+ });
557
+ test('installing a different owned version cannot bypass the preserving replacement path', async () => {
558
+ const { policy, before } = replacementFixture();
559
+ await managePlugin({ ...input(), action: 'install', version: '0.3.22' });
560
+ assert.deepEqual(policy, before);
561
+ assert.equal(fixture.commandArguments.some((args) => args[2] === 'remove'), false);
562
+ });
563
+ test('an exact same-version owned selection is reused without invoking native add', async () => {
564
+ const { native } = replacementFixture();
565
+ const result = await managePlugin({ ...input(), action: 'update', version: '0.3.21' });
566
+ assert.equal(result.changed, false);
567
+ assert.equal(native.selectionCalls, 0);
568
+ });
569
+ test.each([
570
+ 'disabled',
571
+ 'missing selection',
572
+ 'unregistered catalog',
573
+ 'foreign source',
574
+ 'changed cache',
575
+ 'changed catalog',
576
+ 'catalog symlink',
577
+ 'read-only catalog',
578
+ 'unqualified native',
579
+ 'unqualified newer native',
580
+ ])('replacement refuses %s before preparing a new version', async (fault) => {
581
+ const { native, catalog, policy, before } = replacementFixture();
582
+ if (fault === 'disabled')
583
+ native.selected[0].enabled = false;
584
+ if (fault === 'missing selection')
585
+ native.selected = [];
586
+ if (fault === 'unregistered catalog')
587
+ native.selected[0].marketplaceSource.source = join(fixture.home, 'foreign-marketplace');
588
+ if (fault === 'foreign source') {
589
+ const respond = fixture.respond;
590
+ fixture.respond = (args) => {
591
+ const output = respond(args);
592
+ if (args[2] !== 'list' || !output)
593
+ return output;
594
+ const listed = JSON.parse(output);
595
+ listed.installed[0].source.path = join(fixture.home, 'unowned');
596
+ return JSON.stringify(listed);
597
+ };
598
+ }
599
+ if (fault === 'changed cache')
600
+ writeFileSync(join(fixture.home, '.codex/plugins/cache/ai-delivery-user/ai-delivery/0.3.21/skills/intake/SKILL.md'), 'changed');
601
+ if (fault === 'changed catalog')
602
+ writeFileSync(join(catalog, '.agents/plugins/marketplace.json'), '{}');
603
+ const unrelatedCatalog = join(fixture.home, 'unrelated-catalog');
604
+ if (fault === 'catalog symlink') {
605
+ writeFileSync(unrelatedCatalog, 'unrelated catalog sentinel');
606
+ rmSync(join(catalog, '.agents/plugins/marketplace.json'));
607
+ symlinkSync(unrelatedCatalog, join(catalog, '.agents/plugins/marketplace.json'));
608
+ }
609
+ if (fault === 'read-only catalog')
610
+ chmodSync(join(catalog, '.agents/plugins/marketplace.json'), 0o400);
611
+ if (fault === 'unqualified native')
612
+ native.version = 'codex-cli 0.153.0';
613
+ if (fault === 'unqualified newer native')
614
+ native.version = 'codex-cli 0.162.2';
615
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }));
616
+ assert.equal(native.selectionCalls, 0);
617
+ assert.equal(existsSync(join(catalog, 'versions/0.3.22')), false);
618
+ assert.deepEqual(policy, before);
619
+ if (fault === 'catalog symlink')
620
+ assert.equal(readFileSync(unrelatedCatalog, 'utf8'), 'unrelated catalog sentinel');
621
+ });
622
+ test.each(['update', 'install', 'rollback'])('Claude owned %s refuses an unqualified native version before catalog or selection changes', async (action) => {
623
+ doctorFixture(true, 'claude-code');
624
+ fixture.responses.unshift('2.1.295 (Claude Code)', '--keep-data');
625
+ const catalog = join(fixture.home, '.cache/ai-delivery/plugins/claude-code/user/marketplace');
626
+ if (action === 'rollback') {
627
+ const path = join(dirname(catalog), 'state.json');
628
+ const state = JSON.parse(readFileSync(path, 'utf8'));
629
+ state.previousVersion = '0.3.20';
630
+ writeState(state, 'claude-code');
631
+ }
632
+ const paths = ['.agents/plugins/marketplace.json', '.claude-plugin/marketplace.json'].map((name) => join(catalog, name));
633
+ const before = paths.map((path) => readFileSync(path));
634
+ await assert.rejects(managePlugin({ ...input(), host: 'claude-code', action, version: action === 'rollback' ? undefined : '0.3.22' }), /preserv.*unqualified/iu);
635
+ assert.deepEqual(paths.map((path) => readFileSync(path)), before);
636
+ assert.equal(fixture.commandArguments.some((args) => ['update', 'install', 'uninstall'].includes(args[2] ?? '') && !args.includes('--help')), false);
637
+ });
638
+ function claudeReplacementFixture() {
639
+ doctorFixture(true, 'claude-code');
640
+ const initial = JSON.parse(fixture.responses.shift());
641
+ nativeArchiveFixture();
642
+ const catalog = join(fixture.home, '.cache/ai-delivery/plugins/claude-code/user/marketplace');
643
+ const settings = join(fixture.home, '.claude/settings.json');
644
+ const preferences = {
645
+ enabledPlugins: { 'ai-delivery@ai-delivery-user': true, 'unrelated@fictional': false },
646
+ permissions: { allow: ['mcp__fictional__read'], deny: ['mcp__fictional__write'] },
647
+ unknown: { nested: ['retain', null, { explicit: false }] },
648
+ };
649
+ writeFileSync(settings, JSON.stringify(preferences), { mode: 0o600 });
650
+ const before = readFileSync(settings);
651
+ const native = { selected: initial, updates: 0, loseAck: false, failSelection: false };
652
+ fixture.respond = (args) => {
653
+ if (args[0] === 'npm')
654
+ return '';
655
+ if (args[0] === process.execPath)
656
+ return '0.3.22';
657
+ if (args[1] === '--version')
658
+ return '2.1.296 (Claude Code)';
659
+ if (args[2] === 'uninstall' && args.includes('--help'))
660
+ return '--keep-data';
661
+ if (args[2] === 'list')
662
+ return JSON.stringify(native.selected);
663
+ if (args[2] === 'update') {
664
+ assert.deepEqual(args, ['claude', 'plugin', 'update', 'ai-delivery@ai-delivery-user', '--scope', 'user']);
665
+ native.updates++;
666
+ if (native.failSelection)
667
+ return undefined;
668
+ const offered = JSON.parse(readFileSync(join(catalog, '.claude-plugin/marketplace.json'), 'utf8'));
669
+ const { source, version } = offered.plugins[0];
670
+ const cache = join(fixture.home, '.claude/plugins/cache/ai-delivery-user/ai-delivery', version);
671
+ mkdirSync(dirname(cache), { recursive: true, mode: 0o700 });
672
+ cpSync(join(catalog, source), cache, { recursive: true });
673
+ native.selected = [{ ...initial[0], version, installPath: cache }];
674
+ return native.loseAck ? undefined : '{}';
675
+ }
676
+ return undefined;
677
+ };
678
+ return { catalog, settings, before, native };
679
+ }
680
+ test.each(['update', 'install'])('Claude owned forward %s preserves preferences through native update', async (action) => {
681
+ const { settings, before, native } = claudeReplacementFixture();
682
+ const result = await managePlugin({ ...input(), host: 'claude-code', action, version: '0.3.22' });
683
+ assert.equal(result.version, '0.3.22');
684
+ assert.equal(result.nativePluginRoot, join(fixture.home, '.claude/plugins/cache/ai-delivery-user/ai-delivery/0.3.22'));
685
+ assert.equal(native.updates, 1);
686
+ assert.deepEqual(readFileSync(settings), before);
687
+ assert.equal(fixture.commandArguments.some((args) => ['install', 'uninstall'].includes(args[2] ?? '') && !args.includes('--help')), false);
688
+ });
689
+ test('Claude same-version replacement reuses its verified cache without a native update', async () => {
690
+ const { settings, before, native } = claudeReplacementFixture();
691
+ const result = await managePlugin({ ...input(), host: 'claude-code', action: 'update', version: '0.3.21' });
692
+ assert.equal(result.changed, false);
693
+ assert.equal(native.updates, 0);
694
+ assert.deepEqual(readFileSync(settings), before);
695
+ });
696
+ test.each(['0.3.20', '0.3.22-beta.1', '0.3.22+fixture'])('Claude refuses unqualified replacement target %s before publication', async (version) => {
697
+ const { catalog, native, settings, before } = claudeReplacementFixture();
698
+ const paths = ['.agents/plugins/marketplace.json', '.claude-plugin/marketplace.json'].map((name) => join(catalog, name));
699
+ const catalogs = paths.map((path) => readFileSync(path));
700
+ await assert.rejects(managePlugin({ ...input(), host: 'claude-code', action: 'update', version }), /preserv.*unqualified/iu);
701
+ assert.deepEqual(paths.map((path) => readFileSync(path)), catalogs);
702
+ assert.deepEqual(readFileSync(settings), before);
703
+ assert.equal(native.updates, 0);
704
+ assert.equal(existsSync(join(catalog, 'versions', version)), false);
705
+ });
706
+ test('Claude lost update acknowledgement resumes the exact target without selecting twice', async () => {
707
+ const { native, settings, before, catalog } = claudeReplacementFixture();
708
+ native.loseAck = true;
709
+ await assert.rejects(managePlugin({ ...input(), host: 'claude-code', action: 'update', version: '0.3.22' }));
710
+ const interrupted = JSON.parse(readFileSync(join(dirname(catalog), 'state.json'), 'utf8'));
711
+ interrupted.pending.owner = { pid: 2_000_000_000, birth: 'old owner' };
712
+ writeState(interrupted, 'claude-code');
713
+ native.loseAck = false;
714
+ await managePlugin({ ...input(), host: 'claude-code', action: 'update', version: '0.3.22' });
715
+ assert.equal(native.updates, 1);
716
+ assert.deepEqual(readFileSync(settings), before);
717
+ });
718
+ test('Claude prior selection with a published target catalog refuses an ambiguous retry', async () => {
719
+ const { native, settings, before, catalog } = claudeReplacementFixture();
720
+ native.failSelection = true;
721
+ await assert.rejects(managePlugin({ ...input(), host: 'claude-code', action: 'update', version: '0.3.22' }));
722
+ const interrupted = JSON.parse(readFileSync(join(dirname(catalog), 'state.json'), 'utf8'));
723
+ interrupted.pending.owner = { pid: 2_000_000_000, birth: 'old owner' };
724
+ writeState(interrupted, 'claude-code');
725
+ native.failSelection = false;
726
+ await assert.rejects(managePlugin({ ...input(), host: 'claude-code', action: 'update', version: '0.3.22' }), /ambiguous/iu);
727
+ assert.equal(native.updates, 1);
728
+ assert.deepEqual(readFileSync(settings), before);
729
+ });
730
+ test('Claude doctor rejects changed native cache bytes before starting MCP', async () => {
731
+ const cache = doctorFixture(true, 'claude-code');
732
+ writeFileSync(join(cache, 'skills/intake/SKILL.md'), 'foreign native cache bytes');
733
+ const result = await managePlugin({ ...input(), host: 'claude-code', action: 'doctor', version: undefined });
734
+ assert.equal(result.sourceIntegrity, false);
735
+ assert.equal(result.mcp?.startup, 'not_checked');
736
+ });
737
+ test('Claude doctor refuses a native cache path that differs from the owned selection', async () => {
738
+ doctorFixture(true, 'claude-code');
739
+ const entries = JSON.parse(fixture.responses[0]);
740
+ entries[0].installPath = join(fixture.home, 'foreign-native-cache');
741
+ fixture.responses[0] = JSON.stringify(entries);
742
+ const result = await managePlugin({ ...input(), host: 'claude-code', action: 'doctor', version: undefined });
743
+ assert.equal(result.sourceIntegrity, false);
744
+ assert.equal(result.mcp?.startup, 'not_checked');
745
+ });
746
+ test('lost native acknowledgement remains a failure, then exact target postimage resumes without selecting twice', async () => {
747
+ const { native, policy, before, catalog } = replacementFixture();
748
+ native.loseAck = true;
749
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /Native fixture intentionally unavailable/u);
750
+ assert.deepEqual(policy, before);
751
+ const path = join(dirname(catalog), 'state.json');
752
+ const interrupted = JSON.parse(readFileSync(path, 'utf8'));
753
+ assert.equal(interrupted.currentVersion, '0.3.21');
754
+ assert.equal(interrupted.pending.targetVersion, '0.3.22');
755
+ interrupted.pending.owner = { pid: 2_000_000_000, birth: 'old owner' };
756
+ writeState(interrupted);
757
+ native.loseAck = false;
758
+ const result = await managePlugin({ ...input(), action: 'update', version: '0.3.22' });
759
+ assert.equal(result.version, '0.3.22');
760
+ assert.equal(native.selectionCalls, 1);
761
+ assert.deepEqual(policy, before);
762
+ const finished = JSON.parse(readFileSync(path, 'utf8'));
763
+ assert.equal(finished.currentVersion, '0.3.22');
764
+ assert.equal(finished.previousVersion, '0.3.21');
765
+ assert.equal(finished.pending, undefined);
766
+ });
767
+ test('a target catalog with prior native selection and an idle pending command refuses ambiguous replay', async () => {
768
+ const { native, catalog } = replacementFixture();
769
+ native.failSelection = true;
770
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }));
771
+ const path = join(dirname(catalog), 'state.json');
772
+ const interrupted = JSON.parse(readFileSync(path, 'utf8'));
773
+ interrupted.pending.owner = { pid: 2_000_000_000, birth: 'old owner' };
774
+ writeState(interrupted);
775
+ native.failSelection = false;
776
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /ambiguous/u);
777
+ assert.equal(native.selectionCalls, 1);
778
+ assert.equal(JSON.parse(readFileSync(path, 'utf8')).pending.targetVersion, '0.3.22');
779
+ });
780
+ test('recovery rejects a corrupted completed unit before reusing the selected target', async () => {
781
+ const { native, catalog } = replacementFixture();
782
+ native.loseAck = true;
783
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }));
784
+ const statePath = join(dirname(catalog), 'state.json');
785
+ const pending = JSON.parse(readFileSync(statePath, 'utf8'));
786
+ pending.pending.owner = { pid: 2_000_000_000, birth: 'terminated selected owner' };
787
+ writeState(pending);
788
+ const archive = join(catalog, 'versions/0.3.22/archive.tgz');
789
+ writeFileSync(archive, 'corrupted completed archive');
790
+ native.loseAck = false;
791
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }));
792
+ assert.equal(native.selectionCalls, 1);
793
+ assert.equal(readFileSync(archive, 'utf8'), 'corrupted completed archive');
794
+ assert.ok(JSON.parse(readFileSync(statePath, 'utf8')).pending);
795
+ });
796
+ test('qualified Codex rollback uses the retained immutable unit and preserves later unrelated edits', async () => {
797
+ const { native, catalog, policy, before } = replacementFixture();
798
+ await managePlugin({ ...input(), action: 'update', version: '0.3.22' });
799
+ assert.equal(existsSync(join(fixture.home, '.codex/plugins/cache/ai-delivery-user/ai-delivery/0.3.21')), false);
800
+ assert.equal(existsSync(join(catalog, 'versions/0.3.21/version.json')), true);
801
+ policy.later = { sentinel: 'keep later edit' };
802
+ const rolled = await managePlugin({ ...input(), action: 'rollback', version: undefined });
803
+ assert.equal(rolled.version, '0.3.21');
804
+ assert.equal(native.selectionCalls, 2);
805
+ assert.deepEqual(policy, { ...before, later: { sentinel: 'keep later edit' } });
806
+ });
807
+ test('rollback of a removed managed selection refuses rather than reinstalling it', async () => {
808
+ const { catalog, native, policy } = replacementFixture();
809
+ const path = join(dirname(catalog), 'state.json');
810
+ const state = JSON.parse(readFileSync(path, 'utf8'));
811
+ state.currentVersion = null;
812
+ state.previousVersion = '0.3.21';
813
+ state.installedPath = null;
814
+ writeState(state);
815
+ native.selected = [];
816
+ delete policy['ai-delivery@ai-delivery-user'];
817
+ const before = structuredClone(policy);
818
+ await assert.rejects(managePlugin({ ...input(), action: 'rollback', version: undefined }), /current managed selection/u);
819
+ assert.deepEqual(fixture.commandArguments, []);
820
+ assert.deepEqual(policy, before);
821
+ });
822
+ test('rollback refuses a target superseded by the managed writer ahead of its lock', async () => {
823
+ const { catalog, native } = replacementFixture();
824
+ const path = join(dirname(catalog), 'state.json');
825
+ const initial = JSON.parse(readFileSync(path, 'utf8'));
826
+ initial.previousVersion = '0.3.20';
827
+ writeState(initial);
828
+ const respond = fixture.respond;
829
+ let queuedRollback;
830
+ fixture.respond = (args) => {
831
+ const output = respond(args);
832
+ if (args[2] === 'list' && native.selected[0]?.version === '0.3.22' && !queuedRollback)
833
+ queuedRollback = managePlugin({ ...input(), action: 'rollback', version: undefined }).then(() => undefined, (error) => error);
834
+ return output;
835
+ };
836
+ await managePlugin({ ...input(), action: 'update', version: '0.3.22' });
837
+ assert.ok(queuedRollback);
838
+ const error = await queuedRollback;
839
+ assert.ok(error instanceof Error);
840
+ assert.match(error.message, /rollback target changed before/u);
841
+ assert.equal(native.selectionCalls, 1);
842
+ assert.equal(JSON.parse(readFileSync(path, 'utf8')).currentVersion, '0.3.22');
843
+ });
844
+ test('a partial catalog publication resumes with reused units and matches an uninterrupted update', async () => {
845
+ const first = replacementFixture();
846
+ await managePlugin({ ...input(), action: 'update', version: '0.3.22' });
847
+ const statePath = join(dirname(first.catalog), 'state.json');
848
+ const uninterrupted = JSON.parse(readFileSync(statePath, 'utf8'));
849
+ const { catalog, native, policy, before } = replacementFixture();
850
+ const immutableArchive = join(catalog, 'versions/0.3.22/archive.tgz');
851
+ const archiveBefore = readFileSync(immutableArchive);
852
+ const actual = atomicJson.writePrivateJsonFileAtomically;
853
+ let interrupt = true;
854
+ vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
855
+ if (interrupt && path === join(catalog, '.claude-plugin/marketplace.json')) {
856
+ interrupt = false;
857
+ throw new Error('Synthetic catalog publication interruption');
858
+ }
859
+ actual(path, value);
860
+ });
861
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /publication interruption/u);
862
+ assert.equal(native.selectionCalls, 0);
863
+ assert.equal(JSON.parse(readFileSync(join(catalog, '.claude-plugin/marketplace.json'), 'utf8')).plugins[0].version, '0.3.21');
864
+ assert.match(readFileSync(join(catalog, '.agents/plugins/marketplace.json'), 'utf8'), /versions\/0\.3\.22/u);
865
+ const pending = JSON.parse(readFileSync(statePath, 'utf8'));
866
+ pending.pending.owner = { pid: 2_000_000_000, birth: 'terminated publication owner' };
867
+ writeState(pending);
868
+ fixture.commands = [];
869
+ await managePlugin({ ...input(), action: 'update', version: '0.3.22' });
870
+ assert.deepEqual(JSON.parse(readFileSync(statePath, 'utf8')), uninterrupted);
871
+ assert.deepEqual(readFileSync(immutableArchive), archiveBefore);
872
+ assert.equal(fixture.commands.includes('npm'), false);
873
+ assert.equal(native.selectionCalls, 1);
874
+ assert.deepEqual(policy, before);
875
+ });
876
+ test('a failed managed-state commit retains selection and resumes without selecting again', async () => {
877
+ const { native, catalog, policy, before } = replacementFixture();
878
+ const actual = atomicJson.writePrivateJsonFileAtomically;
879
+ const fault = vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
880
+ const state = value;
881
+ if (path.endsWith('/state.json') && state.currentVersion === '0.3.22' && !state.pending)
882
+ throw new Error('Synthetic final state commit failure');
883
+ actual(path, value);
884
+ });
885
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /final state commit failure/u);
886
+ fault.mockRestore();
887
+ const path = join(dirname(catalog), 'state.json');
888
+ const pending = JSON.parse(readFileSync(path, 'utf8'));
889
+ pending.pending.owner = { pid: 2_000_000_000, birth: 'terminated commit owner' };
890
+ writeState(pending);
891
+ await managePlugin({ ...input(), action: 'update', version: '0.3.22' });
892
+ assert.equal(native.selectionCalls, 1);
893
+ assert.deepEqual(policy, before);
894
+ assert.equal(JSON.parse(readFileSync(path, 'utf8')).pending, undefined);
895
+ });
896
+ test.each(['bytes', 'mode'])('managed state %s changed by another writer is not overwritten after native selection', async (change) => {
897
+ const { catalog, native } = replacementFixture();
898
+ const respond = fixture.respond;
899
+ const path = join(dirname(catalog), 'state.json');
900
+ let changed;
901
+ fixture.respond = (args) => {
902
+ const output = respond(args);
903
+ if (args[2] === 'add') {
904
+ if (change === 'mode')
905
+ chmodSync(path, 0o400);
906
+ else {
907
+ const state = JSON.parse(readFileSync(path, 'utf8'));
908
+ state.previousVersion = '0.3.19';
909
+ writeFileSync(path, JSON.stringify(state), { mode: 0o600 });
910
+ }
911
+ changed = readFileSync(path);
912
+ }
913
+ return output;
914
+ };
915
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /Managed state changed/u);
916
+ assert.equal(native.selectionCalls, 1);
917
+ assert.ok(changed);
918
+ assert.deepEqual(readFileSync(path), changed);
919
+ if (change === 'mode')
920
+ assert.equal(lstatSync(path).mode & 0o777, 0o400);
921
+ });
922
+ test('catalog custody changed during preparation refuses before selection without repairing it', async () => {
923
+ const { catalog, native, policy, before } = replacementFixture();
924
+ const respond = fixture.respond;
925
+ const path = join(catalog, '.agents/plugins/marketplace.json');
926
+ fixture.respond = (args) => {
927
+ const output = respond(args);
928
+ if (args[0] === process.execPath)
929
+ chmodSync(path, 0o644);
930
+ return output;
931
+ };
932
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /catalog.*changed/u);
933
+ assert.equal(native.selectionCalls, 0);
934
+ assert.equal(lstatSync(path).mode & 0o777, 0o644);
935
+ assert.deepEqual(policy, before);
936
+ });
443
937
  for (const action of ['install', 'update'])
444
938
  test(`${action} reads back its managed version without capturing an unrelated catalogue over 1 MiB`, async () => {
445
939
  const { entry, cache, catalog } = installationFixture(action);
@@ -455,10 +949,11 @@ for (const action of ['install', 'update'])
455
949
  assert.equal(state.pending, undefined);
456
950
  assert.equal(state.currentVersion, '0.3.22');
457
951
  assert.equal(state.previousVersion, action === 'update' ? '0.3.21' : null);
458
- const mutation = fixture.commandArguments.find((args) => args[2] === (action === 'install' ? 'marketplace' : 'remove'));
952
+ const mutation = fixture.commandArguments.find((args) => args[2] === (action === 'install' ? 'marketplace' : 'add'));
459
953
  assert.deepEqual(mutation, action === 'install'
460
954
  ? ['codex', 'plugin', 'marketplace', 'add', catalog, '--json']
461
- : ['codex', 'plugin', 'remove', 'ai-delivery@ai-delivery-user', '--json']);
955
+ : ['codex', 'plugin', 'add', 'ai-delivery@ai-delivery-user', '--json']);
956
+ assert.equal(fixture.commandArguments.some((args) => args[2] === 'remove'), false);
462
957
  fixture.responses.push(oversizedCatalogue([{ ...entry, enabled: false }]));
463
958
  const doctor = await managePlugin({ ...input(), action: 'doctor', version: undefined });
464
959
  assert.equal(doctor.installed, true);
@@ -530,7 +1025,7 @@ test('interrupted filtered readback resumes the original install without fetchin
530
1025
  state.pending.owner = { pid: 2_000_000_000, birth: 'terminated fixture owner' };
531
1026
  writeFileSync(statePath, JSON.stringify(state), { mode: 0o600 });
532
1027
  const before = readFileSync(join(cache, 'skills/intake/SKILL.md'));
533
- fixture.responses.push('codex-cli 0.153.0', oversizedCatalogue([entry]), JSON.stringify({ installedPath: cache }), oversizedCatalogue([entry]));
1028
+ fixture.responses.push('codex-cli 0.153.0', oversizedCatalogue([entry]), oversizedCatalogue([entry]));
534
1029
  const result = await managePlugin({ ...input(), version: '0.3.22' });
535
1030
  assert.equal(result.installed, true);
536
1031
  assert.equal(result.version, '0.3.22');
@@ -662,11 +1157,11 @@ test('an absent native profile beneath a symlink keeps its identity after creati
662
1157
  });
663
1158
  test('a definitive version preparation failure preserves selection and permits a different valid request', async () => {
664
1159
  const cache = doctorFixture(true);
665
- fixture.responses.unshift('codex-cli 0.153.0');
1160
+ const response = fixture.responses[0];
1161
+ fixture.responses.unshift('codex-cli 0.162.1');
666
1162
  const catalog = join(fixture.home, '.cache/ai-delivery/plugins/codex/user/marketplace');
667
1163
  const catalogPath = join(catalog, '.agents/plugins/marketplace.json');
668
1164
  mkdirSync(dirname(catalogPath), { recursive: true, mode: 0o700 });
669
- writeFileSync(catalogPath, 'unchanged selected catalog', { mode: 0o600 });
670
1165
  const before = readFileSync(catalogPath);
671
1166
  const data = join(fixture.home, 'native-data');
672
1167
  writeFileSync(data, 'preserve native data');
@@ -679,18 +1174,21 @@ test('a definitive version preparation failure preserves selection and permits a
679
1174
  assert.deepEqual(readFileSync(catalogPath), before);
680
1175
  assert.equal(readFileSync(data, 'utf8'), 'preserve native data');
681
1176
  assert.equal(readFileSync(join(cache, 'skills/intake/SKILL.md'), 'utf8'), 'owned skill bytes');
682
- await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.21' }), /Native fixture intentionally unavailable/u);
683
- assert.deepEqual(fixture.commands, ['codex', 'codex', 'npm', 'codex']);
1177
+ fixture.responses.push('codex-cli 0.162.1', response, response);
1178
+ const reused = await managePlugin({ ...input(), action: 'update', version: '0.3.21' });
1179
+ assert.equal(reused.changed, false);
1180
+ assert.equal(fixture.commands.filter((command) => command === 'npm').length, 1);
684
1181
  });
685
1182
  test('failure after catalog selection retains pending recovery before another version', async () => {
686
- doctorFixture(true);
687
- fixture.responses.unshift('codex-cli 0.153.0');
688
- await assert.rejects(managePlugin({ ...input(), action: 'update' }), /Native fixture intentionally unavailable/u);
1183
+ const { native } = replacementFixture();
1184
+ native.failSelection = true;
1185
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /Native fixture intentionally unavailable/u);
689
1186
  const statePath = join(fixture.home, '.cache/ai-delivery/plugins/codex/user/state.json');
690
1187
  const state = JSON.parse(readFileSync(statePath, 'utf8'));
691
- assert.equal(state.pending?.targetVersion, '0.3.21');
692
- await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.22' }), /A live plugin installer still owns this target|Resume the interrupted original plugin command/u);
693
- assert.deepEqual(fixture.commands, ['codex', 'codex', 'codex']);
1188
+ assert.equal(state.pending?.targetVersion, '0.3.22');
1189
+ const before = [...fixture.commandArguments];
1190
+ await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.23' }), /A live plugin installer still owns this target|Resume the interrupted original plugin command/u);
1191
+ assert.deepEqual(fixture.commandArguments, before);
694
1192
  });
695
1193
  test('definitive preparation reports pending-state cleanup failure and preserves its recovery intent', async () => {
696
1194
  const actual = atomicJson.writePrivateJsonFileAtomically;
@@ -710,7 +1208,8 @@ test('definitive preparation reports pending-state cleanup failure and preserves
710
1208
  });
711
1209
  test('an unsupported version archive leaves selection intact and permits a valid version request', async () => {
712
1210
  const cache = doctorFixture(true);
713
- fixture.responses.unshift('codex-cli 0.153.0');
1211
+ const response = fixture.responses[0];
1212
+ fixture.responses.unshift('codex-cli 0.162.1');
714
1213
  const root = join(fixture.home, 'unsupported/package');
715
1214
  const files = {
716
1215
  'package.json': { name: '@aviaratech/ai-delivery', version: '0.3.22' },
@@ -757,8 +1256,10 @@ test('an unsupported version archive leaves selection intact and permits a valid
757
1256
  assert.equal(readFileSync(join(cache, 'skills/intake/SKILL.md'), 'utf8'), 'owned skill bytes');
758
1257
  assert.equal(existsSync(join(fixture.home, '.cache/ai-delivery/plugins/codex/user/marketplace/versions/0.3.22')), false);
759
1258
  fixture.packArchive = '';
760
- await assert.rejects(managePlugin({ ...input(), action: 'update', version: '0.3.21' }), /Native fixture intentionally unavailable/u);
761
- assert.deepEqual(fixture.commands, ['codex', 'codex', 'npm', 'codex']);
1259
+ fixture.responses.push('codex-cli 0.162.1', response, response);
1260
+ const reused = await managePlugin({ ...input(), action: 'update', version: '0.3.21' });
1261
+ assert.equal(reused.changed, false);
1262
+ assert.equal(fixture.commands.filter((command) => command === 'npm').length, 1);
762
1263
  });
763
1264
  test('recovery removes only its recorded incomplete staging directory', async () => {
764
1265
  const version = '0.3.21', directory = join(fixture.home, '.cache/ai-delivery/plugins/codex/user/marketplace/versions');