@aiwg/cli 2026.10.14 → 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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,401 @@
1
+ /**
2
+ * ConciergeIntentRouter — classifies user intent and dispatches to the correct
3
+ * AIWG skill, agent, or flow for the daemon Concierge.
4
+ *
5
+ * Pipeline: CLASSIFY → MATCH → CAPABILITY CHECK → DISPATCH → ABSORB
6
+ *
7
+ * Design: v1 uses pattern-matching intent classification (prompt-based upgrade
8
+ * is a future enhancement). The router never exposes internal
9
+ * skill/agent names in user-facing output — only the result reaches
10
+ * the user. Routing decisions are logged to daemon session state for
11
+ * steward diagnostics.
12
+ *
13
+ * @issue #606
14
+ * @tests @test/unit/daemon/concierge/intent-router.test.js
15
+ */
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Intent category patterns
19
+ // ---------------------------------------------------------------------------
20
+
21
+ /**
22
+ * Ordered list of categories, each with a set of regex patterns.
23
+ * First match wins. 'conversational' is the catch-all fallback.
24
+ */
25
+ const INTENT_PATTERNS = [
26
+ {
27
+ category: 'maintenance',
28
+ patterns: [
29
+ /\baiwg\s+(up\s+to\s+date|version|update|upgrade|sync|health|doctor|check)\b/i,
30
+ /\b(health\s+check|doctor|is\s+aiwg|update\s+aiwg|check\s+for\s+updates?)\b/i,
31
+ /\binstall(ation)?\s+(health|status)\b/i,
32
+ /\bvalidate[\s-]?metadata\b/i,
33
+ /\bcleanup\s+audit\b/i,
34
+ ],
35
+ },
36
+ {
37
+ category: 'scheduling',
38
+ patterns: [
39
+ /\b(run|execute|do|schedule|set\s+up|create)\s+.{0,40}\b(every|each|daily|weekly|morning|night|hour|minute|cron|recurring|interval)\b/i,
40
+ /\b(cron|schedule|recurring|automation)\b/i,
41
+ /\brun\s+.{0,30}\s+at\s+\d/i,
42
+ ],
43
+ },
44
+ {
45
+ category: 'agent-teams',
46
+ patterns: [
47
+ /\b(run|start|launch|kick\s+off|execute)\s+a?\s*(security|test|review|audit|analysis)\s*(team|squad|crew|group)?\b/i,
48
+ /\bagent\s+team\b/i,
49
+ /\bmulti.agent\b/i,
50
+ /\b(security|compliance|performance)\s+review\b/i,
51
+ /\bparallel\s+(agents?|review|execution)\b/i,
52
+ ],
53
+ },
54
+ {
55
+ category: 'query',
56
+ patterns: [
57
+ /\b(what|which|how|where|when|who|why|list|show|what'?s)\b.*\b(command|skill|agent|feature|option|available|install|use|work|mean)\b/i,
58
+ /\b(help|how\s+do\s+i|how\s+to|can\s+(i|you|aiwg)|does\s+(it|aiwg)|what\s+is|explain)\b/i,
59
+ /\b(aiwg\s+kb|knowledge\s+base|documentation|docs)\b/i,
60
+ /\bwhat\s+(are|were|can)\s+.{3,30}\b(command|skill|agent|feature|option|available|install)\b/i,
61
+ /\bhow\s+(does|do|can|should)\s+.{3,60}\b(work|function|run|operate|behave)\b/i,
62
+ ],
63
+ },
64
+ {
65
+ category: 'sdlc',
66
+ patterns: [
67
+ /\b(transition|move|start|begin|kick\s+off|enter)\s+(to\s+|into\s+)?(inception|elaboration|construction|transition|production)\b/i,
68
+ /\b(project\s+status|phase\s+(gate|check|status)|iteration\s+\d+|sprint\s+\d+)\b/i,
69
+ /\b(deploy(ment)?|release|rollout)\s+(to\s+)?(prod(uction)?|staging)\b/i,
70
+ /\b(requirements?|architecture|sad|adr|test\s+plan|risk\s+register)\b/i,
71
+ /\b(intake|onboard|handoff|retrospective|retro)\b/i,
72
+ /\b(fix|address|resolve|work\s+on)\s+(issue|bug|ticket|#\d+)\b/i,
73
+ /\baddress.issues?\b/i,
74
+ /\b(run|start|execute)\s+(the\s+)?ralph\s+loop\b/i,
75
+ ],
76
+ },
77
+ {
78
+ category: 'conversational',
79
+ patterns: [
80
+ // Catch-all — always matches; must be last
81
+ /.*/,
82
+ ],
83
+ },
84
+ ];
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Default handler catalog (v1 — curated by category)
88
+ // ---------------------------------------------------------------------------
89
+
90
+ /**
91
+ * Maps each intent category to its default handler descriptor.
92
+ * Handler ids reference AIWG skills/agents/flows by their internal id.
93
+ * The id is used for dispatch but never surfaced to the user.
94
+ */
95
+ const DEFAULT_HANDLERS = {
96
+ maintenance: {
97
+ id: 'aiwg-steward',
98
+ type: 'agent',
99
+ description: 'AIWG installation health and self-maintenance',
100
+ requires_feature: null,
101
+ },
102
+ scheduling: {
103
+ id: 'schedule',
104
+ type: 'skill',
105
+ description: 'Recurring task scheduling',
106
+ requires_feature: 'cron',
107
+ },
108
+ 'agent-teams': {
109
+ id: 'flow-security-review-cycle',
110
+ type: 'flow',
111
+ description: 'Multi-agent review and team coordination',
112
+ requires_feature: 'agent_teams',
113
+ },
114
+ sdlc: {
115
+ id: 'sdlc-complete',
116
+ type: 'framework',
117
+ description: 'SDLC phase workflows and project management',
118
+ requires_feature: null,
119
+ },
120
+ query: {
121
+ id: 'aiwg-kb',
122
+ type: 'skill',
123
+ description: 'AIWG knowledge base and help',
124
+ requires_feature: null,
125
+ },
126
+ conversational: {
127
+ id: 'concierge-inline',
128
+ type: 'inline',
129
+ description: 'Direct concierge response',
130
+ requires_feature: null,
131
+ },
132
+ };
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Sensitive operation categories for discreet logging
136
+ // ---------------------------------------------------------------------------
137
+
138
+ const SENSITIVE_CATEGORIES = new Set(['maintenance']);
139
+ const SENSITIVE_KEYWORDS = /\b(token|secret|key|credential|password|auth|cert(ificate)?|rotate)\b/i;
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // ConciergeIntentRouter
143
+ // ---------------------------------------------------------------------------
144
+
145
+ export class ConciergeIntentRouter {
146
+ /**
147
+ * @param {Object} [options]
148
+ * @param {Object|null} [options.capabilityMatrix] Loaded capability matrix
149
+ * (from src/providers/capability-matrix.ts). If null, capability checks
150
+ * are skipped.
151
+ * @param {Object|null} [options.catalog] Installed catalog for
152
+ * semantic search (future v2 enhancement). Currently unused.
153
+ * @param {Object|null} [options.sessionLog] Session state logger.
154
+ * Must expose: log(entry: Object) => void
155
+ * @param {number} [options.confidenceThreshold=0.7] Below this score,
156
+ * the router asks for clarification instead of dispatching.
157
+ * @param {string|null} [options.provider] Current provider key
158
+ * (e.g. 'claude-code'). Used for capability checks.
159
+ */
160
+ constructor({
161
+ capabilityMatrix = null,
162
+ catalog = null,
163
+ sessionLog = null,
164
+ confidenceThreshold = 0.7,
165
+ provider = null,
166
+ } = {}) {
167
+ this._capabilityMatrix = capabilityMatrix;
168
+ this._catalog = catalog;
169
+ this._sessionLog = sessionLog;
170
+ this.confidenceThreshold = confidenceThreshold;
171
+ this.provider = provider;
172
+ }
173
+
174
+ // -------------------------------------------------------------------------
175
+ // Public API
176
+ // -------------------------------------------------------------------------
177
+
178
+ /**
179
+ * Route a raw user message to the appropriate handler.
180
+ *
181
+ * Returns a routing result that the Concierge uses for dispatch.
182
+ * Never exposes internal handler names to the caller directly — the
183
+ * caller is responsible for keeping routing internals out of user output.
184
+ *
185
+ * @param {string} message Raw user message
186
+ * @param {Object} [ctx] Optional per-call context overrides
187
+ * @param {string} [ctx.provider] Override the instance-level provider
188
+ * @returns {RoutingResult}
189
+ */
190
+ route(message, ctx = {}) {
191
+ const provider = ctx.provider ?? this.provider;
192
+ const { category, confidence } = this.classify(message);
193
+ const isSensitive = this._isSensitive(message, category);
194
+
195
+ if (confidence < this.confidenceThreshold) {
196
+ const result = this._buildFallback(message, 'low-confidence', { category, confidence });
197
+ this._logDecision({ message: isSensitive ? '[redacted]' : message, ...result, provider });
198
+ return result;
199
+ }
200
+
201
+ const handler = this._matchHandler(category, message);
202
+
203
+ if (!handler) {
204
+ const result = this._buildFallback(message, 'no-handler', { category, confidence });
205
+ this._logDecision({ message: isSensitive ? '[redacted]' : message, ...result, provider });
206
+ return result;
207
+ }
208
+
209
+ const available = this._checkCapability(handler, provider);
210
+
211
+ if (!available) {
212
+ const result = this._buildFallback(message, 'capability-unavailable', {
213
+ category,
214
+ confidence,
215
+ handler,
216
+ provider,
217
+ });
218
+ this._logDecision({ message: isSensitive ? '[redacted]' : message, ...result, provider });
219
+ return result;
220
+ }
221
+
222
+ const result = {
223
+ ok: true,
224
+ category,
225
+ confidence,
226
+ handler,
227
+ provider,
228
+ fallback: false,
229
+ isSensitive,
230
+ };
231
+
232
+ this._logDecision({ message: isSensitive ? '[redacted]' : message, ...result });
233
+ return result;
234
+ }
235
+
236
+ /**
237
+ * Classify the user message into an intent category.
238
+ *
239
+ * Returns the category and a confidence score in [0, 1].
240
+ * Confidence is 1.0 for a specific-category match, 0.5 for conversational.
241
+ *
242
+ * @param {string} message
243
+ * @returns {{ category: string, confidence: number }}
244
+ */
245
+ classify(message) {
246
+ if (!message || typeof message !== 'string') {
247
+ return { category: 'conversational', confidence: 0.5 };
248
+ }
249
+
250
+ const normalized = message.trim();
251
+
252
+ for (const { category, patterns } of INTENT_PATTERNS) {
253
+ // Skip catch-all for primary classification pass
254
+ if (category === 'conversational') continue;
255
+
256
+ for (const pattern of patterns) {
257
+ if (pattern.test(normalized)) {
258
+ return { category, confidence: 1.0 };
259
+ }
260
+ }
261
+ }
262
+
263
+ return { category: 'conversational', confidence: 0.5 };
264
+ }
265
+
266
+ /**
267
+ * Expose the pattern catalog for testing and introspection.
268
+ * @returns {Array<{category: string, patterns: RegExp[]}>}
269
+ */
270
+ getPatterns() {
271
+ return INTENT_PATTERNS.slice(0, -1); // exclude catch-all
272
+ }
273
+
274
+ /**
275
+ * Expose the handler catalog for testing and introspection.
276
+ * @returns {Record<string, Object>}
277
+ */
278
+ getHandlers() {
279
+ return { ...DEFAULT_HANDLERS };
280
+ }
281
+
282
+ // -------------------------------------------------------------------------
283
+ // Private helpers
284
+ // -------------------------------------------------------------------------
285
+
286
+ /**
287
+ * Find the best handler for the given category and message.
288
+ * v1: returns the default catalog handler for the category.
289
+ * v2: will do semantic search against the installed catalog.
290
+ */
291
+ _matchHandler(category, _message) {
292
+ return DEFAULT_HANDLERS[category] ?? null;
293
+ }
294
+
295
+ /**
296
+ * Check whether the handler's required feature is available on the provider.
297
+ * Returns true if no capability matrix is configured or the handler has
298
+ * no feature requirement.
299
+ */
300
+ _checkCapability(handler, provider) {
301
+ if (!this._capabilityMatrix || !provider || !handler.requires_feature) {
302
+ return true;
303
+ }
304
+
305
+ const caps = this._capabilityMatrix.providers?.[provider];
306
+ if (!caps) return true;
307
+
308
+ const feature = handler.requires_feature;
309
+ const native = caps.native_features?.[feature];
310
+ const emulated = caps.emulation?.[feature];
311
+
312
+ return !!(native || (emulated && emulated !== null));
313
+ }
314
+
315
+ /**
316
+ * Build a standardised fallback result.
317
+ */
318
+ _buildFallback(message, reason, details = {}) {
319
+ return {
320
+ ok: false,
321
+ fallback: true,
322
+ reason,
323
+ category: details.category ?? 'unknown',
324
+ confidence: details.confidence ?? 0,
325
+ handler: null,
326
+ provider: details.provider ?? null,
327
+ isSensitive: this._isSensitive(message, details.category),
328
+ // Suggestion for in-persona user response (never expose raw reason)
329
+ suggestion: this._buildFallbackSuggestion(reason, details),
330
+ };
331
+ }
332
+
333
+ /**
334
+ * Build a user-friendly (in-persona) fallback suggestion.
335
+ * These strings are consumed by the Concierge response layer — they are NOT
336
+ * shown verbatim to the user; the Concierge applies tone rules before surfacing.
337
+ */
338
+ _buildFallbackSuggestion(reason, details) {
339
+ switch (reason) {
340
+ case 'low-confidence':
341
+ return 'Could you clarify what you need? I want to make sure I route this correctly.';
342
+ case 'no-handler':
343
+ return `I don\'t have a handler for that category yet. Here\'s what I can help with: maintenance, scheduling, agent teams, SDLC workflows, and general questions.`;
344
+ case 'capability-unavailable': {
345
+ const feature = details.handler?.requires_feature;
346
+ const provider = details.provider;
347
+ return feature && provider
348
+ ? `That feature (${feature}) isn\'t available on ${provider}. I can use AIWG emulation — would you like me to proceed that way?`
349
+ : 'That capability isn\'t available in the current environment. Would you like to see alternatives?';
350
+ }
351
+ default:
352
+ return 'I wasn\'t able to handle that request. Could you rephrase it?';
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Determine if the message or category is sensitive (redact from logs).
358
+ */
359
+ _isSensitive(message, category) {
360
+ if (SENSITIVE_CATEGORIES.has(category)) return false; // maintenance is not sensitive
361
+ return typeof message === 'string' && SENSITIVE_KEYWORDS.test(message);
362
+ }
363
+
364
+ /**
365
+ * Log the routing decision to the session log.
366
+ * Log entries are consumed by the steward for diagnostics — never surfaced
367
+ * directly to the user.
368
+ */
369
+ _logDecision(entry) {
370
+ if (!this._sessionLog) return;
371
+
372
+ try {
373
+ this._sessionLog.log({
374
+ source: 'concierge:intent-router',
375
+ timestamp: new Date().toISOString(),
376
+ ...entry,
377
+ });
378
+ } catch {
379
+ // Non-fatal — logging failures must not disrupt routing
380
+ }
381
+ }
382
+ }
383
+
384
+ // ---------------------------------------------------------------------------
385
+ // Exports
386
+ // ---------------------------------------------------------------------------
387
+
388
+ export { INTENT_PATTERNS, DEFAULT_HANDLERS };
389
+
390
+ /**
391
+ * @typedef {Object} RoutingResult
392
+ * @property {boolean} ok True when a handler was matched and is available
393
+ * @property {string} category Classified intent category
394
+ * @property {number} confidence Classification confidence [0, 1]
395
+ * @property {Object|null} handler Matched handler descriptor (or null on fallback)
396
+ * @property {string|null} provider Provider key used for capability check
397
+ * @property {boolean} fallback True when ok=false and a fallback was triggered
398
+ * @property {boolean} isSensitive True when message contains sensitive keywords
399
+ * @property {string} [reason] Fallback reason (present when fallback=true)
400
+ * @property {string} [suggestion] In-persona fallback suggestion (when fallback=true)
401
+ */
@@ -0,0 +1,272 @@
1
+ /**
2
+ * ConciergeOrchestrator — wires the intent router, response translator,
3
+ * and memory manager into a single pipeline that mediates daemon interactions.
4
+ *
5
+ * Pipeline:
6
+ * user input → intent router → handler dispatch → response translator → user output
7
+ *
8
+ * Lifecycle hooks:
9
+ * - onSessionStart(ctx) — greeting with memory context
10
+ * - handleMessage(msg,ctx) — full classify→dispatch→translate pipeline
11
+ * - translateResponse(raw) — standalone pre-response translation
12
+ * - onError(error, ctx) — error absorption
13
+ *
14
+ * @issue #642
15
+ * @tests @test/unit/daemon/concierge/orchestrator.test.js
16
+ */
17
+
18
+ import { ConciergeIntentRouter } from './intent-router.mjs';
19
+ import { ConciergeResponseTranslator } from './response-translator.mjs';
20
+
21
+ export class ConciergeOrchestrator {
22
+ /**
23
+ * @param {Object} options
24
+ * @param {Object} options.supervisor AgentSupervisor for task dispatch
25
+ * @param {Object} [options.memoryManager] MemoryManager for session context
26
+ * @param {Object} [options.capabilityMatrix] Provider capability data
27
+ * @param {string} [options.provider] Current provider key
28
+ * @param {Object} [options.sessionLog] Session state logger
29
+ */
30
+ constructor(options = {}) {
31
+ this.supervisor = options.supervisor;
32
+ this.memoryManager = options.memoryManager || null;
33
+ this.provider = options.provider || null;
34
+
35
+ this.router = new ConciergeIntentRouter({
36
+ capabilityMatrix: options.capabilityMatrix || null,
37
+ provider: this.provider,
38
+ sessionLog: options.sessionLog || null,
39
+ });
40
+
41
+ this.translator = new ConciergeResponseTranslator();
42
+
43
+ this._sessionStarted = false;
44
+ this._sessionContext = {};
45
+ }
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Session lifecycle
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /**
52
+ * Called on first interaction or explicit session start.
53
+ * Loads memory context and returns a contextual greeting.
54
+ *
55
+ * @param {Object} [ctx] Session context (branch, pending tasks, etc.)
56
+ * @returns {{ greeting: string, memoryContext: string }}
57
+ */
58
+ onSessionStart(ctx = {}) {
59
+ this._sessionStarted = true;
60
+ this._sessionContext = { ...ctx, startedAt: new Date().toISOString() };
61
+
62
+ const memoryContext = this.memoryManager?.getContext?.() || '';
63
+
64
+ // Build a contextual greeting — not a generic hello
65
+ let greeting = 'Good to see you. What are we working on?';
66
+
67
+ if (memoryContext) {
68
+ // Memory exists ��� reference prior context
69
+ const hasActiveWork = memoryContext.includes('in progress') ||
70
+ memoryContext.includes('working on') ||
71
+ memoryContext.includes('active');
72
+ if (hasActiveWork) {
73
+ greeting = 'Picking up where we left off. What would you like to focus on?';
74
+ } else {
75
+ greeting = 'Welcome back. What can I help with?';
76
+ }
77
+ }
78
+
79
+ return { greeting, memoryContext };
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Message handling — the main pipeline
84
+ // ---------------------------------------------------------------------------
85
+
86
+ /**
87
+ * Process a user message through the full concierge pipeline.
88
+ *
89
+ * classify → route → dispatch → translate → return
90
+ *
91
+ * @param {string} message User message
92
+ * @param {Object} [ctx] Per-call context
93
+ * @returns {Promise<ConciergeResult>}
94
+ */
95
+ async handleMessage(message, ctx = {}) {
96
+ // Ensure session is started
97
+ if (!this._sessionStarted) {
98
+ this.onSessionStart(ctx);
99
+ }
100
+
101
+ // Step 1: Route — classify intent, match handler, check capability
102
+ const routing = this.router.route(message, { provider: ctx.provider || this.provider });
103
+
104
+ // Step 2: Dispatch based on routing result
105
+ let rawOutput;
106
+ let taskId = null;
107
+
108
+ if (routing.fallback) {
109
+ // Fallback — use the router's suggestion as the response
110
+ rawOutput = routing.suggestion || 'Could you clarify what you need?';
111
+ } else if (routing.handler?.type === 'inline') {
112
+ // Conversational — concierge responds directly (no task dispatch)
113
+ rawOutput = this._handleInline(message, routing);
114
+ } else {
115
+ // Dispatch to supervisor as a task
116
+ const dispatchResult = this._dispatch(message, routing);
117
+ taskId = dispatchResult.taskId;
118
+ // For async tasks, return immediately with task reference
119
+ // The pre-response hook will translate the result when it completes
120
+ return {
121
+ type: 'task-dispatched',
122
+ taskId,
123
+ category: routing.category,
124
+ handler: routing.handler?.id,
125
+ message: `On it. I've queued that for ${routing.handler?.description || routing.category}.`,
126
+ };
127
+ }
128
+
129
+ // Step 3: Translate the response
130
+ const translated = this.translator.translate(rawOutput, {
131
+ isSensitive: routing.isSensitive,
132
+ });
133
+
134
+ return {
135
+ type: 'response',
136
+ taskId,
137
+ category: routing.category,
138
+ response: translated.translated,
139
+ bypassed: translated.bypassed,
140
+ discreetApplied: translated.discreetApplied,
141
+ };
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // Pre-response hook — translate raw task output
146
+ // ---------------------------------------------------------------------------
147
+
148
+ /**
149
+ * Translate raw output from a completed task.
150
+ * Called by the daemon when a supervisor task completes.
151
+ *
152
+ * @param {string} raw Raw task output
153
+ * @param {Object} [options] Translation options
154
+ * @param {boolean} [options.raw] Skip translation
155
+ * @param {boolean} [options.verbose] Skip translation
156
+ * @param {string} [options.sourceType] Output type hint
157
+ * @param {boolean} [options.isSensitive] Mark as sensitive
158
+ * @returns {TranslationResult}
159
+ */
160
+ translateResponse(raw, options = {}) {
161
+ return this.translator.translate(raw, options);
162
+ }
163
+
164
+ // ---------------------------------------------------------------------------
165
+ // Error absorption
166
+ // ---------------------------------------------------------------------------
167
+
168
+ /**
169
+ * Absorb an error and return a composed, non-technical response.
170
+ * Never exposes stack traces or internal state to the user.
171
+ *
172
+ * @param {Error|string} error The error to absorb
173
+ * @param {Object} [ctx] Context about what was happening
174
+ * @returns {{ response: string, severity: string }}
175
+ */
176
+ onError(error, ctx = {}) {
177
+ const message = error instanceof Error ? error.message : String(error);
178
+ const stack = error instanceof Error ? error.stack : '';
179
+
180
+ // Classify the error
181
+ let severity = 'recoverable';
182
+ let response;
183
+
184
+ if (message.includes('ENOENT') || message.includes('not found')) {
185
+ severity = 'user-actionable';
186
+ response = 'I couldn\'t find what was needed. Could you check the path or resource exists?';
187
+ } else if (message.includes('ECONNREFUSED') || message.includes('timeout') || message.includes('ETIMEDOUT')) {
188
+ severity = 'recoverable';
189
+ response = 'A connection issue occurred. I\'ll retry shortly.';
190
+ } else if (message.includes('permission') || message.includes('EACCES')) {
191
+ severity = 'user-actionable';
192
+ response = 'I don\'t have the required permissions. You may need to check access settings.';
193
+ } else if (message.includes('INVALID_PARAMS') || message.includes('Missing required')) {
194
+ severity = 'user-actionable';
195
+ response = `Something was missing from the request: ${message.replace(/^.*?:\s*/, '')}`;
196
+ } else {
197
+ severity = 'system-level';
198
+ response = 'Something went wrong internally. Details have been logged.';
199
+ }
200
+
201
+ return { response, severity, logged: true };
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Status
206
+ // ---------------------------------------------------------------------------
207
+
208
+ /**
209
+ * Return concierge status for IPC/CLI inspection.
210
+ */
211
+ getStatus() {
212
+ return {
213
+ enabled: true,
214
+ sessionStarted: this._sessionStarted,
215
+ sessionContext: this._sessionContext,
216
+ provider: this.provider,
217
+ routerPatterns: this.router.getPatterns().length,
218
+ routerHandlers: Object.keys(this.router.getHandlers()).length,
219
+ };
220
+ }
221
+
222
+ // ---------------------------------------------------------------------------
223
+ // Private
224
+ // ---------------------------------------------------------------------------
225
+
226
+ /**
227
+ * Handle inline/conversational messages directly.
228
+ * No task dispatch — the concierge responds in-persona.
229
+ */
230
+ _handleInline(message, routing) {
231
+ const lower = (message || '').toLowerCase().trim();
232
+
233
+ if (/^(thanks|thank you|cheers|ta|thx)/i.test(lower)) {
234
+ return 'Happy to help.';
235
+ }
236
+ if (/^(looks? good|perfect|great|nice|ok|okay|👍)/i.test(lower)) {
237
+ return 'Glad that works. Let me know if you need anything else.';
238
+ }
239
+ if (/^(hi|hello|hey|good (morning|afternoon|evening))/i.test(lower)) {
240
+ return this._sessionStarted
241
+ ? 'What can I help with?'
242
+ : this.onSessionStart({}).greeting;
243
+ }
244
+
245
+ return 'Understood. What would you like to do next?';
246
+ }
247
+
248
+ /**
249
+ * Dispatch a message to the supervisor based on routing result.
250
+ */
251
+ _dispatch(message, routing) {
252
+ const handler = routing.handler;
253
+ const prompt = handler.type === 'agent'
254
+ ? message // Agents receive the raw user message
255
+ : `[Concierge → ${handler.id}] ${message}`; // Skills/flows get a tagged prompt
256
+
257
+ const task = this.supervisor.submit(prompt, {
258
+ agent: handler.type === 'agent' ? handler.id : undefined,
259
+ priority: 5, // Chat messages get higher priority
260
+ metadata: {
261
+ source: 'concierge',
262
+ category: routing.category,
263
+ handlerId: handler.id,
264
+ handlerType: handler.type,
265
+ },
266
+ });
267
+
268
+ return { taskId: task.id };
269
+ }
270
+ }
271
+
272
+ export default ConciergeOrchestrator;