sneakoscope 8.0.2 → 8.0.3

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 (122) hide show
  1. package/README.md +47 -23
  2. package/config/skills-hash-ledger.v1.json +1 -1
  3. package/crates/sks-core/Cargo.lock +1 -1
  4. package/crates/sks-core/Cargo.toml +1 -1
  5. package/dist/bin/fast-inline.js +55 -13
  6. package/dist/bin/sks-dispatch.js +1 -1
  7. package/dist/cli/command-manifest-lite.js +4 -0
  8. package/dist/cli/command-registry.js +4 -0
  9. package/dist/cli/install-helpers-codex-lb-chain.js +187 -0
  10. package/dist/cli/install-helpers-codex-lb-config.js +74 -8
  11. package/dist/cli/install-helpers.js +89 -44
  12. package/dist/commands/codex-lb.js +117 -19
  13. package/dist/commands/doctor.js +697 -37
  14. package/dist/config/skills-manifest.json +3 -2
  15. package/dist/core/agents/agent-runner-codex-exec.js +5 -3
  16. package/dist/core/codex/codex-config-guard.js +238 -52
  17. package/dist/core/codex-adapter.js +5 -3
  18. package/dist/core/codex-app/menubar/constants.js +10 -1
  19. package/dist/core/codex-app/menubar/global-install.js +288 -0
  20. package/dist/core/codex-app/menubar/installer.js +79 -14
  21. package/dist/core/codex-app/menubar/launch-agent.js +267 -45
  22. package/dist/core/codex-app/menubar/paths.js +3 -0
  23. package/dist/core/codex-app/menubar/rollback.js +55 -7
  24. package/dist/core/codex-app/menubar/status.js +75 -4
  25. package/dist/core/codex-control/codex-0139-image-path-real-probe.js +3 -1
  26. package/dist/core/codex-control/codex-0139-web-search-probe.js +3 -1
  27. package/dist/core/codex-control/codex-app-server-runtime-env.js +13 -4
  28. package/dist/core/codex-control/codex-app-server-v2-client.js +3 -3
  29. package/dist/core/codex-exec-output-schema.js +4 -1
  30. package/dist/core/codex-lb/codex-lb-env.js +63 -72
  31. package/dist/core/codex-lb/codex-lb-setup.js +15 -2
  32. package/dist/core/codex-lb/desktop-center-credentials.js +517 -58
  33. package/dist/core/codex-lb/desktop-controller.js +153 -24
  34. package/dist/core/codex-lb/routing-truth.js +327 -0
  35. package/dist/core/codex-native/core-skill-manifest.js +1 -1
  36. package/dist/core/commands/basic-cli.js +7 -1
  37. package/dist/core/commands/qa-loop-command.js +3 -1
  38. package/dist/core/commands/telegram-command.js +241 -0
  39. package/dist/core/config-adopt/config-adopt-command.js +35 -0
  40. package/dist/core/config-adopt/config-adopt.js +346 -0
  41. package/dist/core/config-adopt/index.js +3 -0
  42. package/dist/core/doctor/command-alias-cleanup.js +4 -1
  43. package/dist/core/doctor/current-project-guidance-nested.js +37 -6
  44. package/dist/core/doctor/current-project-guidance.js +11 -6
  45. package/dist/core/doctor/doctor-readiness-matrix.js +14 -0
  46. package/dist/core/doctor/retired-managed-residue-private.js +1 -1
  47. package/dist/core/doctor/sks-menubar-doctor.js +4 -0
  48. package/dist/core/feature-fixtures.js +8 -0
  49. package/dist/core/hooks-runtime/hook-context.js +9 -0
  50. package/dist/core/hooks-runtime/managed-skill-admission.js +54 -4
  51. package/dist/core/hooks-runtime/official-subagent-lifecycle.js +69 -1
  52. package/dist/core/hooks-runtime/subagent-skill-availability-contract.js +2 -2
  53. package/dist/core/hooks-runtime/subagent-skill-availability-evidence.js +3 -3
  54. package/dist/core/hooks-runtime/subagent-skill-availability-guards.js +43 -5
  55. package/dist/core/hooks-runtime/subagent-skill-availability.js +64 -30
  56. package/dist/core/hooks-runtime/subagent-stop-hook.js +15 -2
  57. package/dist/core/hooks-runtime.js +148 -4
  58. package/dist/core/imagegen/imagegen-capability.js +46 -0
  59. package/dist/core/imagegen/require-imagegen.js +2 -2
  60. package/dist/core/init/skills.js +17 -3
  61. package/dist/core/install/installed-package-smoke.js +8 -2
  62. package/dist/core/naruto/hardware-capacity-probe.js +9 -3
  63. package/dist/core/naruto/naruto-concurrency-governor.js +68 -24
  64. package/dist/core/perf/import-graph-budget.js +0 -1
  65. package/dist/core/product-design-app-server.js +13 -1
  66. package/dist/core/release/package-size-budget.js +2 -2
  67. package/dist/core/release/release-pack-receipt.js +1 -2
  68. package/dist/core/routes/dollar-manifest-lite.js +1 -1
  69. package/dist/core/routes.js +1 -1
  70. package/dist/core/security/private-credential-file.js +209 -0
  71. package/dist/core/subagents/agent-catalog.js +17 -32
  72. package/dist/core/subagents/naruto-help-contract.js +5 -5
  73. package/dist/core/subagents/official-subagent-config.js +16 -6
  74. package/dist/core/subagents/official-subagent-preparation.js +34 -15
  75. package/dist/core/subagents/official-subagent-prompt.js +4 -4
  76. package/dist/core/subagents/official-subagent-runner.js +27 -4
  77. package/dist/core/subagents/thread-budget.js +19 -12
  78. package/dist/core/subagents/wave-lifecycle.js +18 -6
  79. package/dist/core/telegram/access.js +54 -0
  80. package/dist/core/telegram/client.js +144 -0
  81. package/dist/core/telegram/confirmation.js +37 -0
  82. package/dist/core/telegram/doctor.js +151 -0
  83. package/dist/core/telegram/index.js +9 -0
  84. package/dist/core/telegram/keychain.js +265 -0
  85. package/dist/core/telegram/liveness.js +109 -0
  86. package/dist/core/telegram/poller.js +90 -0
  87. package/dist/core/telegram/redaction.js +15 -0
  88. package/dist/core/telegram/types.js +1 -0
  89. package/dist/core/update/update-diagnostics.js +52 -0
  90. package/dist/core/update/update-migration-state.js +5 -1
  91. package/dist/core/update/update-operation.js +2 -1
  92. package/dist/core/update/update-stage-diagnostics.js +38 -0
  93. package/dist/core/update/update-status.js +2 -9
  94. package/dist/core/update-check.js +147 -31
  95. package/dist/core/version.js +1 -1
  96. package/dist/core/zellij/zellij-launcher.js +23 -4
  97. package/dist/native/sks-menubar/Sources/AppDelegate.swift +13 -0
  98. package/dist/native/sks-menubar/Sources/AppIdentity.swift +7 -0
  99. package/dist/native/sks-menubar/Sources/OperationCoordinator.swift +3 -2
  100. package/dist/native/sks-menubar/Sources/ProvidersConnectTest.swift +115 -0
  101. package/dist/native/sks-menubar/Sources/ProvidersFastMode.swift +17 -0
  102. package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +190 -0
  103. package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +100 -59
  104. package/dist/native/sks-menubar/Sources/SingletonInstanceGuard.swift +328 -0
  105. package/dist/native/sks-menubar/Sources/TelegramPrivateFileStore.swift +320 -0
  106. package/dist/native/sks-menubar/Sources/TelegramPrivateFileSupport.swift +303 -0
  107. package/dist/native/sks-menubar/Sources/TelegramProcessGateway.swift +238 -0
  108. package/dist/native/sks-menubar/Sources/TelegramRuntimeSupport.swift +56 -0
  109. package/dist/native/sks-menubar/Sources/TelegramSupport.swift +56 -0
  110. package/dist/native/sks-menubar/Sources/TelegramTransport.swift +474 -0
  111. package/dist/native/sks-menubar/Sources/main.swift +15 -1
  112. package/dist/native/sks-menubar/Tests/OperationCoordinatorTests.swift +4 -3
  113. package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +129 -0
  114. package/dist/native/sks-menubar/Tests/SingletonInstanceGuardTests.swift +183 -0
  115. package/dist/native/sks-menubar/Tests/TelegramRuntimeSmokeTests.swift +267 -0
  116. package/dist/native/sks-menubar/Tests/TelegramRuntimeTests.swift +222 -0
  117. package/dist/scripts/codex-lb-fast-mode-truth-check.js +1 -1
  118. package/dist/scripts/codex-lb-fast-ui-preservation-check.js +1 -1
  119. package/dist/scripts/current-command-surface-check.js +2 -4
  120. package/dist/scripts/official-subagent-workflow-check.js +1 -1
  121. package/dist/scripts/packlist-performance-check.js +1 -2
  122. package/package.json +1 -1
@@ -122,6 +122,7 @@ export function commandAliasCleanupReport(opts, skillResidue = emptySkillResidue
122
122
  ...(projectGuidance.error_count ? [`current_project_guidance_reconcile_failed:${projectGuidance.error_count}`] : [])
123
123
  ];
124
124
  const ok = blockers.length === 0;
125
+ const warnings = projectGuidance.warnings.map((warning) => `${warning.code}:${warning.cutoff_path}:${warning.exceeded_directory_count}`);
125
126
  return {
126
127
  schema: COMMAND_ALIAS_CLEANUP_SCHEMA,
127
128
  ok,
@@ -165,6 +166,7 @@ export function commandAliasCleanupReport(opts, skillResidue = emptySkillResidue
165
166
  ok: false,
166
167
  detail: 'Rewrite legacy commands inside skills, remove OMX/DCodex from the live surface, and reconcile retired SKS-managed residue.'
167
168
  }],
169
+ warnings,
168
170
  blockers
169
171
  };
170
172
  }
@@ -177,7 +179,8 @@ function emptyProjectGuidance(fix) {
177
179
  reconciled_count: 0,
178
180
  remaining_count: 0,
179
181
  preserved_user_file_count: 0,
180
- error_count: 0
182
+ error_count: 0,
183
+ warnings: []
181
184
  };
182
185
  }
183
186
  function emptyManagedResidue(fix) {
@@ -4,15 +4,23 @@ import { inspectConfinedPath } from '../managed-path-safety.js';
4
4
  const NESTED_AGENTS_MAX_DEPTH = 12;
5
5
  const NESTED_AGENTS_MAX_DIRECTORIES = 4096;
6
6
  const NESTED_AGENTS_SKIPPED_DIRECTORIES = new Set([
7
+ '.cache',
7
8
  '.git',
8
9
  '.next',
9
10
  '.sneakoscope',
11
+ '.tox',
10
12
  '.turbo',
13
+ '.venv',
14
+ '__pycache__',
11
15
  'build',
12
16
  'coverage',
17
+ 'deriveddata',
13
18
  'dist',
14
19
  'node_modules',
15
- 'out'
20
+ 'out',
21
+ 'pods',
22
+ 'target',
23
+ 'venv'
16
24
  ]);
17
25
  export async function collectNestedProjectRoots(projectRoot, excludedRoots) {
18
26
  const roots = new Set();
@@ -20,10 +28,17 @@ export async function collectNestedProjectRoots(projectRoot, excludedRoots) {
20
28
  const excluded = new Set([...excludedRoots].map((root) => path.resolve(root)));
21
29
  let cursor = 0;
22
30
  let errorCount = 0;
23
- let truncated = false;
31
+ let cutoffPath = null;
32
+ let cutoffReason = null;
33
+ let exceededDirectoryCount = 0;
34
+ const recordCutoff = (target, reason) => {
35
+ cutoffPath ||= path.resolve(target);
36
+ cutoffReason ||= reason;
37
+ exceededDirectoryCount += 1;
38
+ };
24
39
  while (cursor < queue.length) {
25
40
  if (cursor >= NESTED_AGENTS_MAX_DIRECTORIES) {
26
- truncated = true;
41
+ recordCutoff(queue[cursor]?.directory || projectRoot, 'directory_limit');
27
42
  break;
28
43
  }
29
44
  const current = queue[cursor++];
@@ -62,15 +77,31 @@ export async function collectNestedProjectRoots(projectRoot, excludedRoots) {
62
77
  continue;
63
78
  }
64
79
  if (current.depth >= NESTED_AGENTS_MAX_DEPTH) {
65
- truncated = true;
80
+ recordCutoff(target, 'depth_limit');
66
81
  continue;
67
82
  }
68
83
  if (queue.length >= NESTED_AGENTS_MAX_DIRECTORIES) {
69
- truncated = true;
84
+ recordCutoff(target, 'directory_limit');
70
85
  continue;
71
86
  }
72
87
  queue.push({ directory: target, depth: current.depth + 1 });
73
88
  }
74
89
  }
75
- return { roots: [...roots].sort(), errorCount, truncated };
90
+ const warnings = cutoffPath && cutoffReason
91
+ ? [{
92
+ code: 'guidance_scan_truncated',
93
+ cutoff_path: cutoffPath,
94
+ cutoff_reason: cutoffReason,
95
+ visited_directory_count: cursor,
96
+ exceeded_directory_count: exceededDirectoryCount,
97
+ directory_limit: NESTED_AGENTS_MAX_DIRECTORIES,
98
+ depth_limit: NESTED_AGENTS_MAX_DEPTH
99
+ }]
100
+ : [];
101
+ return {
102
+ roots: [...roots].sort(),
103
+ errorCount,
104
+ truncated: warnings.length > 0,
105
+ warnings
106
+ };
76
107
  }
@@ -41,7 +41,14 @@ export async function reconcileCurrentProjectGuidance(opts) {
41
41
  { root: home, installScope: 'global' },
42
42
  { root: globalRuntimeRoot, installScope: 'global' }
43
43
  ]);
44
- const counters = { detected: 0, reconciled: 0, remaining: 0, preserved: 0, errors: 0 };
44
+ const counters = {
45
+ detected: 0,
46
+ reconciled: 0,
47
+ remaining: 0,
48
+ preserved: 0,
49
+ errors: 0,
50
+ warnings: []
51
+ };
45
52
  const runId = `${Date.now()}-${process.pid}`;
46
53
  for (const scope of scopes) {
47
54
  await reconcileGuidanceScope(scope, opts.fix, runId, counters);
@@ -57,7 +64,8 @@ export async function reconcileCurrentProjectGuidance(opts) {
57
64
  reconciled_count: counters.reconciled,
58
65
  remaining_count: counters.remaining,
59
66
  preserved_user_file_count: counters.preserved,
60
- error_count: counters.errors
67
+ error_count: counters.errors,
68
+ warnings: counters.warnings
61
69
  };
62
70
  }
63
71
  async function reconcileGuidanceScope(scope, fix, runId, counters) {
@@ -136,10 +144,7 @@ async function reconcileNestedProjectGuidance(projectRoot, excludedRoots, fix, r
136
144
  counters.errors += scan.errorCount;
137
145
  counters.remaining += scan.errorCount;
138
146
  }
139
- if (scan.truncated) {
140
- counters.errors += 1;
141
- counters.remaining += 1;
142
- }
147
+ counters.warnings.push(...scan.warnings);
143
148
  const scope = { root: projectRoot, installScope: 'project' };
144
149
  const quarantineRoot = path.join(projectRoot, '.sneakoscope', 'quarantine', 'current-project-guidance', runId);
145
150
  for (const root of scan.roots) {
@@ -63,6 +63,13 @@ export function buildDoctorReadinessMatrix(input = {}) {
63
63
  warnings.add('codex_app_fast_selector_repaired_restart_app_if_needed');
64
64
  if (input.sks_menubar?.ok === false)
65
65
  warnings.add(`sks_menubar_${input.sks_menubar?.status || 'blocked'}`);
66
+ const telegramRemote = input.telegram_remote || null;
67
+ if (telegramRemote?.status === 'degraded') {
68
+ for (const blocker of normalizeList(telegramRemote.blockers))
69
+ warnings.add(`telegram_remote:${blocker}`);
70
+ if (!normalizeList(telegramRemote.blockers).length)
71
+ warnings.add('telegram_remote_degraded');
72
+ }
66
73
  const codex0138Doctor = input.codex_0138_doctor || null;
67
74
  if (codex0138Doctor?.ok === false)
68
75
  for (const blocker of normalizeList(codex0138Doctor.blockers))
@@ -84,6 +91,13 @@ export function buildDoctorReadinessMatrix(input = {}) {
84
91
  warnings.add(`codex_app_harness:${blocker}`);
85
92
  if (input.codex_lb?.ok === false)
86
93
  warnings.add(`codex_lb_${input.codex_lb?.circuit?.state || 'blocked'}`);
94
+ if (input.codex_lb?.provider_status?.selected === true && input.codex_lb?.routing_ok !== true) {
95
+ const routingBlockers = normalizeList(input.codex_lb?.routing_truth?.blockers);
96
+ for (const blocker of routingBlockers)
97
+ blockers.add(blocker);
98
+ if (!routingBlockers.length)
99
+ blockers.add('codex_lb_routing_truth_unverified');
100
+ }
87
101
  const localModel = input.local_model || {};
88
102
  const localStatus = String(localModel.status || (localModel.enabled ? 'enabled_unverified' : 'disabled'));
89
103
  if (localModel.enabled === true && localStatus === 'enabled_unverified')
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { inspectConfinedPath, moveConfinedPath, removeEmptyTreeVerified, uniqueConfinedPath, walkConfinedEntries } from '../managed-path-safety.js';
3
3
  import { escapeRegExp } from '../text/regex.js';
4
- export const REMOVED_PUBLIC_COMMANDS = ['team', 'mad-db', 'tmux', 'xai', 'swarm', 'agent', 'ralph', 'ui', 'glm', 'telegram'];
4
+ export const REMOVED_PUBLIC_COMMANDS = ['team', 'mad-db', 'tmux', 'xai', 'swarm', 'agent', 'ralph', 'ui', 'glm'];
5
5
  const RETIRED_COMMAND_TOMBSTONES = new Set(REMOVED_PUBLIC_COMMANDS);
6
6
  const RETIRED_MISSION_MODES = new Set([
7
7
  ...REMOVED_PUBLIC_COMMANDS,
@@ -12,6 +12,10 @@ export function buildSksMenuBarDoctorPostcheck(status) {
12
12
  blockers.push('menubar_status_not_ok');
13
13
  return {
14
14
  ok: blockers.length === 0,
15
+ installed_version: status.installed_version || null,
16
+ running_version: status.running_process?.package_version || null,
17
+ running_pid: status.running_process?.pid || null,
18
+ menubar_version_probe: status.menubar_version_probe || null,
15
19
  blockers,
16
20
  warnings: [
17
21
  ...(status.warnings || []),
@@ -21,10 +21,18 @@ const FIXTURES = Object.freeze({
21
21
  }),
22
22
  'cli-paths': fixture('execute_and_validate_artifacts', 'sks paths managed --json', ['.sneakoscope/managed-paths.json'], 'pass'),
23
23
  'cli-rollback': fixture('execute', 'sks rollback list --json', [], 'pass'),
24
+ 'cli-config': fixture('execute', 'sks config --help', [], 'pass', {
25
+ quality: 'wiring_only',
26
+ reason: 'The non-mutating help path proves the installed config command is wired; config-adopt mutation and dry-run behavior are covered by focused config-adopt tests.'
27
+ }),
24
28
  'cli-setup': fixture('real_optional', 'sks setup --json --local-only', [], 'pass'),
25
29
  'cli-codex': fixture('execute', 'sks codex compatibility --json', [], 'pass'),
26
30
  'cli-codex-app': fixture('real_optional', 'sks codex-app check --json', [], 'pass'),
27
31
  'cli-codex-lb': fixture('execute_and_validate_artifacts', 'sks codex-lb metrics --json', [], 'pass'),
32
+ 'cli-telegram': fixture('execute', 'sks telegram --help', [], 'pass', {
33
+ quality: 'wiring_only',
34
+ reason: 'The non-mutating help path proves the installed Telegram command is wired without requiring a bot token, private-file state, resident poller, or network access; transport behavior is covered by focused Telegram tests.'
35
+ }),
28
36
  'cli-mcp': fixture('execute', 'sks mcp config list --scope project --trusted-project --json', [], 'pass', {
29
37
  reason: 'Project-scoped MCP inventory is a read-only, hermetic runtime probe when the trusted-project boundary is explicit; mutation, health, auth, and merge behavior remain covered by dedicated tests.'
30
38
  }),
@@ -232,6 +232,15 @@ export function shouldPrepareFreshRouteOnActivePrompt(prompt, route = null, opts
232
232
  return false;
233
233
  return routeRequiresSubagents(route, prompt);
234
234
  }
235
+ export function looksLikeExplicitActiveWorkflowReplacementPrompt(prompt) {
236
+ const normalized = String(prompt || '').trim().toLowerCase();
237
+ if (!normalized)
238
+ return false;
239
+ return /\b(?:cancel|replace|supersede|discard|abandon|restart)\b[\s\S]{0,48}\b(?:current|active|old|previous|workflow|run|task|mission)\b/.test(normalized)
240
+ || /\b(?:start over|switch to a new task)\b/.test(normalized)
241
+ || /(?:현재|기존|이전)[^\n]{0,32}(?:작업|워크플로|실행|미션)[^\n]{0,24}(?:취소|교체|대체|폐기|중단)/.test(normalized)
242
+ || /(?:취소|교체|대체|폐기|중단)[^\n]{0,24}(?:새 작업|새로운 작업|다른 작업)/.test(normalized);
243
+ }
235
244
  function isClarificationAwaiting(state = {}) {
236
245
  const phase = String(state.phase || '');
237
246
  const stopGate = String(state.stop_gate || '');
@@ -1,17 +1,67 @@
1
1
  import { resolveAuthoritativeSksSkillSources } from '../codex-native/sks-skill-paths.js';
2
2
  import { healAuthoritativeManagedSkillDigestMismatches, managedSkillResolutionIsHealable } from './managed-skill-generation-heal.js';
3
- export async function resolveManagedSkillSourcesForAdmission(input) {
4
- const resolution = await resolveAuthoritativeSksSkillSources(input);
3
+ const DEFAULT_DEPENDENCIES = {
4
+ resolveSources: resolveAuthoritativeSksSkillSources,
5
+ repairGeneration: healAuthoritativeManagedSkillDigestMismatches
6
+ };
7
+ const VERIFIED_GENERATION_RECOVERY_REASONS = new Set([
8
+ 'version_mismatch',
9
+ 'manifest_missing',
10
+ 'manifest_digest_mismatch',
11
+ 'installed_content_mismatch'
12
+ ]);
13
+ export async function resolveManagedSkillSourcesForAdmission(input, dependencies = DEFAULT_DEPENDENCIES) {
14
+ const resolution = await dependencies.resolveSources(input);
5
15
  const repairMode = input.repairMode || 'stale-generation';
6
16
  if (repairMode === 'none' || !managedSkillResolutionIsHealable(resolution)) {
7
17
  return resolution;
8
18
  }
9
- const recovery = await healAuthoritativeManagedSkillDigestMismatches({
19
+ const recovery = await dependencies.repairGeneration({
10
20
  root: input.root,
11
21
  ...(input.home !== undefined ? { home: input.home } : {}),
12
22
  resolution,
13
23
  generationOnly: true
14
24
  });
15
- const rechecked = await resolveAuthoritativeSksSkillSources(input);
25
+ const rechecked = await dependencies.resolveSources(input);
26
+ if (!recoveryVerifiesWholeGeneration(resolution, recovery)) {
27
+ return { ...resolution, recovery };
28
+ }
16
29
  return { ...rechecked, recovery };
17
30
  }
31
+ function recoveryVerifiesWholeGeneration(resolution, recovery) {
32
+ if (recovery?.attempted !== true
33
+ || !Number.isSafeInteger(recovery.healed_count)
34
+ || !Array.isArray(recovery.attempts)) {
35
+ return false;
36
+ }
37
+ const unresolved = new Set(resolution.unresolved);
38
+ const blockers = new Set(resolution.blockers);
39
+ const expectedAttempts = new Set(resolution.issues
40
+ .filter((issue) => (issue.reason === 'content_digest_mismatch'
41
+ && issue.scope === 'global'
42
+ && unresolved.has(issue.canonical_name)
43
+ && blockers.has(`content_digest_mismatch:${issue.canonical_name}:global`)))
44
+ .map((issue) => `${issue.canonical_name}\0${issue.path}`));
45
+ if (!expectedAttempts.size
46
+ || recovery.healed_count !== expectedAttempts.size
47
+ || recovery.attempts.length !== expectedAttempts.size) {
48
+ return false;
49
+ }
50
+ const verifiedAttempts = new Set();
51
+ for (const attempt of recovery.attempts) {
52
+ const reason = String(attempt?.reason || '');
53
+ const reasonPrefix = 'stale_global_generation_reconciled:';
54
+ const generationReason = reason.startsWith(reasonPrefix)
55
+ ? reason.slice(reasonPrefix.length)
56
+ : '';
57
+ const key = `${String(attempt?.canonical_skill || '')}\0${String(attempt?.original_path || '')}`;
58
+ if (attempt?.status !== 'healed'
59
+ || !VERIFIED_GENERATION_RECOVERY_REASONS.has(generationReason)
60
+ || !expectedAttempts.has(key)
61
+ || verifiedAttempts.has(key)) {
62
+ return false;
63
+ }
64
+ verifiedAttempts.add(key);
65
+ }
66
+ return verifiedAttempts.size === expectedAttempts.size;
67
+ }
@@ -14,8 +14,70 @@ import { HOST_CAPABILITY_HOOK_EVIDENCE_FILENAME, HOST_CAPABILITY_HOOK_OBSERVATIO
14
14
  import { observedParentModelMismatch } from './payload-signals.js';
15
15
  import { finalizeNarutoTerminalProof } from './naruto-terminal-finalization.js';
16
16
  import { subagentSkillAvailabilityRunBlockers } from './subagent-skill-availability.js';
17
+ import { MAX_LIFECYCLE_THREADS } from './subagent-skill-availability-contract.js';
17
18
  const SUBAGENT_LIFECYCLE_CAPTURE_FAILURE_SCHEMA = 'sks.subagent-lifecycle-capture-failure.v1';
18
19
  const MAX_SUBAGENT_LIFECYCLE_CAPTURE_FAILURES = 528;
20
+ export async function inspectActiveOfficialSubagentWorkflow(root, state, sessionKey = null) {
21
+ const missionId = String(state?.mission_id || '').trim();
22
+ const workflowRunId = String(state?.official_subagent_run_id || '').trim();
23
+ if (!missionId || !workflowRunId || state?.route_closed === true)
24
+ return { status: 'inactive' };
25
+ const ownedSession = String(state?.session_scope || '').trim();
26
+ const currentSession = String(sessionKey || '').trim();
27
+ if (ownedSession && currentSession && ownedSession !== currentSession) {
28
+ return { status: 'invalid', missionId, workflowRunId, reason: 'session_scope_mismatch' };
29
+ }
30
+ const artifactDir = officialSubagentArtifactDir(root, state, sessionKey);
31
+ try {
32
+ await ensureOfficialSubagentArtifactDirConfined(root, artifactDir);
33
+ const plan = await readJson(path.join(artifactDir, 'subagent-plan.json'), null);
34
+ if (plan?.schema !== 'sks.subagent-plan.v1'
35
+ || plan?.workflow !== 'official_codex_subagent'
36
+ || String(plan?.mission_id || '').trim() !== missionId
37
+ || String(plan?.workflow_run_id || '').trim() !== workflowRunId) {
38
+ return { status: 'invalid', missionId, workflowRunId, reason: 'active_plan_binding_invalid' };
39
+ }
40
+ const gate = await readJson(path.join(artifactDir, 'naruto-gate.json'), null).catch(() => null);
41
+ if (gate?.terminal === true
42
+ && gate?.passed === true
43
+ && String(gate?.workflow_run_id || '').trim() === workflowRunId) {
44
+ return { status: 'inactive' };
45
+ }
46
+ const events = (await readSubagentEvents(artifactDir)).filter((event) => event.run_id === workflowRunId);
47
+ const liveThreads = new Set();
48
+ for (const event of events) {
49
+ if (!event.thread_id)
50
+ continue;
51
+ if (event.event_name === 'SubagentStart')
52
+ liveThreads.add(event.thread_id);
53
+ else if (event.event_name === 'SubagentStop')
54
+ liveThreads.delete(event.thread_id);
55
+ }
56
+ if (liveThreads.size > MAX_LIFECYCLE_THREADS) {
57
+ return { status: 'invalid', missionId, workflowRunId, reason: 'active_event_bound_exceeded' };
58
+ }
59
+ const lifecycle = plan?.wave_lifecycle;
60
+ if (lifecycle != null) {
61
+ const openThreads = Number(lifecycle?.open_threads);
62
+ if (lifecycle?.schema !== 'sks.subagent-wave-lifecycle.v1'
63
+ || lifecycle?.owner !== 'root_parent'
64
+ || String(lifecycle?.workflow_run_id || '').trim() !== workflowRunId
65
+ || !Number.isSafeInteger(openThreads)
66
+ || openThreads < 0
67
+ || openThreads > MAX_LIFECYCLE_THREADS) {
68
+ return { status: 'invalid', missionId, workflowRunId, reason: 'active_lifecycle_invalid' };
69
+ }
70
+ if (events.length > 0 && openThreads !== liveThreads.size) {
71
+ return { status: 'invalid', missionId, workflowRunId, reason: 'active_lifecycle_event_mismatch' };
72
+ }
73
+ return { status: 'active', missionId, workflowRunId, openThreads };
74
+ }
75
+ return { status: 'active', missionId, workflowRunId, openThreads: liveThreads.size };
76
+ }
77
+ catch {
78
+ return { status: 'invalid', missionId, workflowRunId, reason: 'active_workflow_inspection_failed' };
79
+ }
80
+ }
19
81
  export async function recordAndRefreshSubagentEvidence(root, state, payload, eventName, sessionKey = null) {
20
82
  const artifactDir = officialSubagentArtifactDir(root, state, sessionKey);
21
83
  await ensureOfficialSubagentArtifactDirConfined(root, artifactDir);
@@ -43,7 +105,10 @@ export async function recordAndRefreshSubagentEvidence(root, state, payload, eve
43
105
  return null;
44
106
  const priorEvents = await readSubagentEvents(artifactDir);
45
107
  let boundRunId = explicitRunId;
46
- if (!boundRunId && eventName === 'SubagentStop' && normalizedInputEvent?.thread_id) {
108
+ if (!boundRunId
109
+ && eventName === 'SubagentStop'
110
+ && normalizedInputEvent?.thread_id
111
+ && String(payload?.turn_id || '').trim()) {
47
112
  const matchingStartRuns = [...new Set(priorEvents
48
113
  .filter((row) => row.event_name === 'SubagentStart'
49
114
  && row.thread_id === normalizedInputEvent.thread_id
@@ -55,6 +120,9 @@ export async function recordAndRefreshSubagentEvidence(root, state, payload, eve
55
120
  if (!boundRunId)
56
121
  return null;
57
122
  }
123
+ else if (!boundRunId && eventName === 'SubagentStop') {
124
+ return null;
125
+ }
58
126
  else if (!boundRunId) {
59
127
  boundRunId = workflowRunId || null;
60
128
  }
@@ -1,9 +1,10 @@
1
+ import { HARD_NARUTO_MAX_THREADS } from '../subagents/thread-budget.js';
1
2
  export const SUBAGENT_SKILL_AVAILABILITY_BLOCKER_FILENAME = 'subagent-skill-availability-blocker.json';
2
3
  export const SUBAGENT_SKILL_AVAILABILITY_BLOCKER_SCHEMA = 'sks.subagent-skill-availability-blocker.v1';
3
4
  export const GUARD_DIR = 'subagent-skill-availability';
4
5
  export const EMERGENCY_DENIAL_DIR = 'subagent-skill-availability-emergency-denials';
5
- export const MAX_EMERGENCY_DENIALS = 64;
6
6
  export const MAX_LIFECYCLE_THREADS = HARD_NARUTO_MAX_THREADS;
7
+ export const MAX_EMERGENCY_DENIALS = MAX_LIFECYCLE_THREADS;
7
8
  export const MAX_GUARD_DIRECTORY_ENTRIES = (HARD_NARUTO_MAX_THREADS * 2) + 16;
8
9
  export const MAX_LIFECYCLE_GUARD_BYTES = 64 * 1024;
9
10
  export const MAX_SUBAGENT_PLAN_BYTES = 256 * 1024;
@@ -28,4 +29,3 @@ export function validBlocker(value) {
28
29
  && value.blockers.length > 0
29
30
  && value.blockers.every((item) => (SUBAGENT_ADMISSION_BLOCKER_RE.test(String(item || ''))));
30
31
  }
31
- import { HARD_NARUTO_MAX_THREADS } from '../subagents/thread-budget.js';
@@ -135,7 +135,7 @@ async function clearMatchingEmergencyDenials(root, artifactDir, threadHash) {
135
135
  }
136
136
  async function pruneEmergencyDenials(root, artifactDir) {
137
137
  const dir = emergencyDenialDir(artifactDir);
138
- const records = await readEmergencyDenialsWithFiles(root, artifactDir);
138
+ const records = await readEmergencyDenialsWithFiles(root, artifactDir, MAX_EMERGENCY_DENIALS + 1);
139
139
  if (records === null)
140
140
  return false;
141
141
  const ordered = records
@@ -159,7 +159,7 @@ async function readEmergencyDenials(root, artifactDir) {
159
159
  const records = await readEmergencyDenialsWithFiles(root, artifactDir);
160
160
  return records === null ? [null] : records.map((entry) => entry.blocker);
161
161
  }
162
- async function readEmergencyDenialsWithFiles(root, artifactDir) {
162
+ async function readEmergencyDenialsWithFiles(root, artifactDir, maxEntries = MAX_EMERGENCY_DENIALS) {
163
163
  const dir = emergencyDenialDir(artifactDir);
164
164
  let inspected;
165
165
  try {
@@ -172,7 +172,7 @@ async function readEmergencyDenialsWithFiles(root, artifactDir) {
172
172
  return [];
173
173
  if (inspected.leafSymlink || !inspected.stat?.isDirectory())
174
174
  return null;
175
- const names = await boundedDirectoryNames(dir, MAX_EMERGENCY_DENIALS);
175
+ const names = await boundedDirectoryNames(dir, maxEntries);
176
176
  if (names === null)
177
177
  return null;
178
178
  const records = [];
@@ -4,7 +4,7 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { sha256, writeJsonAtomic } from '../fsx.js';
6
6
  import { ensureConfinedDirectory, inspectConfinedPath, removeManagedPathVerified } from '../managed-path-safety.js';
7
- import { ADMISSION_SCHEMA, GUARD_DIR, MAX_GUARD_DIRECTORY_ENTRIES, MAX_LIFECYCLE_GUARD_BYTES, MAX_SUBAGENT_PLAN_BYTES, SUBAGENT_ADMISSION_BLOCKER_RE, SubagentSkillAvailabilityGuardError } from './subagent-skill-availability-contract.js';
7
+ import { ADMISSION_SCHEMA, GUARD_DIR, MAX_GUARD_DIRECTORY_ENTRIES, MAX_LIFECYCLE_GUARD_BYTES, MAX_LIFECYCLE_THREADS, MAX_SUBAGENT_PLAN_BYTES, SUBAGENT_ADMISSION_BLOCKER_RE, SubagentSkillAvailabilityGuardError } from './subagent-skill-availability-contract.js';
8
8
  const MAX_OFFICIAL_TRANSCRIPT_FIRST_LINE_BYTES = 64 * 1024;
9
9
  const MAX_OFFICIAL_TRANSCRIPT_DISCOVERY_ENTRIES = 4_096;
10
10
  const MAX_OFFICIAL_TRANSCRIPT_DISCOVERY_DEPTH = 4;
@@ -41,7 +41,7 @@ export async function readConfinedJson(boundary, file) {
41
41
  const result = await readBoundedConfinedJson(path.resolve(boundary), path.resolve(file), MAX_SUBAGENT_PLAN_BYTES);
42
42
  return result.status === 'value' ? result.value : null;
43
43
  }
44
- export async function admissionGuardRoots(root, artifactDir) {
44
+ export async function admissionGuardRoots(root, artifactDir, binding) {
45
45
  const projectRoot = path.resolve(root);
46
46
  const canonicalRoot = await fsp.realpath(projectRoot);
47
47
  const home = path.resolve(process.env.HOME || os.homedir());
@@ -54,15 +54,30 @@ export async function admissionGuardRoots(root, artifactDir) {
54
54
  }] : []),
55
55
  { root: homeGuardDir(home, canonicalRoot), boundary: home, missionIndependent: true }
56
56
  ];
57
+ const missionId = String(binding?.missionId || '').trim();
58
+ const workflowRunId = String(binding?.workflowRunId || '').trim();
59
+ const runPartition = missionId && workflowRunId
60
+ ? `run-${sha256(JSON.stringify([missionId, workflowRunId]))}`
61
+ : null;
57
62
  const unique = new Map();
58
63
  for (const entry of roots) {
59
64
  const previous = unique.get(entry.root);
60
65
  if (!previous || (!previous.missionIndependent && entry.missionIndependent)) {
61
- unique.set(entry.root, entry);
66
+ unique.set(entry.root, {
67
+ ...entry,
68
+ root: runPartition ? path.join(entry.root, runPartition) : entry.root
69
+ });
62
70
  }
63
71
  }
64
72
  return [...unique.values()];
65
73
  }
74
+ export async function admissionGuardRootsWithLegacyMirrors(root, artifactDir, binding) {
75
+ const [scoped, legacy] = await Promise.all([
76
+ admissionGuardRoots(root, artifactDir, binding),
77
+ admissionGuardRoots(root, artifactDir)
78
+ ]);
79
+ return { scoped, legacy };
80
+ }
66
81
  export async function writeAdmissionPair(root, admission) {
67
82
  const [threadWrite, turnWrite] = await Promise.all([
68
83
  safeWriteJson(threadGuardPath(root.root, admission.thread_id_hash), root.boundary, admission),
@@ -78,8 +93,19 @@ export async function readAdmissionPair(root, expectedThreadHash, expectedSessio
78
93
  const threadAdmission = await readAdmission(threadFile, root.boundary);
79
94
  if (!turnAdmission && !threadAdmission)
80
95
  return null;
81
- if (!turnAdmission || !threadAdmission)
96
+ if (!turnAdmission && threadAdmission) {
97
+ if (threadAdmission.thread_id_hash !== expectedThreadHash)
98
+ throw invalidGuard(true);
99
+ const currentTurnPartiallyPersisted = threadAdmission.session_scope_hash === expectedSessionHash
100
+ && threadAdmission.turn_id_hash === expectedTurnHash;
101
+ if (currentTurnPartiallyPersisted)
102
+ throw invalidGuard(true);
103
+ return null;
104
+ }
105
+ if (turnAdmission && !threadAdmission)
82
106
  throw invalidGuard(true);
107
+ if (!turnAdmission || !threadAdmission)
108
+ return null;
83
109
  validateAdmissionBinding(turnAdmission, expectedThreadHash, expectedSessionHash, expectedTurnHash);
84
110
  validateAdmissionBinding(threadAdmission, expectedThreadHash, expectedSessionHash, expectedTurnHash);
85
111
  if (admissionFingerprint(turnAdmission) !== admissionFingerprint(threadAdmission)) {
@@ -102,6 +128,14 @@ export async function readAdmissionPair(root, expectedThreadHash, expectedSessio
102
128
  }
103
129
  return turnAdmission;
104
130
  }
131
+ export async function readAdmissionForThread(root, expectedThreadHash) {
132
+ const admission = await readAdmission(threadGuardPath(root.root, expectedThreadHash), root.boundary);
133
+ if (!admission)
134
+ return null;
135
+ if (admission.thread_id_hash !== expectedThreadHash)
136
+ throw invalidGuard(true);
137
+ return admission;
138
+ }
105
139
  async function readAdmission(file, boundary) {
106
140
  const result = await readBoundedConfinedJson(boundary, file, MAX_LIFECYCLE_GUARD_BYTES);
107
141
  if (result.status === 'missing')
@@ -129,7 +163,11 @@ export async function blockedRunAdmissions(guardRoot, missionId, workflowRunId)
129
163
  if (names === null)
130
164
  return ['subagent_skill_availability_guard_invalid'];
131
165
  const blockers = [];
132
- for (const name of names.filter((item) => /^thread-[a-f0-9]{64}\.json$/.test(item)).sort()) {
166
+ const threadNames = names.filter((item) => /^thread-[a-f0-9]{64}\.json$/.test(item)).sort();
167
+ if (threadNames.length > MAX_LIFECYCLE_THREADS) {
168
+ return ['subagent_skill_availability_guard_invalid'];
169
+ }
170
+ for (const name of threadNames) {
133
171
  let admission;
134
172
  try {
135
173
  admission = await readAdmission(path.join(guardRoot.root, name), guardRoot.boundary);