@aiwg/cli 2026.10.15 → 2026.10.16

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 (180) 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 +23 -9
  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/cli/handlers/daemon.js +17 -1
  26. package/dist/src/cli/handlers/doctor-args.js +10 -5
  27. package/dist/src/cli/handlers/doctor-help.js +4 -1
  28. package/dist/src/cli/handlers/index.js +2 -2
  29. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  30. package/dist/src/cli/handlers/models.js +3 -2
  31. package/dist/src/cli/handlers/regenerate.js +8 -16
  32. package/dist/src/cli/handlers/sessions.js +7 -7
  33. package/dist/src/cli/handlers/subcommands.js +8 -0
  34. package/dist/src/cli/handlers/update.js +157 -0
  35. package/dist/src/cli/handlers/use.js +14 -4
  36. package/dist/src/cli/handlers/utilities.js +3 -560
  37. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  38. package/dist/src/cli/services/deployment-verification.js +0 -1
  39. package/dist/src/config/aiwg-config.js +2 -1
  40. package/dist/src/config/authorization-cli.js +7 -3
  41. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  42. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  43. package/dist/src/config/framework-aliases.js +12 -0
  44. package/dist/src/config/host-resource-report.d.mts +19 -0
  45. package/dist/src/config/host-resource-report.mjs +80 -0
  46. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  47. package/dist/src/config/host-resource-runtime.mjs +293 -0
  48. package/dist/src/config/installed-selection.js +22 -0
  49. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  50. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  51. package/dist/src/decision/heldout/access.js +74 -0
  52. package/dist/src/decision/heldout/calibration.js +1 -0
  53. package/dist/src/decision/heldout/collector.js +8 -1
  54. package/dist/src/effects/verifiers/file.js +22 -5
  55. package/dist/src/extensions/claude-attribution.js +82 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  57. package/dist/src/extensions/commands/daemon.js +109 -0
  58. package/dist/src/extensions/commands/definitions.js +5 -89
  59. package/dist/src/gates/heldout.js +17 -7
  60. package/dist/src/lint/check-patterns.js +163 -0
  61. package/dist/src/lint/checks.js +268 -0
  62. package/dist/src/lint/reference-resolution.js +54 -0
  63. package/dist/src/lint/runner.js +3 -465
  64. package/dist/src/mcp/helpers.mjs +11 -1
  65. package/dist/src/memory/project-registry.js +44 -4
  66. package/dist/src/models/worker-plan.js +36 -5
  67. package/dist/src/models/wrapper-deployment.js +25 -12
  68. package/dist/src/models/wrapper-enforcement.js +47 -7
  69. package/dist/src/network-analysis/research.js +2 -1
  70. package/dist/src/policy/hitl-check.js +14 -4
  71. package/dist/src/policy/hitl-consume.js +54 -0
  72. package/dist/src/policy/hitl-receipt.js +2 -0
  73. package/dist/src/policy/hitl.js +11 -3
  74. package/dist/src/providers/provider-context-contracts.js +162 -0
  75. package/dist/src/providers/provider-definition-schema.js +136 -0
  76. package/dist/src/providers/provider-definitions.js +8 -1298
  77. package/dist/src/providers/provider-seeds-1.js +360 -0
  78. package/dist/src/providers/provider-seeds-2.js +387 -0
  79. package/dist/src/providers/provider-seeds-3.js +262 -0
  80. package/dist/src/research/clients/arxiv.js +4 -30
  81. package/dist/src/research/clients/base.js +48 -22
  82. package/dist/src/research/identity.js +34 -2
  83. package/dist/src/research/query-cli.js +3 -87
  84. package/dist/src/research/query-options.js +87 -0
  85. package/dist/src/research/reference-match.js +70 -24
  86. package/dist/src/research/services/acquisition.js +9 -7
  87. package/dist/src/research/services/citation.js +5 -2
  88. package/dist/src/research/types.js +2 -0
  89. package/dist/src/serve/mission-conductor.js +48 -4
  90. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  91. package/dist/src/sessions/adapters/grok-build.js +14 -7
  92. package/dist/src/sessions/workspace-discovery.js +5 -5
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +16 -46
  94. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  95. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  96. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  97. package/dist/src/smiths/context-pipeline/generator.js +9 -10
  98. package/dist/src/smiths/context-pipeline/managed-hook.js +1 -1
  99. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  100. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  101. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  102. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  103. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  104. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  105. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  106. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  107. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  108. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  109. package/package.json +10 -1
  110. package/schemas/decision/D29Study.v10.schema.json +65 -0
  111. package/tools/agents/deploy-agents.mjs +10 -0
  112. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  113. package/tools/agents/providers/context-write.mjs +4 -0
  114. package/tools/agents/providers/pi.mjs +3 -1
  115. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  116. package/tools/agents/providers/rule-delivery.mjs +20 -1144
  117. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  118. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  119. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  120. package/tools/daemon/README.md +511 -0
  121. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  122. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  123. package/tools/daemon/agent-supervisor.mjs +299 -0
  124. package/tools/daemon/automation-engine.mjs +310 -0
  125. package/tools/daemon/autonomous-engine.mjs +346 -0
  126. package/tools/daemon/behavior-loader.mjs +316 -0
  127. package/tools/daemon/behavior.mjs +174 -0
  128. package/tools/daemon/concierge/intent-router.mjs +401 -0
  129. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  130. package/tools/daemon/concierge/response-translator.mjs +462 -0
  131. package/tools/daemon/config.mjs +377 -0
  132. package/tools/daemon/cron-scheduler.mjs +178 -0
  133. package/tools/daemon/daemon-main.mjs +1169 -0
  134. package/tools/daemon/event-router.mjs +84 -0
  135. package/tools/daemon/file-watcher.mjs +383 -0
  136. package/tools/daemon/index.mjs +1181 -0
  137. package/tools/daemon/init-profile.mjs +124 -0
  138. package/tools/daemon/ipc-client.mjs +197 -0
  139. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  140. package/tools/daemon/ipc-server.mjs +275 -0
  141. package/tools/daemon/maintenance-owner.mjs +79 -0
  142. package/tools/daemon/memory-manager.mjs +386 -0
  143. package/tools/daemon/message-router.mjs +194 -0
  144. package/tools/daemon/provider-watcher.mjs +585 -0
  145. package/tools/daemon/pty-adapter.mjs +420 -0
  146. package/tools/daemon/repl-chat.mjs +359 -0
  147. package/tools/daemon/resource-bounds.mjs +88 -0
  148. package/tools/daemon/sandbox-transport.mjs +295 -0
  149. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  150. package/tools/daemon/task-store.mjs +450 -0
  151. package/tools/daemon/tmux-manager.mjs +324 -0
  152. package/tools/daemon/update-policy.mjs +517 -0
  153. package/tools/daemon/web-server.mjs +399 -0
  154. package/tools/daemon/web-ui/index.html +585 -0
  155. package/tools/daemon/web-ui/styles.css +156 -0
  156. package/tools/docker/Dockerfile.daemon +35 -0
  157. package/tools/docker/container-manager.mjs +291 -0
  158. package/tools/messaging/adapter-registry.mjs +230 -0
  159. package/tools/messaging/adapters/base.mjs +326 -0
  160. package/tools/messaging/adapters/discord.mjs +462 -0
  161. package/tools/messaging/adapters/slack.mjs +402 -0
  162. package/tools/messaging/adapters/telegram.mjs +552 -0
  163. package/tools/messaging/chat-handler.mjs +297 -0
  164. package/tools/messaging/command-router.mjs +269 -0
  165. package/tools/messaging/event-bus.mjs +199 -0
  166. package/tools/messaging/index.mjs +456 -0
  167. package/tools/messaging/message-formatter.mjs +320 -0
  168. package/tools/messaging/room-manager.mjs +277 -0
  169. package/tools/messaging/types.mjs +94 -0
  170. package/tools/providers/pi-bridge-policy.mjs +4 -0
  171. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  172. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  173. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  174. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  175. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  176. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  177. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  178. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  179. package/tools/ralph-external/session-launcher.mjs +7 -7
  180. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -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) {
@@ -51,7 +57,8 @@ export async function resolveReference(input, root, year, clients = createResolv
51
57
  // A direct lookup establishes the requested ID when the API omits that externalId.
52
58
  if (identifier.kind !== 's2')
53
59
  Object.assign(paper, { [key]: identifier.id });
54
- verified.add(paper.id);
60
+ for (const key of identityKeys(paper).filter(key => !key.startsWith('title:')))
61
+ verified.add(key);
55
62
  }
56
63
  papers.push(paper);
57
64
  }
@@ -77,7 +84,8 @@ export async function resolveReference(input, root, year, clients = createResolv
77
84
  const idPaths = paths.filter(path => path.method === 'id');
78
85
  findings.push({ type: 'identifier_unresolved', supplied: identifier.id, paths: idPaths,
79
86
  returned: idPaths.map(path => {
80
- const detail = path.error ?? path.returned.map(paper => JSON.stringify(normalizeIdentity(paper))).join(', ');
87
+ const detail = path.error ?? path.returned.map(paper => JSON.stringify({ ...normalizeIdentity(paper),
88
+ openReviewId: paper.openReviewId, aclId: paper.aclId })).join(', ');
81
89
  const outcome = path.returned.length ? 'returned (identifier mismatch)' : path.status;
82
90
  return `${path.source}/${path.method} (${path.query}): ${outcome}${detail ? `: ${detail}` : ''}`;
83
91
  }).join('; ') });
@@ -88,18 +96,24 @@ export async function resolveReference(input, root, year, clients = createResolv
88
96
  await attempt('arxiv', 'title', query, async () => (await clients.arxiv.search(query, { limit: 5 })).papers);
89
97
  await attempt('crossref', 'bibliographic', input, async () => (await clients.crossref.searchBibliographic(input, { limit: 5 })).papers);
90
98
  }
91
- const candidates = mergePapers(papers).map(paper => scorePaper(reference, paper, verified.has(paper.id)))
99
+ const candidates = mergePapers(papers).map(paper => scorePaper(reference, paper, identityKeys(paper).some(key => verified.has(key))))
92
100
  .sort((a, b) => b.score - a.score || a.paper.id.localeCompare(b.paper.id)).slice(0, 5);
93
- for (const candidate of candidates) {
101
+ for (const candidate of candidates.slice(0, 1)) {
94
102
  if (reference.title && normalizeTitle(reference.title) !== normalizeTitle(candidate.paper.title)) {
95
103
  findings.push({ type: 'title_mismatch', supplied: reference.title, returned: candidate.paper.title, candidate: candidate.paper.id });
96
104
  }
97
105
  }
98
106
  const classified = classifyCandidates(candidates);
99
- const status = identifierUnresolved && classified === 'resolved' ? 'ambiguous' : classified;
107
+ const incomplete = paths.some(path => path.status === 'error');
108
+ const titleAmbiguous = needsTitleDisambiguation(reference, candidates, incomplete);
109
+ const status = classified === 'unresolved' && incomplete ? 'deferred'
110
+ : classified === 'resolved' && (identifierUnresolved || titleAmbiguous) ? 'ambiguous' : classified;
111
+ if (titleAmbiguous && classified !== 'unresolved')
112
+ findings.push({ type: 'title_ambiguous',
113
+ supplied: reference.title, returned: 'Supply a year, author, or verified identifier to disambiguate this title' });
100
114
  const paper = status === 'resolved' ? candidates[0].paper : undefined;
101
115
  const corpusMatches = paper ? findInCorpus(root, paper) : [];
102
- return { input, reference, status, incomplete: paths.some(path => path.status === 'error'), candidates,
116
+ return { input, reference, status, incomplete, candidates,
103
117
  ...(paper ? { paper } : {}), findings, paths_tried: paths, already_in_corpus: corpusMatches.length > 0, corpus_matches: corpusMatches };
104
118
  }
105
119
  //# 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
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Daemon Command Handlers
3
3
  *
4
- * Handlers for daemon-related CLI commands (behavior management, daemon init).
4
+ * Handlers for daemon-related CLI commands (lifecycle, behavior management, daemon init).
5
5
  * Each handler delegates to existing scripts in tools/.
6
6
  *
7
7
  * @tests @test/unit/cli/handlers/coverage.test.ts
@@ -22,6 +22,20 @@ class DaemonHandler {
22
22
  return runner.run(this.scriptPath, ctx.args);
23
23
  }
24
24
  }
25
+ /** Runs the existing daemon CLI without changing its shared lifecycle state. */
26
+ class DaemonControlHandler extends DaemonHandler {
27
+ id = 'daemon';
28
+ name = 'Daemon';
29
+ description = 'Manage the daemon: start, stop, status, chat, attach and scheduled tasks';
30
+ scriptPath = 'tools/daemon/index.mjs';
31
+ async execute(ctx) {
32
+ const runner = createScriptRunner(await getFrameworkRoot());
33
+ return runner.run(this.scriptPath, ctx.args, { cwd: ctx.cwd });
34
+ }
35
+ async help(ctx) {
36
+ return this.execute({ ...ctx, args: ['--help'] });
37
+ }
38
+ }
25
39
  /**
26
40
  * Behavior Handler
27
41
  *
@@ -47,12 +61,14 @@ class DaemonInitHandler extends DaemonHandler {
47
61
  /**
48
62
  * Exported handler instances
49
63
  */
64
+ export const daemonHandler = new DaemonControlHandler();
50
65
  export const behaviorHandler = new BehaviorHandler();
51
66
  export const daemonInitHandler = new DaemonInitHandler();
52
67
  /**
53
68
  * All daemon handlers for registration
54
69
  */
55
70
  export const daemonHandlers = [
71
+ daemonHandler,
56
72
  behaviorHandler,
57
73
  daemonInitHandler,
58
74
  ];
@@ -1,10 +1,10 @@
1
1
  // Validate public doctor flags before routing early-return modes.
2
2
  import { argsTerminatorIndex, hasPositionalOrSwitch, requireFlagValue, valueTokenIndexes } from '../flag-parsing.js';
3
3
  export function parsePublicDoctorFlags(args) {
4
- const valueFlags = ['--provider', '--bundle', '--scope', '--context-baseline', '--context-budget-tokens', '--cli', '--forget-approval'];
4
+ const valueFlags = ['--provider', '--bundle', '--scope', '--context-baseline', '--context-budget-tokens', '--cli', '--forget-approval', '--group'];
5
5
  const knownFlags = new Set([
6
6
  ...valueFlags, '--list-approvals', '--all-providers', '--probe-workers', '--qualify', '--yes', '--dry-run', '--no-budget-check', '--strict-context', '--json',
7
- '--decision-offload', '--deployment', '--user', '--verbose', '-v', '--project-local', '--quiet', '--help', '-h',
7
+ '--resources', '--decision-offload', '--deployment', '--user', '--verbose', '-v', '--project-local', '--quiet', '--help', '-h',
8
8
  ]);
9
9
  const hasSwitch = (name) => hasPositionalOrSwitch(args, name, valueFlags);
10
10
  const values = new Map();
@@ -21,19 +21,24 @@ export function parsePublicDoctorFlags(args) {
21
21
  throw new Error(`Unknown flag: ${name}`);
22
22
  }
23
23
  }
24
+ if (values.get('--group') !== undefined && !hasSwitch('--resources'))
25
+ throw new Error('--group requires --resources');
26
+ if (hasSwitch('--resources') && (['--probe-workers', '--decision-offload', '--deployment', '--user', '--project-local'].some(hasSwitch) || values.get('--scope') !== undefined)) {
27
+ throw new Error('--resources must run separately from other doctor modes');
28
+ }
24
29
  if (hasSwitch('--decision-offload') && (hasSwitch('--probe-workers') || hasSwitch('--deployment') || hasSwitch('--user') || values.get('--scope') !== undefined)) {
25
30
  throw new Error('--decision-offload is a separate offline mode; do not combine it with worker, deployment or user-scope checks');
26
31
  }
27
32
  if (['--list-approvals', '--forget-approval', '--qualify', '--cli', '--yes', '--dry-run'].some(flag => hasSwitch(flag) || values.get(flag)) && !hasSwitch('--probe-workers')) {
28
33
  throw new Error('--list-approvals, --forget-approval, --qualify, --cli, --yes and --dry-run require --probe-workers');
29
34
  }
30
- if ((hasSwitch('--list-approvals') || values.get('--forget-approval')) && ((hasSwitch('--list-approvals') && values.get('--forget-approval')) || ['--qualify', '--dry-run', '--decision-offload', '--deployment', '--user'].some(hasSwitch) || values.get('--scope') !== undefined)) {
35
+ if ((hasSwitch('--list-approvals') || values.get('--forget-approval')) && ((hasSwitch('--list-approvals') && values.get('--forget-approval')) || ['--qualify', '--dry-run', '--resources', '--decision-offload', '--deployment', '--user'].some(hasSwitch) || values.get('--scope') !== undefined)) {
31
36
  throw new Error('Approval management must run separately from other doctor modes');
32
37
  }
33
38
  if (values.get('--forget-approval') && !hasSwitch('--yes'))
34
39
  throw new Error('--forget-approval requires --yes');
35
- if (hasSwitch('--json') && !hasSwitch('--probe-workers') && !hasSwitch('--deployment') && !hasSwitch('--decision-offload')) {
36
- throw new Error('--json requires --probe-workers or --deployment or --decision-offload');
40
+ if (hasSwitch('--json') && !hasSwitch('--probe-workers') && !hasSwitch('--deployment') && !hasSwitch('--decision-offload') && !hasSwitch('--resources')) {
41
+ throw new Error('--json requires --probe-workers or --deployment or --decision-offload or --resources');
37
42
  }
38
43
  return { hasSwitch, values };
39
44
  }
@@ -18,10 +18,12 @@ Options:
18
18
  --yes Confirm worker qualification or approval removal
19
19
  --dry-run With --probe-workers, preview qualification without writes
20
20
  --cli NAME Limit worker probes, qualification, or approvals to one CLI
21
+ --group <name> Apply the named group cap (requires --resources)
22
+ --resources Report live host resources, threshold origins and remaining worker slots (supports --json)
21
23
  --decision-offload Show offline advisory decision readiness and adoption report
22
24
  --probe-workers Run bounded worker CLI version probes (default: config-only, no subprocess)
23
25
  --project-local Include project-local artifact diagnostics
24
- --json Emit machine-readable output (with --probe-workers: one worker-probe record per CLI; with --deployment: deployment verification; with --decision-offload: offline snapshot)
26
+ --json Emit machine-readable output (with --probe-workers: one worker-probe record per CLI; with --deployment: deployment verification; with --decision-offload: offline snapshot; with --resources: host capacity)
25
27
  --verbose, -v Include verbose diagnostics
26
28
  --help, -h Show this help
27
29
 
@@ -29,6 +31,7 @@ Exit status:
29
31
  0 Checks completed; ordinary doctor warnings are advisory.
30
32
  1 Diagnostic errors, failed or partial explicit worker qualification, or blocked recorded invocations.
31
33
  2 Invalid usage.
34
+ --resources exits 1 when slots are zero.
32
35
  --qualify uses the same exit status in text and JSON output.
33
36
  `;
34
37
  //# sourceMappingURL=doctor-help.js.map
@@ -19,7 +19,7 @@ import { statusHandler, wizardHandler, migrateWorkspaceHandler, rollbackWorkspac
19
19
  import { prefillCardsHandler, contributeStartHandler, validateMetadataHandler, doctorHandler, contextFirewallHandler, updateHandler, utilityHandlers, } from './utilities.js';
20
20
  import { skillLintHandler } from './skill-lint.js';
21
21
  import { addAgentHandler, addCommandHandler, addSkillHandler, addBehaviorHandler, addTemplateHandler, scaffoldAddonHandler, scaffoldExtensionHandler, scaffoldFrameworkHandler, scaffoldingHandlers, } from './scaffolding.js';
22
- import { behaviorHandler, daemonInitHandler, daemonHandlers, } from './daemon.js';
22
+ import { behaviorHandler, daemonHandler, daemonInitHandler, daemonHandlers, } from './daemon.js';
23
23
  import { housekeeperHandler, housekeeperHandlers, } from './housekeeper.js';
24
24
  import { ralphHandler, ralphStatusHandler, ralphAbortHandler, ralphResumeHandler, ralphAttachHandler, ralphExternalHandler, ralphMemoryHandler, ralphConfigHandler, ralphHandlers, } from './ralph.js';
25
25
  import { mcpHandler, catalogHandler, listHandler, removeHandler, promoteHandler, newBundleHandler, quickrefHandler, newProjectHandler, installPluginHandler, uninstallPluginHandler, pluginStatusHandler, packagePluginHandler, packageAllPluginsHandler, indexHandler, corpusHandler, discoverHandler, showHandler, featuresHandler, skillsHandler, configHandler, opsHandler, storageHandler, activityLogHandler, kbHandler, memoryHandler, reflectionsHandler, provenanceHandler, researchStoreHandler, researchQueryHandler, chunkHandler, fanoutHandler, rlmPrepHandler, rlmSearchHandler, rlmStatusCliHandler, rlmCacheHandler, subcommandHandlers, } from './subcommands.js';
@@ -98,7 +98,7 @@ installPluginHandler, uninstallPluginHandler, pluginStatusHandler, packagePlugin
98
98
  // Scaffolding
99
99
  addAgentHandler, addCommandHandler, addSkillHandler, addBehaviorHandler, addTemplateHandler, scaffoldAddonHandler, scaffoldExtensionHandler, scaffoldFrameworkHandler,
100
100
  // Daemon
101
- behaviorHandler, daemonInitHandler, housekeeperHandler,
101
+ behaviorHandler, daemonHandler, daemonInitHandler, housekeeperHandler,
102
102
  // Ralph
103
103
  ralphHandler, ralphStatusHandler, ralphAbortHandler, ralphResumeHandler, ralphAttachHandler, ralphExternalHandler, ralphMemoryHandler, ralphConfigHandler,
104
104
  // Mission Control