@aiwg/cli 2026.10.15 → 2026.10.18

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 (286) hide show
  1. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  2. package/dist/src/artifacts/citation-parser.js +7 -6
  3. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  4. package/dist/src/artifacts/corpus-tools/cli.js +8 -3
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
  7. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  8. package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
  9. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  10. package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
  11. package/dist/src/artifacts/corpus-tools/expand.js +16 -17
  12. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  13. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  14. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  15. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  16. package/dist/src/artifacts/corpus-tools/resolve-cli.js +11 -3
  17. package/dist/src/artifacts/corpus-tools/resolve.js +42 -11
  18. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  19. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  20. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  21. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  22. package/dist/src/artifacts/graph-query.js +5 -3
  23. package/dist/src/artifacts/hybrid-query.js +11 -2
  24. package/dist/src/artifacts/index-refresh.js +2 -0
  25. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  26. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  27. package/dist/src/artifacts/query-engine-discover.js +285 -0
  28. package/dist/src/artifacts/query-engine-entries.js +188 -0
  29. package/dist/src/artifacts/query-engine-index.js +249 -0
  30. package/dist/src/artifacts/query-engine-matching.js +143 -0
  31. package/dist/src/artifacts/query-engine-options.js +2 -0
  32. package/dist/src/artifacts/query-engine-rules.js +202 -0
  33. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  34. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  35. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  36. package/dist/src/artifacts/query-engine-show.js +300 -0
  37. package/dist/src/artifacts/query-engine.js +7 -2576
  38. package/dist/src/cli/handlers/daemon.js +17 -1
  39. package/dist/src/cli/handlers/doctor-args.js +10 -5
  40. package/dist/src/cli/handlers/doctor-help.js +4 -1
  41. package/dist/src/cli/handlers/index.js +2 -2
  42. package/dist/src/cli/handlers/mc-agents.js +111 -0
  43. package/dist/src/cli/handlers/mc-args.js +54 -0
  44. package/dist/src/cli/handlers/mc-control.js +227 -0
  45. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  46. package/dist/src/cli/handlers/mc-help.js +171 -0
  47. package/dist/src/cli/handlers/mc-run.js +343 -0
  48. package/dist/src/cli/handlers/mc-session.js +138 -0
  49. package/dist/src/cli/handlers/mc-status.js +258 -0
  50. package/dist/src/cli/handlers/mc-summary.js +43 -0
  51. package/dist/src/cli/handlers/mc-types.js +3 -0
  52. package/dist/src/cli/handlers/mc-worker.js +205 -0
  53. package/dist/src/cli/handlers/mc.js +12 -1665
  54. package/dist/src/cli/handlers/models-refusal.js +13 -0
  55. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  56. package/dist/src/cli/handlers/models.js +5 -3
  57. package/dist/src/cli/handlers/regenerate.js +8 -16
  58. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  59. package/dist/src/cli/handlers/remove-options.js +31 -0
  60. package/dist/src/cli/handlers/remove-user.js +174 -0
  61. package/dist/src/cli/handlers/remove.js +201 -0
  62. package/dist/src/cli/handlers/sessions.js +7 -7
  63. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  64. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  65. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  66. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  67. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  68. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  69. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  70. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  71. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  72. package/dist/src/cli/handlers/subcommands.js +18 -1976
  73. package/dist/src/cli/handlers/update.js +157 -0
  74. package/dist/src/cli/handlers/use.js +14 -4
  75. package/dist/src/cli/handlers/utilities.js +3 -560
  76. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  77. package/dist/src/cli/scope-resolver.js +1 -142
  78. package/dist/src/cli/services/deployment-verification.js +0 -1
  79. package/dist/src/cli/user-scope-mirror.js +173 -0
  80. package/dist/src/config/aiwg-config.js +2 -1
  81. package/dist/src/config/authorization-cli.js +7 -3
  82. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  83. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  84. package/dist/src/config/dispatch-thresholds-runtime.mjs +21 -7
  85. package/dist/src/config/framework-aliases.js +12 -0
  86. package/dist/src/config/host-resource-report.d.mts +24 -0
  87. package/dist/src/config/host-resource-report.mjs +110 -0
  88. package/dist/src/config/host-resource-runtime.d.mts +37 -0
  89. package/dist/src/config/host-resource-runtime.mjs +296 -0
  90. package/dist/src/config/installed-selection.js +22 -0
  91. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  92. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  93. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  94. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  95. package/dist/src/decision/ensemble-study/gates.js +78 -0
  96. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  97. package/dist/src/decision/ensemble-study/score.js +3 -2
  98. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  99. package/dist/src/decision/heldout/access.js +74 -0
  100. package/dist/src/decision/heldout/calibration.js +1 -0
  101. package/dist/src/decision/heldout/collector.js +8 -1
  102. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  103. package/dist/src/decision/sensitivity/comparative.js +18 -41
  104. package/dist/src/effects/verifiers/file.js +22 -5
  105. package/dist/src/extensions/claude-attribution.js +82 -0
  106. package/dist/src/extensions/claude-hooks-installer.js +133 -69
  107. package/dist/src/extensions/commands/daemon.js +109 -0
  108. package/dist/src/extensions/commands/definitions.js +5 -89
  109. package/dist/src/gates/evaluate.js +2 -358
  110. package/dist/src/gates/heldout.js +17 -7
  111. package/dist/src/gates/observations.js +363 -0
  112. package/dist/src/gates/pack-composition.js +270 -0
  113. package/dist/src/gates/pack-tightening.js +197 -0
  114. package/dist/src/gates/pack-validation.js +262 -0
  115. package/dist/src/gates/registry-error.js +5 -0
  116. package/dist/src/gates/registry.js +13 -685
  117. package/dist/src/lint/check-patterns.js +163 -0
  118. package/dist/src/lint/checks.js +268 -0
  119. package/dist/src/lint/reference-resolution.js +54 -0
  120. package/dist/src/lint/runner.js +3 -465
  121. package/dist/src/mcp/helpers.mjs +11 -1
  122. package/dist/src/mcp/json-document.mjs +29 -0
  123. package/dist/src/mcp/muse-native-config.mjs +1 -28
  124. package/dist/src/memory/project-registry.js +44 -4
  125. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  126. package/dist/src/models/worker-plan.js +36 -5
  127. package/dist/src/models/wrapper-deployment.js +25 -12
  128. package/dist/src/models/wrapper-enforcement.js +47 -7
  129. package/dist/src/network-analysis/research.js +2 -1
  130. package/dist/src/plugin/command-ownership.js +34 -0
  131. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  132. package/dist/src/plugin/skill-command-translator.js +6 -232
  133. package/dist/src/policy/hitl-check.js +14 -4
  134. package/dist/src/policy/hitl-consume.js +54 -0
  135. package/dist/src/policy/hitl-receipt.js +2 -0
  136. package/dist/src/policy/hitl.js +11 -3
  137. package/dist/src/providers/context-output-ownership.js +26 -0
  138. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  139. package/dist/src/providers/deployment-ownership.mjs +226 -0
  140. package/dist/src/providers/deployment-removal.js +200 -0
  141. package/dist/src/providers/provider-context-contracts.js +162 -0
  142. package/dist/src/providers/provider-definition-schema.js +136 -0
  143. package/dist/src/providers/provider-definitions.js +8 -1298
  144. package/dist/src/providers/provider-seeds-1.js +360 -0
  145. package/dist/src/providers/provider-seeds-2.js +387 -0
  146. package/dist/src/providers/provider-seeds-3.js +262 -0
  147. package/dist/src/providers/removal-transaction.js +86 -0
  148. package/dist/src/providers/settings-document.d.mts +3 -0
  149. package/dist/src/providers/settings-document.mjs +47 -0
  150. package/dist/src/providers/settings-removal.js +190 -0
  151. package/dist/src/providers/skill-ownership.d.mts +19 -2
  152. package/dist/src/providers/skill-ownership.mjs +12 -4
  153. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  154. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  155. package/dist/src/providers/transformation-receipt-source.js +194 -0
  156. package/dist/src/research/clients/arxiv.js +4 -30
  157. package/dist/src/research/clients/base.js +48 -22
  158. package/dist/src/research/identity.js +42 -4
  159. package/dist/src/research/query-cli.js +3 -87
  160. package/dist/src/research/query-options.js +87 -0
  161. package/dist/src/research/reference-match.js +105 -24
  162. package/dist/src/research/services/acquisition.js +9 -7
  163. package/dist/src/research/services/citation.js +5 -2
  164. package/dist/src/research/types.js +2 -0
  165. package/dist/src/rules/activation.mjs +15 -6
  166. package/dist/src/rules/core-startup.mjs +2 -2
  167. package/dist/src/serve/mission-conductor.js +52 -4
  168. package/dist/src/serve/mission-summary.js +56 -0
  169. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  170. package/dist/src/sessions/adapters/grok-build.js +14 -7
  171. package/dist/src/sessions/workspace-discovery.js +5 -5
  172. package/dist/src/smiths/context-pipeline/aiwg-md.js +39 -46
  173. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  174. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  175. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  176. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  177. package/dist/src/smiths/context-pipeline/generator.js +10 -11
  178. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  179. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  180. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  181. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  182. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  183. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  184. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  185. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  186. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  187. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  188. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  189. package/dist/src/smiths/hook-bridge/index.js +9 -0
  190. package/package.json +13 -1
  191. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  192. package/schemas/decision/D29Study.v10.schema.json +65 -0
  193. package/tools/agents/deploy-agents.mjs +24 -675
  194. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  195. package/tools/agents/deploy-options.mjs +258 -0
  196. package/tools/agents/deploy-support.mjs +165 -0
  197. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  198. package/tools/agents/providers/base-behaviors.mjs +168 -0
  199. package/tools/agents/providers/base-context.mjs +205 -0
  200. package/tools/agents/providers/base-contract.mjs +116 -0
  201. package/tools/agents/providers/base-files.mjs +252 -0
  202. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  203. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  204. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  205. package/tools/agents/providers/base-inventory.mjs +269 -0
  206. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  207. package/tools/agents/providers/base-migrations.mjs +258 -0
  208. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  209. package/tools/agents/providers/base-rule-index.mjs +450 -0
  210. package/tools/agents/providers/base-runtime.mjs +60 -0
  211. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  212. package/tools/agents/providers/base.mjs +16 -3364
  213. package/tools/agents/providers/claude-post-deploy.mjs +20 -1
  214. package/tools/agents/providers/context-write.mjs +4 -0
  215. package/tools/agents/providers/hermes-startup.mjs +0 -5
  216. package/tools/agents/providers/muse.mjs +7 -2
  217. package/tools/agents/providers/pi.mjs +3 -1
  218. package/tools/agents/providers/rule-delivery-surface.mjs +359 -0
  219. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  220. package/tools/agents/providers/rule-deployment-commit.mjs +148 -0
  221. package/tools/agents/providers/rule-deployment-prepare.mjs +461 -0
  222. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  223. package/tools/agents/providers/rule-projection.mjs +3 -0
  224. package/tools/daemon/README.md +511 -0
  225. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  226. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  227. package/tools/daemon/agent-supervisor.mjs +299 -0
  228. package/tools/daemon/automation-engine.mjs +310 -0
  229. package/tools/daemon/autonomous-engine.mjs +346 -0
  230. package/tools/daemon/behavior-loader.mjs +316 -0
  231. package/tools/daemon/behavior.mjs +174 -0
  232. package/tools/daemon/concierge/intent-router.mjs +401 -0
  233. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  234. package/tools/daemon/concierge/response-translator.mjs +462 -0
  235. package/tools/daemon/config.mjs +377 -0
  236. package/tools/daemon/cron-scheduler.mjs +178 -0
  237. package/tools/daemon/daemon-main.mjs +1169 -0
  238. package/tools/daemon/event-router.mjs +84 -0
  239. package/tools/daemon/file-watcher.mjs +383 -0
  240. package/tools/daemon/index.mjs +1181 -0
  241. package/tools/daemon/init-profile.mjs +124 -0
  242. package/tools/daemon/ipc-client.mjs +197 -0
  243. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  244. package/tools/daemon/ipc-server.mjs +275 -0
  245. package/tools/daemon/maintenance-owner.mjs +79 -0
  246. package/tools/daemon/memory-manager.mjs +386 -0
  247. package/tools/daemon/message-router.mjs +194 -0
  248. package/tools/daemon/provider-watcher.mjs +585 -0
  249. package/tools/daemon/pty-adapter.mjs +420 -0
  250. package/tools/daemon/repl-chat.mjs +359 -0
  251. package/tools/daemon/resource-bounds.mjs +88 -0
  252. package/tools/daemon/sandbox-transport.mjs +295 -0
  253. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  254. package/tools/daemon/task-store.mjs +450 -0
  255. package/tools/daemon/tmux-manager.mjs +324 -0
  256. package/tools/daemon/update-policy.mjs +517 -0
  257. package/tools/daemon/web-server.mjs +399 -0
  258. package/tools/daemon/web-ui/index.html +585 -0
  259. package/tools/daemon/web-ui/styles.css +156 -0
  260. package/tools/docker/Dockerfile.daemon +35 -0
  261. package/tools/docker/container-manager.mjs +291 -0
  262. package/tools/messaging/adapter-registry.mjs +230 -0
  263. package/tools/messaging/adapters/base.mjs +326 -0
  264. package/tools/messaging/adapters/discord.mjs +462 -0
  265. package/tools/messaging/adapters/slack.mjs +402 -0
  266. package/tools/messaging/adapters/telegram.mjs +552 -0
  267. package/tools/messaging/chat-handler.mjs +297 -0
  268. package/tools/messaging/command-router.mjs +269 -0
  269. package/tools/messaging/event-bus.mjs +199 -0
  270. package/tools/messaging/index.mjs +456 -0
  271. package/tools/messaging/message-formatter.mjs +320 -0
  272. package/tools/messaging/room-manager.mjs +277 -0
  273. package/tools/messaging/types.mjs +94 -0
  274. package/tools/providers/pi-bridge-policy.mjs +4 -0
  275. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  276. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  277. package/tools/ralph-external/lib/worker-invocation-processes.mjs +7 -4
  278. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  279. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  280. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  281. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  282. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  283. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  284. package/tools/ralph-external/session-launcher.mjs +7 -7
  285. package/tools/scripts/resource-preflight.mjs +3 -242
  286. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -1,13 +1,20 @@
1
1
  // Traverse the due corpus frontier, suppress known papers, and checkpoint ranked recommendations.
2
- import { statSync } from 'node:fs';
3
2
  import { AiwgError } from '../../cli/errors.js';
4
3
  import { SemanticScholarClient } from '../../research/clients/semantic-scholar.js';
5
4
  import { identityKeys } from '../../research/identity.js';
6
5
  import { ResearchError, ResearchErrorCode } from '../../research/types.js';
7
6
  import { findInCorpus, loadCorpusIdentities } from './resolve-corpus.js';
8
7
  import { ExpansionQueue, rankCandidates } from './expand-queue.js';
9
- import { appendState, expansionPaths, readJsonl, writeQueue } from './expand-state.js';
8
+ import { appendState, compactState, expansionPaths, readJsonl, writeQueue } from './expand-state.js';
9
+ import { expansionDates } from './expand-dates.js';
10
10
  function seedId(record) {
11
+ const preferred = record.fields.map(fields => {
12
+ const keys = identityKeys(fields);
13
+ return keys.find(key => key.startsWith('arxivId:')) ?? keys.find(key => key.startsWith('doi:'));
14
+ });
15
+ if (preferred[0] && preferred[1] && preferred[0] !== preferred[1]) {
16
+ process.stderr.write(`Warning: ${record.ref} primary and sidecar seed IDs differ (${preferred[0]} vs ${preferred[1]}); using primary.\n`);
17
+ }
11
18
  // Prefer the primary document and citation frontmatter IDs over body URL fallbacks.
12
19
  for (const fields of record.fields) {
13
20
  const keys = identityKeys(fields);
@@ -21,17 +28,6 @@ function seedId(record) {
21
28
  const arxiv = [...record.keys].find(key => key.startsWith('arxivId:'));
22
29
  return arxiv ? `arXiv:${arxiv.slice(8)}` : null;
23
30
  }
24
- function seedDate(record) {
25
- for (const fields of record.fields) {
26
- const discovery = fields.discovery;
27
- for (const value of [fields.inducted, fields.inducted_on, fields.added, fields.created, fields.date, discovery?.date]) {
28
- const date = value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : NaN;
29
- if (Number.isFinite(date))
30
- return date;
31
- }
32
- }
33
- return statSync(record.path).mtimeMs;
34
- }
35
31
  export async function expandCorpus(root, cwd, options) {
36
32
  const corpus = loadCorpusIdentities(root);
37
33
  if (options.seeds?.some(ref => !corpus.some(record => record.ref === ref))) {
@@ -50,8 +46,9 @@ export async function expandCorpus(root, cwd, options) {
50
46
  if (!excluded(row.paper, row.identity_keys))
51
47
  queue.add(row.paper, row.seed_refs, row);
52
48
  }
53
- const scoped = corpus.filter(record => (!options.seeds || options.seeds.includes(record.ref))
54
- && (options.since === undefined || seedDate(record) >= options.since));
49
+ const selected = corpus.filter(record => !options.seeds || options.seeds.includes(record.ref));
50
+ const dates = options.since === undefined ? undefined : expansionDates(root, selected);
51
+ const scoped = selected.filter(record => options.since === undefined || dates.get(record.path) >= options.since);
55
52
  const now = Date.now();
56
53
  const due = scoped.map(record => ({ record, id: seedId(record) })).filter(({ record, id }) => {
57
54
  const last = previous.get(record.ref);
@@ -106,8 +103,10 @@ export async function expandCorpus(root, cwd, options) {
106
103
  }
107
104
  rankCandidates(result.candidates);
108
105
  }
109
- if (options.write)
106
+ if (options.write) {
110
107
  writeQueue(paths, result.candidates, renderExpansion(result));
108
+ compactState(paths);
109
+ }
111
110
  return result;
112
111
  }
113
112
  export function renderExpansion(result) {
@@ -116,7 +115,7 @@ export function renderExpansion(result) {
116
115
  lines.push(`- ${row.ref}: ${row.status} (${row.seed_id ?? 'no ID'}), ${row.n_returned} returned${row.error ? ` — ${row.error}` : ''}`);
117
116
  lines.push('', 'Ranking: distinct seed convergence, then publication year, then optional in-corpus reference overlap.', '');
118
117
  for (const [index, row] of result.candidates.entries()) {
119
- lines.push(`## ${index + 1}. ${row.paper.title}`, '', `Year: ${row.paper.year}; IDs: ${row.identity_keys.filter(key => !key.startsWith('title:')).join(', ')}`, `Score components: convergence=${row.score_parts.convergence}, recency=${row.score_parts.recency}, overlap=${row.score_parts.overlap ?? 'not checked'}`, `Seed REFs: ${row.seed_refs.join(', ')}`, `Discovery: ${row.discovery.surface}; via: ${row.discovery.via}`, '');
118
+ lines.push(`## ${index + 1}. ${row.paper.title}`, '', `Review: ${row.review?.status ?? 'pending'}`, `Year: ${row.paper.year}; IDs: ${row.identity_keys.filter(key => !key.startsWith('title:')).join(', ')}`, `Score components: convergence=${row.score_parts.convergence}, recency=${row.score_parts.recency}, overlap=${row.score_parts.overlap ?? 'not checked'}`, `Seed REFs: ${row.seed_refs.join(', ')}`, `Discovery: ${row.discovery.surface}; via: ${row.discovery.via}`, '');
120
119
  }
121
120
  for (const error of result.overlap_errors)
122
121
  lines.push(`Overlap failed for ${error.paper_id}: ${error.error}`);
@@ -15,6 +15,8 @@
15
15
  * @tests @test/unit/artifacts/induction-audit.test.ts
16
16
  */
17
17
  import * as fs from 'fs';
18
+ import { refIdFromFilename } from '../../research/identity.js';
19
+ import { refFilesForId } from './ref-files.js';
18
20
  import * as path from 'path';
19
21
  import { createHash } from 'crypto';
20
22
  import { parseFrontmatter } from '../corpus-views/ref-parser.js';
@@ -43,24 +45,23 @@ function refFiles(root) {
43
45
  const dir = path.join(root, ...REFS_DIR);
44
46
  if (!fs.existsSync(dir))
45
47
  return [];
46
- return fs.readdirSync(dir).filter((f) => /^REF-\d{3,4}[a-z]?(-.*)?\.md$/.test(f)).sort();
48
+ return fs.readdirSync(dir, { withFileTypes: true }).filter(f => f.isFile() && refIdFromFilename(f.name)).map(f => f.name).sort();
47
49
  }
48
50
  function refIdOf(filename) {
49
- const m = filename.match(/^(REF-\d{3,4}[a-z]?)/);
50
- return m ? m[1] : null;
51
+ return refIdFromFilename(filename);
51
52
  }
52
53
  function findAnalysis(root, refId) {
53
54
  const dir = path.join(root, ...REFS_DIR);
54
55
  if (!fs.existsSync(dir))
55
56
  return null;
56
- const m = fs.readdirSync(dir).find((f) => f === `${refId}.md` || f.startsWith(`${refId}-`));
57
+ const m = refFilesForId(dir, refId)[0];
57
58
  return m ? path.join(dir, m) : null;
58
59
  }
59
60
  function hasPdf(root, refId) {
60
61
  const dir = path.join(root, ...PDFS_DIR);
61
62
  if (!fs.existsSync(dir))
62
63
  return false;
63
- return fs.readdirSync(dir).some((f) => f === `${refId}.pdf` || f.startsWith(`${refId}-`));
64
+ return refFilesForId(dir, refId, '.pdf').length > 0;
64
65
  }
65
66
  /** Audit one ref. Required sections come from its source type's registry entry. */
66
67
  function auditRef(root, refId, reg) {
@@ -182,7 +183,7 @@ function pdfHash(root, refId) {
182
183
  const dir = path.join(root, ...PDFS_DIR);
183
184
  if (!fs.existsSync(dir))
184
185
  return null;
185
- const m = fs.readdirSync(dir).find((f) => f === `${refId}.pdf` || f.startsWith(`${refId}-`));
186
+ const m = refFilesForId(dir, refId, '.pdf')[0];
186
187
  if (!m)
187
188
  return null;
188
189
  return createHash('sha256').update(fs.readFileSync(path.join(dir, m))).digest('hex');
@@ -16,6 +16,7 @@
16
16
  * @tests @test/unit/artifacts/integrity-scan.test.ts
17
17
  */
18
18
  import * as fs from 'fs';
19
+ import { refIdFromFilename } from '../../research/identity.js';
19
20
  import * as path from 'path';
20
21
  import { load as loadYaml } from 'js-yaml';
21
22
  const TEXT_SUFFIXES = new Set(['.md', '.txt', '.tex', '.bib', '.yaml', '.yml', '.html', '.htm']);
@@ -56,8 +57,7 @@ export function loadIntegrityPatterns(root) {
56
57
  }
57
58
  const SEVERITY_RANK = { none: 0, low: 1, medium: 2, high: 3, critical: 4 };
58
59
  function refFromPath(p) {
59
- const m = p.match(/REF-\d{3,}[a-z]?/);
60
- return m ? m[0] : 'NO-REF';
60
+ return refIdFromFilename(path.basename(p), path.extname(p)) ?? 'NO-REF';
61
61
  }
62
62
  function excerpt(line, limit = 220) {
63
63
  const compact = line.trim().split(/\s+/).join(' ');
@@ -140,7 +140,7 @@ export function scanCorpus(root, opts = {}) {
140
140
  : DEFAULT_TARGET_DIRS.map((parts) => path.join(root, ...parts));
141
141
  const findings = [];
142
142
  for (const file of iterFiles(targets)) {
143
- if (opts.ref && !file.includes(opts.ref))
143
+ if (opts.ref && refFromPath(file) !== opts.ref)
144
144
  continue;
145
145
  findings.push(...scanFile(root, file, patterns));
146
146
  }
@@ -16,6 +16,8 @@
16
16
  * @source historical: corpus/radar_init.py, corpus/radar_report.py
17
17
  */
18
18
  import * as fs from 'fs';
19
+ import { isRefId, refSortKey } from '../../research/identity.js';
20
+ import { refFilesForId } from './ref-files.js';
19
21
  import * as path from 'path';
20
22
  import { load as loadYaml } from 'js-yaml';
21
23
  import { parseFrontmatter, extractRadar } from '../corpus-views/ref-parser.js';
@@ -30,7 +32,7 @@ export function listRadarRefs(corpusRoot) {
30
32
  try {
31
33
  return fs
32
34
  .readdirSync(radarDir(corpusRoot))
33
- .filter((f) => /^REF-\d{3,4}[a-z]?-radar\.md$/.test(f))
35
+ .filter((f) => f.endsWith('-radar.md') && isRefId(f.slice(0, -9)))
34
36
  .map((f) => f.replace(/-radar\.md$/, ''))
35
37
  .sort();
36
38
  }
@@ -43,7 +45,7 @@ export function listCitationRefs(corpusRoot) {
43
45
  try {
44
46
  return fs
45
47
  .readdirSync(path.join(corpusRoot, ...CITES_DIR))
46
- .filter((f) => /^REF-\d{3,4}[a-z]?-citations\.md$/.test(f))
48
+ .filter((f) => f.endsWith('-citations.md') && isRefId(f.slice(0, -13)))
47
49
  .map((f) => f.replace(/-citations\.md$/, ''))
48
50
  .sort();
49
51
  }
@@ -90,10 +92,9 @@ export function loadClusterMap(corpusRoot) {
90
92
  }
91
93
  }
92
94
  return (refId) => {
93
- const m = refId.match(/^REF-(\d+)/);
94
- if (!m)
95
+ if (!isRefId(refId))
95
96
  return '';
96
- const n = parseInt(m[1], 10);
97
+ const [n] = refSortKey(refId);
97
98
  for (const [low, high, tag] of rules) {
98
99
  if (n >= low && n <= high)
99
100
  return tag;
@@ -131,10 +132,7 @@ export function readAnalysisGrade(corpusRoot, refId) {
131
132
  function analysisFiles(corpusRoot, refId) {
132
133
  const dir = path.join(corpusRoot, ...REFS_DIR);
133
134
  try {
134
- return fs
135
- .readdirSync(dir)
136
- .filter((f) => f.startsWith(`${refId}-`) && f.endsWith('.md') && !f.startsWith('TEMPLATE'))
137
- .sort()
135
+ return refFilesForId(dir, refId)
138
136
  .map((f) => path.join(dir, f));
139
137
  }
140
138
  catch {
@@ -0,0 +1,11 @@
1
+ // Locate regular corpus files by exact REF identity and extension.
2
+ import { readdirSync } from 'node:fs';
3
+ import { isRefId, refIdFromFilename } from '../../research/identity.js';
4
+ export function refFilesForId(directory, refId, extension = '.md') {
5
+ if (!isRefId(refId))
6
+ return [];
7
+ return readdirSync(directory, { withFileTypes: true })
8
+ .filter(file => file.isFile() && refIdFromFilename(file.name, extension) === refId)
9
+ .map(file => file.name).sort();
10
+ }
11
+ //# sourceMappingURL=ref-files.js.map
@@ -2,8 +2,9 @@
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { resolve } from 'node:path';
4
4
  import { AiwgError } from '../../cli/errors.js';
5
+ import { ResearchError, ResearchErrorCode } from '../../research/types.js';
5
6
  import { createResolverClients, resolveReference } from './resolve.js';
6
- export const RESOLVE_USAGE = 'aiwg corpus resolve "<title | URL | arXiv ID | DOI | bibliography line>" [--year YYYY] [--json]\naiwg corpus resolve --from-file refs.txt [--year YYYY] [--json]\nExit codes: 0 resolved, 2 ambiguous, 3 unresolved (batch: worst line), 1 usage error.\n';
7
+ export const RESOLVE_USAGE = 'aiwg corpus resolve "<title | URL | arXiv ID | DOI | bibliography line>" [--year YYYY] [--json]\naiwg corpus resolve --from-file refs.txt [--year YYYY] [--json]\nExit codes: 0 resolved, 2 ambiguous, 3 unresolved, 4 deferred (incomplete lookup; retry), 1 usage or storage error (batch: worst line).\n';
7
8
  function usage(message) {
8
9
  throw new AiwgError({ code: 'ERR_CORPUS_RESOLVE_USAGE', message, exitCode: 1, hint: RESOLVE_USAGE.trim() });
9
10
  }
@@ -78,13 +79,20 @@ export async function resolveCli(args, root, cwd) {
78
79
  results.push({ ...await resolveReference(reference.input, root, year, clients), ...reference });
79
80
  }
80
81
  catch (error) {
81
- results.push({ ...reference, reference: { input: reference.input }, status: 'unresolved', incomplete: true,
82
+ // Storage, validation and programming errors keep the corpus error/exit convention.
83
+ if (!(error instanceof ResearchError) || ![
84
+ ResearchErrorCode.RF_103, ResearchErrorCode.RF_104,
85
+ ResearchErrorCode.RF_200, ResearchErrorCode.RF_201, ResearchErrorCode.RF_202,
86
+ ResearchErrorCode.RF_500, ResearchErrorCode.RF_501, ResearchErrorCode.RF_502,
87
+ ].includes(error.code))
88
+ throw error;
89
+ results.push({ ...reference, reference: { input: reference.input }, status: 'deferred', incomplete: true,
82
90
  error: error instanceof Error ? error.message : String(error), candidates: [], findings: [], paths_tried: [],
83
91
  already_in_corpus: false, corpus_matches: [] });
84
92
  }
85
93
  }
86
94
  process.stdout.write(json ? JSON.stringify(fromFile ? results : results[0], null, 2) + '\n' : results.map(render).join('\n'));
87
- const exitCode = results.reduce((worst, result) => Math.max(worst, { resolved: 0, ambiguous: 2, unresolved: 3 }[result.status]), 0);
95
+ const exitCode = results.reduce((worst, result) => Math.max(worst, { resolved: 0, ambiguous: 2, unresolved: 3, deferred: 4 }[result.status]), 0);
88
96
  if (exitCode)
89
97
  throw new AiwgError({ code: 'ERR_CORPUS_RESOLVE_RESULT', message: 'Reference resolution requires review; see results', exitCode });
90
98
  }
@@ -2,8 +2,8 @@
2
2
  import { ArxivClient } from '../../research/clients/arxiv.js';
3
3
  import { CrossRefClient } from '../../research/clients/crossref.js';
4
4
  import { SemanticScholarClient } from '../../research/clients/semantic-scholar.js';
5
- import { normalizeIdentity, normalizeTitle } from '../../research/identity.js';
6
- import { classifyCandidates, mergePapers, parsePartialReference, scorePaper } from '../../research/reference-match.js';
5
+ import { identityKeys, normalizeIdentity, normalizeTitle } from '../../research/identity.js';
6
+ import { classifyCandidates, mergePapers, needsTitleDisambiguation, parsePartialReference, scorePaper } from '../../research/reference-match.js';
7
7
  import { ResearchError, ResearchErrorCode } from '../../research/types.js';
8
8
  import { findInCorpus } from './resolve-corpus.js';
9
9
  export function createResolverClients() {
@@ -11,7 +11,13 @@ export function createResolverClients() {
11
11
  }
12
12
  function canonicalPaper(paper) {
13
13
  const identity = normalizeIdentity(paper);
14
- return { ...paper, ...Object.fromEntries(Object.entries(identity).filter(([key, value]) => key !== 'title' && value !== undefined)) };
14
+ const validYear = (value) => Number.isInteger(value) && value >= 1000 && value <= 2199;
15
+ const year = validYear(paper.year) ? paper.year : Number(paper.publicationDate?.slice(0, 4));
16
+ if (!validYear(year))
17
+ throw new ResearchError(ResearchErrorCode.RF_301, 'Response lacks a valid publication year');
18
+ // Keep source spelling in results; normalizeIdentity supplies case-insensitive keys.
19
+ return { ...paper, year, ...Object.fromEntries(Object.entries(identity)
20
+ .filter(([key, value]) => !['title', 'openReviewId', 'aclId'].includes(key) && value !== undefined)) };
15
21
  }
16
22
  function s2Identifier(identifier) {
17
23
  switch (identifier.kind) {
@@ -31,7 +37,17 @@ export async function resolveReference(input, root, year, clients = createResolv
31
37
  const identifier = reference.identifier;
32
38
  async function attempt(source, method, query, run, byId = false) {
33
39
  try {
34
- const returned = (await run()).slice(0, 5).map(canonicalPaper);
40
+ const returned = (await run()).slice(0, 5).flatMap(paper => {
41
+ try {
42
+ return [canonicalPaper(paper)];
43
+ }
44
+ catch (error) {
45
+ // Missing years are record quality, not a failed request; retain valid siblings.
46
+ if (error instanceof ResearchError && error.code === ResearchErrorCode.RF_301)
47
+ return [];
48
+ throw error;
49
+ }
50
+ });
35
51
  if (returned.some(paper => !paper.id || !normalizeTitle(paper.title))) {
36
52
  throw new ResearchError(ResearchErrorCode.RF_301, 'Response lacks a paper identity or title');
37
53
  }
@@ -51,15 +67,21 @@ export async function resolveReference(input, root, year, clients = createResolv
51
67
  // A direct lookup establishes the requested ID when the API omits that externalId.
52
68
  if (identifier.kind !== 's2')
53
69
  Object.assign(paper, { [key]: identifier.id });
54
- verified.add(paper.id);
70
+ for (const key of identityKeys(paper).filter(key => !key.startsWith('title:')))
71
+ verified.add(key);
55
72
  }
56
73
  papers.push(paper);
57
74
  }
58
75
  }
59
76
  catch (error) {
60
77
  const missing = error instanceof ResearchError && error.code === ResearchErrorCode.RF_300;
78
+ const retryable = error instanceof ResearchError && [
79
+ ResearchErrorCode.RF_103, ResearchErrorCode.RF_104, ResearchErrorCode.RF_200,
80
+ ResearchErrorCode.RF_201, ResearchErrorCode.RF_202, ResearchErrorCode.RF_500,
81
+ ResearchErrorCode.RF_501, ResearchErrorCode.RF_502,
82
+ ].includes(error.code);
61
83
  paths.push({ source, method, query, status: missing ? 'empty' : 'error', returned: [],
62
- ...(missing ? {} : { error: error instanceof Error ? error.message : String(error) }) });
84
+ ...(missing ? {} : { error: error instanceof Error ? error.message : String(error), retryable }) });
63
85
  }
64
86
  }
65
87
  if (identifier) {
@@ -77,7 +99,8 @@ export async function resolveReference(input, root, year, clients = createResolv
77
99
  const idPaths = paths.filter(path => path.method === 'id');
78
100
  findings.push({ type: 'identifier_unresolved', supplied: identifier.id, paths: idPaths,
79
101
  returned: idPaths.map(path => {
80
- const detail = path.error ?? path.returned.map(paper => JSON.stringify(normalizeIdentity(paper))).join(', ');
102
+ const detail = path.error ?? path.returned.map(paper => JSON.stringify({ ...normalizeIdentity(paper),
103
+ openReviewId: paper.openReviewId, aclId: paper.aclId })).join(', ');
81
104
  const outcome = path.returned.length ? 'returned (identifier mismatch)' : path.status;
82
105
  return `${path.source}/${path.method} (${path.query}): ${outcome}${detail ? `: ${detail}` : ''}`;
83
106
  }).join('; ') });
@@ -88,18 +111,26 @@ export async function resolveReference(input, root, year, clients = createResolv
88
111
  await attempt('arxiv', 'title', query, async () => (await clients.arxiv.search(query, { limit: 5 })).papers);
89
112
  await attempt('crossref', 'bibliographic', input, async () => (await clients.crossref.searchBibliographic(input, { limit: 5 })).papers);
90
113
  }
91
- const candidates = mergePapers(papers).map(paper => scorePaper(reference, paper, verified.has(paper.id)))
114
+ const candidates = mergePapers(papers).map(paper => scorePaper(reference, paper, identityKeys(paper).some(key => verified.has(key))))
92
115
  .sort((a, b) => b.score - a.score || a.paper.id.localeCompare(b.paper.id)).slice(0, 5);
93
- for (const candidate of candidates) {
116
+ for (const candidate of candidates.slice(0, 1)) {
94
117
  if (reference.title && normalizeTitle(reference.title) !== normalizeTitle(candidate.paper.title)) {
95
118
  findings.push({ type: 'title_mismatch', supplied: reference.title, returned: candidate.paper.title, candidate: candidate.paper.id });
96
119
  }
97
120
  }
98
121
  const classified = classifyCandidates(candidates);
99
- const status = identifierUnresolved && classified === 'resolved' ? 'ambiguous' : classified;
122
+ const incomplete = paths.some(path => path.retryable);
123
+ const titleAmbiguous = needsTitleDisambiguation(reference, candidates, incomplete);
124
+ const status = classified === 'unresolved' && incomplete ? 'deferred'
125
+ : classified === 'resolved' && (identifierUnresolved || titleAmbiguous) ? 'ambiguous' : classified;
126
+ if (titleAmbiguous && classified !== 'unresolved')
127
+ findings.push({ type: 'title_ambiguous',
128
+ supplied: reference.title, returned: reference.year === undefined
129
+ ? 'Supply a year, author, or verified identifier to disambiguate this title'
130
+ : 'Supply an author or verified identifier to disambiguate this title' });
100
131
  const paper = status === 'resolved' ? candidates[0].paper : undefined;
101
132
  const corpusMatches = paper ? findInCorpus(root, paper) : [];
102
- return { input, reference, status, incomplete: paths.some(path => path.status === 'error'), candidates,
133
+ return { input, reference, status, incomplete, candidates,
103
134
  ...(paper ? { paper } : {}), findings, paths_tried: paths, already_in_corpus: corpusMatches.length > 0, corpus_matches: corpusMatches };
104
135
  }
105
136
  //# sourceMappingURL=resolve.js.map
@@ -1,6 +1,7 @@
1
1
  /** Experimental hybrid corpus-retrieval benchmark. Never replaces research-query. @issue #2038 */
2
2
  import { createHash } from 'node:crypto';
3
3
  import fs from 'node:fs';
4
+ import { refIdsInText } from '../../research/identity.js';
4
5
  import path from 'node:path';
5
6
  import { performance } from 'node:perf_hooks';
6
7
  import { bm25Rank, tokenizeText } from '../fulltext.js';
@@ -103,7 +104,7 @@ export function parseConceptScheme(content) {
103
104
  }
104
105
  function documentId(entry) {
105
106
  const text = [entry.name, entry.title, entry.path].filter(Boolean).join(' ');
106
- return text.match(/\bREF-\d+\b/i)?.[0]?.toUpperCase() ?? path.basename(entry.path).replace(/\.[^.]+$/, '');
107
+ return refIdsInText(text)[0] ?? path.basename(entry.path).replace(/\.[^.]+$/, '');
107
108
  }
108
109
  function isResearch(entry) {
109
110
  const candidate = `${entry.type} ${entry.path}`.toLowerCase().replaceAll('\\', '/');
@@ -12,8 +12,10 @@
12
12
  * @tests @test/unit/artifacts/sidecar-lint.test.ts
13
13
  */
14
14
  import * as fs from 'fs';
15
+ import { REF_ID_PATTERN } from '../../research/identity.js';
16
+ import { refFilesForId } from './ref-files.js';
15
17
  import * as path from 'path';
16
- const REF_ID_RE = /\bREF-\d+[a-z]?\b/g;
18
+ const REF_ID_RE = new RegExp(REF_ID_PATTERN, 'g');
17
19
  const CITES_DIR = ['documentation', 'citations'];
18
20
  const REFS_DIR = ['documentation', 'references'];
19
21
  /** List `documentation/citations/REF-*-citations.md` files under the corpus root. */
@@ -147,9 +149,7 @@ export function refTitle(root, ref) {
147
149
  const refsDir = path.join(root, ...REFS_DIR);
148
150
  if (!fs.existsSync(refsDir))
149
151
  return '?';
150
- const match = fs
151
- .readdirSync(refsDir)
152
- .find((f) => f === `${ref}.md` || f.startsWith(`${ref}-`));
152
+ const match = refFilesForId(refsDir, ref)[0];
153
153
  if (!match)
154
154
  return '?';
155
155
  const text = fs.readFileSync(path.join(refsDir, match), 'utf-8');
@@ -12,6 +12,7 @@
12
12
  * @tests @test/unit/artifacts/sidecar-repair.test.ts
13
13
  */
14
14
  import * as fs from 'fs';
15
+ import { refFilesForId } from './ref-files.js';
15
16
  import * as path from 'path';
16
17
  import { load as loadYaml } from 'js-yaml';
17
18
  import { DEFAULT_AFFILIATION_MAP, buildAffiliationReverse } from '../corpus-views/corpus-config.js';
@@ -133,7 +134,7 @@ function findAnalysisDoc(root, ref) {
133
134
  const dir = path.join(root, ...REFS_DIR);
134
135
  if (!fs.existsSync(dir))
135
136
  return null;
136
- const match = fs.readdirSync(dir).find((f) => f.startsWith(`${ref}-`));
137
+ const match = refFilesForId(dir, ref)[0];
137
138
  return match ? path.join(dir, match) : null;
138
139
  }
139
140
  export function repairAuthors(root, opts = {}) {
@@ -15,20 +15,10 @@ import { createHash } from 'crypto';
15
15
  import { load as loadYaml } from 'js-yaml';
16
16
  import { TOPIC_PATTERNS, METHOD_PATTERNS, VENUE_PATTERNS, SIZE_PATTERNS, SIZE_TIERS, classifyFirst, classifyMany, } from './taxonomies.js';
17
17
  import { normalizeSourceType, loadSourceTypeRegistry } from '../corpus-tools/source-types.js';
18
- const REF_FILE_RE = /^REF-(\d{3,4}[a-z]?)-/;
19
- const REF_ID_RE = /REF-\d{3,4}[a-z]?/g;
18
+ import { refIdFromFilename as extractRefId, REF_ID_PATTERN } from '../../research/identity.js';
19
+ const REF_ID_RE = new RegExp(REF_ID_PATTERN, 'g');
20
20
  const YEAR_RE = /\b(?:19|20)(\d{2})\b/;
21
- /** Sort key for REF ids: [numeric, alpha-suffix]. Mirrors build.py ref_sort_key. */
22
- export function refSortKey(refId) {
23
- const m = refId.match(/REF-(\d+)([a-z]?)/);
24
- return m ? [parseInt(m[1], 10), m[2]] : [999999, refId];
25
- }
26
- /** Compare two REF ids by (numeric, suffix). */
27
- export function compareRefId(a, b) {
28
- const [an, as_] = refSortKey(a);
29
- const [bn, bs] = refSortKey(b);
30
- return an !== bn ? an - bn : as_ < bs ? -1 : as_ > bs ? 1 : 0;
31
- }
21
+ export { refSortKey, compareRefId } from '../../research/identity.js';
32
22
  /** Title-case matching Python str.title(): cap first letter of each alpha run, lowercase the rest. */
33
23
  export function slugToTitle(value) {
34
24
  return value.replace(/-/g, ' ').replace(/_/g, ' ').replace(/[A-Za-z]+/g, (w) => w[0].toUpperCase() + w.slice(1).toLowerCase());
@@ -53,10 +43,6 @@ export function parseFrontmatter(text) {
53
43
  return {};
54
44
  }
55
45
  }
56
- function extractRefId(filename) {
57
- const m = filename.match(REF_FILE_RE);
58
- return m ? `REF-${m[1]}` : null;
59
- }
60
46
  function extractTitle(text, fm) {
61
47
  if (typeof fm.title === 'string')
62
48
  return fm.title.trim().replace(/^"|"$/g, '');
@@ -8,6 +8,8 @@
8
8
  * @source @src/artifacts/types.ts
9
9
  * @tests @test/unit/artifacts/graph-query.test.ts
10
10
  */
11
+ import path from 'node:path';
12
+ import { isRefId, refIdFromFilename } from '../research/identity.js';
11
13
  import { normalizeEdges } from './types.js';
12
14
  import { buildFortemiCoreDependencyGraph, loadFortemiCoreMetadataEntries } from './fortemi-core-query-adapter.js';
13
15
  import { closeGraphBackend, openGraphBackend } from './backend-runtime.js';
@@ -57,7 +59,7 @@ export function getNeighbors(graph, node, direction = 'both', edgeType, metadata
57
59
  *
58
60
  * Supports:
59
61
  * - Exact path match ("documentation/citations/REF-008-citations.md")
60
- * - REF-XXX shorthand — finds the first key containing the REF identifier
62
+ * - REF-XXX shorthand — finds a key with the exact REF filename token
61
63
  * - Partial path match — finds the first key ending with the given string
62
64
  */
63
65
  export function resolveNode(graph, node) {
@@ -65,8 +67,8 @@ export function resolveNode(graph, node) {
65
67
  if (graph[node])
66
68
  return node;
67
69
  // REF-XXX shorthand
68
- if (/^REF-\d+$/.test(node)) {
69
- const key = Object.keys(graph).find(k => k.includes(node));
70
+ if (isRefId(node)) {
71
+ const key = Object.keys(graph).find(k => refIdFromFilename(path.basename(k)) === node);
70
72
  return key ?? null;
71
73
  }
72
74
  // Partial path match
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import { promises as fs } from 'fs';
11
11
  import path from 'path';
12
+ import { isRefId, refIdFromFilename } from '../research/identity.js';
12
13
  import { resolveProjectAiwgDir } from '../config/project-artifacts.js';
13
14
  // ============================================================================
14
15
  // ArtifactIndex
@@ -109,7 +110,7 @@ export class ArtifactIndex {
109
110
  */
110
111
  findDependents(artifactPath) {
111
112
  const normalized = artifactPath.replace(/^\.aiwg\//, '');
112
- return this.artifacts.filter((a) => a.references.some((ref) => ref.includes(normalized)));
113
+ return this.artifacts.filter((a) => a.references.some((ref) => referenceMatches(normalized, ref)));
113
114
  }
114
115
  /**
115
116
  * Find artifacts referenced by a given artifact.
@@ -119,7 +120,7 @@ export class ArtifactIndex {
119
120
  if (!artifact)
120
121
  return [];
121
122
  return artifact.references
122
- .map((ref) => this.artifacts.find((a) => a.relativePath.includes(ref)))
123
+ .map((ref) => this.artifacts.find((a) => referenceMatches(ref, a.relativePath)))
123
124
  .filter(Boolean);
124
125
  }
125
126
  getAll() {
@@ -222,4 +223,12 @@ function keywordScore(artifact, query) {
222
223
  }
223
224
  return matches / terms.length;
224
225
  }
226
+ /** Compare a REF token or a complete path component without substring aliases. */
227
+ function referenceMatches(reference, candidate) {
228
+ const normalized = reference.replace(/^\.aiwg\//, '');
229
+ const target = candidate.replace(/^\.aiwg\//, '');
230
+ if (isRefId(normalized))
231
+ return refIdFromFilename(path.basename(target)) === normalized;
232
+ return target === normalized || target.endsWith(`/${normalized}`);
233
+ }
225
234
  //# sourceMappingURL=hybrid-query.js.map
@@ -172,6 +172,8 @@ export async function refreshResourceGate(workspace, live) {
172
172
  admissionHostResources: config?.parallelism?.admission?.hostResources,
173
173
  overlay: { max_load_ratio: 0.8 },
174
174
  });
175
+ // An index refresh is not a worker launch, so the worker cap never gates it.
176
+ delete thresholds.max_workers;
175
177
  const result = preflight.evaluateDispatchGate(live ?? preflight.readLiveHostResources({ paths: [workspace] }), thresholds);
176
178
  return { ok: result.ok, reason: result.failures.map((failure) => failure.reason).join('; ') || undefined };
177
179
  }