@staix/agent-hub 0.35.0 → 0.37.0

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 (165) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +25 -4
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +71 -1
  5. package/docs/agent-notes/adapters.md +5 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +7 -6
  8. package/docs/agent-notes/local-worker.md +1 -0
  9. package/docs/agent-notes/models.md +5 -3
  10. package/docs/agent-notes/tasks.md +9 -2
  11. package/docs/agent-notes/tests.md +1 -1
  12. package/docs/contracts/companion-cli-v1.json +70 -0
  13. package/docs/design/adapters.md +115 -2
  14. package/docs/design/agent-hub-architecture.md +10 -2
  15. package/docs/design/bus.md +8 -0
  16. package/docs/design/execution-reference.md +171 -11
  17. package/docs/design/guidance-experiments.md +438 -0
  18. package/docs/design/guidance-probes.md +802 -0
  19. package/docs/design/model-routes.md +1053 -0
  20. package/docs/design/supervision.md +121 -0
  21. package/docs/design/task-board.md +111 -0
  22. package/docs/dogfood.md +24 -15
  23. package/docs/events.md +20 -1
  24. package/docs/memory.md +3 -3
  25. package/docs/operations.md +366 -133
  26. package/docs/profiles.md +2 -2
  27. package/docs/quickstart.md +114 -3
  28. package/docs/research.md +5 -3
  29. package/docs/sdlc.md +113 -7
  30. package/docs/security.md +88 -6
  31. package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
  32. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  33. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  34. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  35. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  36. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
  37. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  38. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  39. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  40. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  41. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  42. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  43. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  44. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  45. package/docs/verified.json +27 -27
  46. package/package.json +3 -4
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/kimi-hook.js +3570 -1800
  49. package/plugins/agent-hub/server.js +4112 -1913
  50. package/src/adapters/channel-peer.ts +7 -1
  51. package/src/adapters/claude-channel.ts +7 -4
  52. package/src/adapters/compat.ts +10 -10
  53. package/src/adapters/local-probe.ts +174 -0
  54. package/src/adapters/local-worker.ts +233 -22
  55. package/src/adapters/qwen-dual.ts +324 -44
  56. package/src/cli/console-state.ts +25 -6
  57. package/src/cli/console-versions.ts +99 -0
  58. package/src/cli/console.ts +13 -1
  59. package/src/cli/guidance.ts +67 -0
  60. package/src/cli/help.ts +12 -4
  61. package/src/cli/identity.ts +10 -3
  62. package/src/cli/init-prompt.ts +15 -2
  63. package/src/cli/init-required-checks.ts +122 -0
  64. package/src/cli/init-settings.ts +10 -4
  65. package/src/cli/init.ts +39 -3
  66. package/src/cli/install-paths.ts +7 -2
  67. package/src/cli/lineage.ts +78 -0
  68. package/src/cli/main.ts +171 -14
  69. package/src/cli/runtime-version-warning.ts +2 -2
  70. package/src/cli/sdlc-output.ts +9 -5
  71. package/src/cli/setup-research.ts +10 -0
  72. package/src/hub/autonomy-defaults.ts +20 -9
  73. package/src/hub/board.ts +346 -4
  74. package/src/hub/build-entry.ts +11 -0
  75. package/src/hub/bus.ts +12 -0
  76. package/src/hub/ci-watch.ts +4 -4
  77. package/src/hub/config-apply.ts +6 -3
  78. package/src/hub/config-trust.ts +7 -1
  79. package/src/hub/control-client.ts +5 -2
  80. package/src/hub/daemon.ts +508 -26
  81. package/src/hub/delivery-hints.ts +4 -2
  82. package/src/hub/delivery-journal.ts +50 -2
  83. package/src/hub/delivery-public.ts +51 -0
  84. package/src/hub/dogfood-profile.ts +8 -4
  85. package/src/hub/events.ts +3 -2
  86. package/src/hub/execution-lineage-owner.ts +272 -0
  87. package/src/hub/execution-lineage.ts +52 -8
  88. package/src/hub/execution-links.ts +85 -0
  89. package/src/hub/guidance-probe-store.ts +713 -0
  90. package/src/hub/guidance-probes.ts +358 -0
  91. package/src/hub/guidance-variants.ts +398 -0
  92. package/src/hub/handoff.ts +1 -0
  93. package/src/hub/hub-tools.ts +43 -2
  94. package/src/hub/inference.ts +18 -5
  95. package/src/hub/manager.ts +44 -2
  96. package/src/hub/memory-policy.ts +2 -2
  97. package/src/hub/operational-authority.ts +13 -1
  98. package/src/hub/peers.ts +6 -1
  99. package/src/hub/planning.ts +1 -1
  100. package/src/hub/ports.ts +1 -1
  101. package/src/hub/progress.ts +47 -23
  102. package/src/hub/report.ts +2 -0
  103. package/src/hub/research.ts +1 -0
  104. package/src/hub/restart.ts +20 -0
  105. package/src/hub/roles.ts +26 -0
  106. package/src/hub/routing.ts +4 -1
  107. package/src/hub/sdlc-merge.ts +39 -1
  108. package/src/hub/sdlc-release-authorization.ts +139 -17
  109. package/src/hub/sdlc-release-policy.ts +100 -0
  110. package/src/hub/sdlc-release.ts +60 -8
  111. package/src/hub/sdlc.ts +62 -11
  112. package/src/hub/settings.ts +2 -0
  113. package/src/hub/supervision-proposals.ts +405 -0
  114. package/src/hub/supervision-rules.ts +388 -0
  115. package/src/hub/supervision.ts +2 -0
  116. package/src/hub/task-approval.ts +2 -2
  117. package/src/hub/task-repository.ts +5 -0
  118. package/src/hub/tasks.ts +917 -53
  119. package/src/local/probe-errors.ts +28 -0
  120. package/src/local/probe-sandbox.ts +224 -0
  121. package/src/local/probe-types.ts +108 -0
  122. package/src/local/probe-workspace.ts +237 -0
  123. package/src/local/sandbox.ts +71 -2
  124. package/src/local/tools.ts +135 -9
  125. package/src/memory/capture.ts +2 -2
  126. package/src/models/relay.ts +9 -2
  127. package/src/models/route/advisor-trigger.ts +88 -0
  128. package/src/models/route/config.ts +39 -8
  129. package/src/models/route/conversation-view.ts +179 -0
  130. package/src/models/route/decision-evidence.ts +1 -1
  131. package/src/models/route/decision.ts +193 -26
  132. package/src/models/route/escalation-control.ts +30 -0
  133. package/src/models/route/hub-prompts.ts +97 -0
  134. package/src/models/route/judge-choice.ts +155 -0
  135. package/src/models/route/judge-replies.ts +102 -0
  136. package/src/models/route/labels.ts +14 -70
  137. package/src/models/route/observation-signals.ts +250 -0
  138. package/src/models/route/plan-execute-choice.ts +27 -0
  139. package/src/models/route/relay-selector.ts +10 -9
  140. package/src/models/route/runtime.ts +129 -60
  141. package/src/models/route/stage-diagnostics.ts +22 -0
  142. package/src/models/route/stage-evidence.ts +55 -0
  143. package/src/models/route/stage-fallback.ts +58 -0
  144. package/src/models/route/stage-input.ts +155 -0
  145. package/src/models/route/stage.ts +5 -147
  146. package/src/models/route/turn-state.ts +77 -0
  147. package/src/omniroute/client.ts +3 -0
  148. package/src/ui/guidance-panel.ts +156 -0
  149. package/src/ui/guidance-view.ts +43 -0
  150. package/src/ui/lineage-view.ts +34 -0
  151. package/src/ui/plugin.ts +141 -27
  152. package/src/version.ts +4 -0
  153. package/templates/adec/README.md +32 -0
  154. package/templates/adec/ahub.plan-execute.json +23 -0
  155. package/templates/adec/ahub.stage.json +23 -0
  156. package/LICENSES/Apache-2.0.txt +0 -204
  157. package/src/models/route/advisor.ts +0 -102
  158. package/src/models/route/escalation.ts +0 -82
  159. package/src/models/route/judge.ts +0 -23
  160. package/src/models/route/normalize.ts +0 -103
  161. package/src/models/route/plan-execute.ts +0 -52
  162. package/src/models/route/prompts.ts +0 -8
  163. package/src/models/route/signals.ts +0 -247
  164. package/src/models/route/state.ts +0 -54
  165. package/src/models/route/text.ts +0 -61
@@ -0,0 +1,155 @@
1
+ import { types } from "node:util";
2
+ import type { StageEvidence } from "./stage-evidence.ts";
3
+
4
+ export type HostChoicePurpose = "plan_execute_model" | "advisor_judge_model" | "escalation_judge_model";
5
+ export type HostPhase = "planning" | "executing";
6
+ const PACKET_BYTES = 1024;
7
+
8
+ function data(value: unknown, key: string): unknown {
9
+ if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)) return undefined;
10
+ const prototype = Object.getPrototypeOf(value);
11
+ if (prototype !== Object.prototype && prototype !== null) return undefined;
12
+ return Object.getOwnPropertyDescriptor(value, key)?.value;
13
+ }
14
+ const unit = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
15
+ const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
16
+
17
+ /** Compose only checked R1 scalars; no unknown property or serialization hook is copied. */
18
+ export function hostChoicePacket(evidence: StageEvidence, purpose: HostChoicePurpose, phase: HostPhase | undefined, sensitive: boolean): string | undefined {
19
+ try {
20
+ if (purpose !== "plan_execute_model" && purpose !== "advisor_judge_model" && purpose !== "escalation_judge_model") return undefined;
21
+ if (purpose === "plan_execute_model" ? phase !== "planning" && phase !== "executing" : phase !== undefined) return undefined;
22
+ if (data(evidence, "schemaVersion") !== 1 || data(evidence, "kind") !== "stage-route-evidence") return undefined;
23
+ const source = data(evidence, "dimensions");
24
+ const severity = data(source, "severity"), spinning = data(source, "spinning"), exploring = data(source, "exploring"), productionIntensity = data(source, "productionIntensity");
25
+ if (![severity, spinning, exploring, productionIntensity].every(unit)) return undefined;
26
+ const dimensions = { severity, spinning, exploring, productionIntensity };
27
+ let packet: string;
28
+ if (sensitive) packet = JSON.stringify({ schemaVersion: 1, kind: "stage-route-evidence", dimensions });
29
+ else {
30
+ const turn = data(evidence, "turn"), incomplete = data(evidence, "incomplete"), signals = data(evidence, "signals"), scores = data(evidence, "scores");
31
+ if (turn !== "user" && turn !== "tool_result" && turn !== "compaction" && turn !== "other" || typeof incomplete !== "boolean") return undefined;
32
+ const results = data(signals, "results"), failures = data(signals, "failures"), repeatedFailures = data(signals, "repeatedFailures"), reads = data(signals, "reads"), mutations = data(signals, "mutations"), assistantTurns = data(signals, "assistantTurns");
33
+ const tests = data(signals, "tests"), fault = data(signals, "fault"), efficient = data(scores, "efficient"), capable = data(scores, "capable");
34
+ if (![results, failures, repeatedFailures, reads, mutations, assistantTurns].every(count) || !unit(efficient) || !unit(capable)
35
+ || tests !== "none" && tests !== "pass" && tests !== "fail" && tests !== "unknown"
36
+ || fault !== "none" && fault !== "reported" && fault !== "exception" && fault !== "critical") return undefined;
37
+ const stage = { schemaVersion: 1, kind: "stage-route-evidence", turn, incomplete,
38
+ signals: { results, failures, repeatedFailures, reads, mutations, assistantTurns, tests, fault }, dimensions, scores: { efficient, capable } };
39
+ packet = JSON.stringify({ schemaVersion: 1, kind: "host-route-choice-evidence", purpose, ...(phase ? { phase } : {}), stage });
40
+ }
41
+ return Buffer.byteLength(packet, "utf8") <= PACKET_BYTES ? packet : undefined;
42
+ } catch { return undefined; }
43
+ }
44
+
45
+ export interface ChoiceWindow<T> {
46
+ result: Promise<T | undefined>;
47
+ readonly commonSettled: Promise<void>;
48
+ close(): Promise<T | undefined>;
49
+ }
50
+
51
+ /**
52
+ * ponytail: common host preparation has no cancellation API. Closing races it, not joins it.
53
+ * Only the separately started request is abortable/joined. Upgrade common ports to optional
54
+ * abort/currentness support if an actual hang is observed; do not infer physical cancellation.
55
+ */
56
+ export function startChoiceWindow<P, T>(ports: {
57
+ signal: AbortSignal;
58
+ prepare(closed: () => boolean): Promise<P | undefined>;
59
+ request(prepared: P, signal: AbortSignal, closed: () => boolean): Promise<T | undefined>;
60
+ }): ChoiceWindow<T> {
61
+ const controller = new AbortController();
62
+ let closed = false, settled = false, value: T | undefined, failed = false, failure: unknown;
63
+ let request: Promise<T | undefined> | undefined, closing: Promise<T | undefined> | undefined;
64
+ let resolve!: (value: T | undefined) => void, reject!: (error: unknown) => void;
65
+ const result = new Promise<T | undefined>((yes, no) => { resolve = yes; reject = no; });
66
+ // A later await still observes rejection; this consumer prevents an unhandled gap during fallback.
67
+ void result.catch(() => {});
68
+ const done = (answer: T | undefined) => { if (!closed) { settled = true; value = answer; resolve(answer); } };
69
+ const refuse = (error: unknown) => { if (!closed) { settled = true; failed = true; failure = error; reject(error); } };
70
+ const close = (): Promise<T | undefined> => {
71
+ if (closing) return closing;
72
+ let complete!: (value: T | undefined) => void, fail!: (error: unknown) => void;
73
+ closing = new Promise<T | undefined>((yes, no) => { complete = yes; fail = no; });
74
+ void closing.catch(() => {});
75
+ closed = true; controller.abort();
76
+ ports.signal.removeEventListener("abort", abort);
77
+ if (!settled) resolve(undefined);
78
+ void (async () => {
79
+ if (request) await request.catch(() => undefined);
80
+ if (failed) throw failure;
81
+ return value;
82
+ })().then(complete, fail);
83
+ return closing;
84
+ };
85
+ const abort = () => { void close().catch(() => {}); };
86
+ ports.signal.addEventListener("abort", abort, { once: true });
87
+ let commonSettled: Promise<void>;
88
+ if (ports.signal.aborted) { abort(); commonSettled = Promise.resolve(); }
89
+ else {
90
+ // Both late fulfillment and late rejection are consumed; neither can start HTTP after close.
91
+ commonSettled = Promise.resolve().then(() => ports.prepare(() => closed)).then(prepared => {
92
+ if (closed) return;
93
+ if (prepared === undefined) { done(undefined); return; }
94
+ let finish!: (value: T | undefined) => void, fail!: (error: unknown) => void;
95
+ request = new Promise<T | undefined>((yes, no) => { finish = yes; fail = no; });
96
+ void request.catch(() => {});
97
+ // Publish the owned-task slot before invoking its port, including reentrant close/abort.
98
+ try {
99
+ void ports.request(prepared, controller.signal, () => closed).then(answer => {
100
+ done(answer);
101
+ finish(answer);
102
+ }, error => {
103
+ refuse(error);
104
+ fail(error);
105
+ });
106
+ } catch (error) { refuse(error); fail(error); }
107
+ }, refuse).catch(refuse);
108
+ }
109
+ return { result, close, commonSettled };
110
+ }
111
+
112
+ export async function runHostJudge<T, O>(ports: {
113
+ parent: AbortSignal;
114
+ timeoutMs: number;
115
+ current(): void;
116
+ common(signal: AbortSignal): Promise<boolean>;
117
+ fallback(signal: AbortSignal): Promise<T | undefined>;
118
+ observe(signal: AbortSignal): ChoiceWindow<O> | undefined;
119
+ }): Promise<{ value: T | undefined; observation: O | undefined }> {
120
+ if (!Number.isSafeInteger(ports.timeoutMs) || ports.timeoutMs <= 0) throw new RangeError("invalid host judge deadline");
121
+ const controller = new AbortController();
122
+ let stop!: () => void;
123
+ const stopped = new Promise<{ kind: "stop" }>(resolve => { stop = () => { controller.abort(); resolve({ kind: "stop" }); }; });
124
+ const abort = () => stop();
125
+ ports.parent.addEventListener("abort", abort, { once: true });
126
+ const timer = setTimeout(stop, ports.timeoutMs);
127
+ let window: ChoiceWindow<O> | undefined;
128
+ try {
129
+ if (ports.parent.aborted) { stop(); return { value: undefined, observation: undefined }; }
130
+ ports.current();
131
+ const preparation = Promise.resolve().then(() => ports.common(controller.signal));
132
+ void preparation.catch(() => {});
133
+ const ready = await Promise.race([preparation.then(allowed => ({ kind: "ready" as const, allowed })), stopped]);
134
+ if (ready.kind === "stop" || !ready.allowed) return { value: undefined, observation: undefined };
135
+ ports.current();
136
+ // Invoke the fallback port first. House quota admission runs before its first await;
137
+ // this does not attest downstream provider/GPU generation order or a custom host's admission.
138
+ const fallback = ports.fallback(controller.signal).then(value => ({ kind: "fallback" as const, value }));
139
+ void fallback.catch(() => {});
140
+ window = ports.observe(controller.signal);
141
+ let observed = false;
142
+ for (;;) {
143
+ const event = await Promise.race([fallback, stopped, ...(!observed && window ? [window.result.then(value => ({ kind: "observation" as const, value }))] : [])]);
144
+ if (event.kind === "observation") { observed = true; continue; }
145
+ const observation = await window?.close();
146
+ if (event.kind === "stop") return { value: undefined, observation: undefined };
147
+ ports.current();
148
+ return { value: event.value, observation };
149
+ }
150
+ } finally {
151
+ clearTimeout(timer); ports.parent.removeEventListener("abort", abort);
152
+ try { await window?.close(); }
153
+ finally { controller.abort(); }
154
+ }
155
+ }
@@ -0,0 +1,102 @@
1
+ /** Host-owned semantic replies. They never select a model or grant admission. */
2
+ const REPLY_BYTES = 64 * 1024;
3
+ const FEEDBACK_BYTES = 4096;
4
+
5
+ export type AdvisorReply = { kind: "approve" } | { kind: "redo"; feedback: string };
6
+ export type EscalationCategory = "none" | "repetition" | "false_progress" | "drift" | "desperation" | "capability_gap";
7
+ export interface EscalationReply {
8
+ escalate: boolean;
9
+ category: EscalationCategory;
10
+ newEvidence: boolean;
11
+ reason: string;
12
+ }
13
+
14
+ function bounded(text: unknown): text is string {
15
+ return typeof text === "string" && text.length <= REPLY_BYTES && Buffer.byteLength(text, "utf8") <= REPLY_BYTES;
16
+ }
17
+
18
+ function feedback(text: string): string {
19
+ if (Buffer.byteLength(text, "utf8") <= FEEDBACK_BYTES) return text;
20
+ let bytes = 0, result = "";
21
+ for (const character of text) {
22
+ const size = Buffer.byteLength(character, "utf8");
23
+ if (bytes + size > FEEDBACK_BYTES) break;
24
+ result += character; bytes += size;
25
+ }
26
+ return result;
27
+ }
28
+
29
+ const DECORATIONS = ["**", "__", "*", "_", "`", "\"", "'"] as const;
30
+ const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
+
32
+ function stripLeadingDecoration(input: string): string {
33
+ let value = input.trimStart();
34
+ for (let count = 0; count < 8; count++) {
35
+ const quote = /^(?:>\s*)+/.exec(value), heading = /^#{1,6}[ \t]+/.exec(value), list = /^(?:[-+*]|[0-9]{1,3}[.)])[ \t]+/.exec(value);
36
+ const prefix = quote ?? heading ?? list;
37
+ if (!prefix) break;
38
+ value = value.slice(prefix[0].length).trimStart();
39
+ }
40
+ return value;
41
+ }
42
+
43
+ function advisorVerdict(input: string): { verdict: "APPROVE" | "REDO"; rest: string } | undefined {
44
+ let value = stripLeadingDecoration(input);
45
+ // A whole decorated verdict, e.g. **Verdict: REDO**: feedback.
46
+ for (const marker of DECORATIONS) {
47
+ const escaped = escapeRegExp(marker), whole = new RegExp(`^${escaped}\\s*Verdict\\s*:\\s*(APPROVE|REDO)\\s*${escaped}(?=$|[\\s:.-])`, "i").exec(value);
48
+ if (whole) return { verdict: whole[1]!.toUpperCase() as "APPROVE" | "REDO", rest: value.slice(whole[0].length) };
49
+ }
50
+ // Optional prefix may itself be bold, italic, underscored or inline-code decorated.
51
+ let prefix = /^Verdict\s*:\s*/i.exec(value);
52
+ if (prefix) value = value.slice(prefix[0].length);
53
+ else {
54
+ for (const marker of DECORATIONS) {
55
+ const escaped = escapeRegExp(marker), decorated = new RegExp(`^${escaped}\\s*Verdict\\s*:${escaped}\\s*`, "i").exec(value);
56
+ if (decorated) { value = value.slice(decorated[0].length); break; }
57
+ }
58
+ }
59
+ value = value.trimStart();
60
+ const marker = DECORATIONS.find(candidate => value.startsWith(candidate));
61
+ if (marker) value = value.slice(marker.length).trimStart();
62
+ const match = (marker ? /^(APPROVE|REDO)/i : /^(APPROVE|REDO)\b/i).exec(value);
63
+ if (!match) return undefined;
64
+ let rest = value.slice(match[0].length);
65
+ if (marker) {
66
+ rest = rest.trimStart();
67
+ if (!rest.startsWith(marker)) return undefined;
68
+ rest = rest.slice(marker.length);
69
+ }
70
+ return { verdict: match[1]!.toUpperCase() as "APPROVE" | "REDO", rest };
71
+ }
72
+
73
+ export function parseAdvisorReply(text: unknown): AdvisorReply | undefined {
74
+ if (!bounded(text)) return undefined;
75
+ const parsed = advisorVerdict(text);
76
+ if (!parsed) return undefined;
77
+ if (parsed.verdict === "APPROVE") return { kind: "approve" };
78
+ return { kind: "redo", feedback: feedback(parsed.rest.replace(/^\s*:\s*/, "").trim()) };
79
+ }
80
+
81
+ function category(value: unknown): value is EscalationCategory {
82
+ return value === "none" || value === "repetition" || value === "false_progress"
83
+ || value === "drift" || value === "desperation" || value === "capability_gap";
84
+ }
85
+
86
+ export function parseEscalationReply(text: unknown): EscalationReply | undefined {
87
+ if (!bounded(text)) return undefined;
88
+ let json = text;
89
+ const trimmed = text.trim();
90
+ if (trimmed.startsWith("```") || trimmed.endsWith("```")) {
91
+ const fence = /^```[ \t]*(?:json[ \t]*)?\r?\n([\s\S]*?)\r?\n```[ \t]*$/i.exec(trimmed);
92
+ if (!fence) return undefined;
93
+ json = fence[1]!;
94
+ }
95
+ let value: unknown;
96
+ try { value = JSON.parse(json); } catch { return undefined; }
97
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
98
+ const reply = value as Record<string, unknown>;
99
+ if (typeof reply.escalate !== "boolean" || !category(reply.category)
100
+ || typeof reply.new_evidence !== "boolean" || typeof reply.reason !== "string") return undefined;
101
+ return { escalate: reply.escalate, category: reply.category, newEvidence: reply.new_evidence, reason: feedback(reply.reason) };
102
+ }
@@ -1,7 +1,6 @@
1
- import { createHash, randomUUID } from "node:crypto";
1
+ import { randomUUID } from "node:crypto";
2
2
  import type { ChatMessage } from "../../omniroute/client.ts";
3
- import { extractToolSignals, fingerprint } from "./signals.ts";
4
- import { normalizeConversation } from "./normalize.ts";
3
+ import { projectOutcomeWithContext, priorFailureContext, type RetainedObservationFailure } from "./observation-signals.ts";
5
4
 
6
5
  export type RouteTurnOutcome = "completed" | "failed";
7
6
  export type RouteTestOutcome = "pass" | "fail" | "none";
@@ -22,7 +21,7 @@ export interface RouteLabelEvent {
22
21
  interface DecisionLabel {
23
22
  id: string;
24
23
  dimensions: RouteDimensions;
25
- baselineFingerprints: Set<string>;
24
+ baselineFingerprints: readonly RetainedObservationFailure[] | undefined;
26
25
  next?: RouteLabelEvent["next"];
27
26
  advisor?: RouteAdvisorOutcome;
28
27
  }
@@ -33,10 +32,7 @@ interface OpenTurn {
33
32
  closed: boolean;
34
33
  }
35
34
 
36
- const discreteSeverity = (value: number): 0 | 0.3 | 0.7 | 1 => value >= 1 ? 1 : value >= 0.7 ? 0.7 : value >= 0.3 ? 0.3 : 0;
37
- const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex");
38
-
39
- /** Holds only identifiers, numeric dimensions, enums, and hashed diagnostic fingerprints. */
35
+ /** Holds identifiers, dimensions, enums, hashes and bounded private operation names; no arguments/results. */
40
36
  export class RouteLabelTracker {
41
37
  private active: OpenTurn | undefined;
42
38
  private readonly turns = new Map<string, OpenTurn>();
@@ -57,7 +53,8 @@ export class RouteLabelTracker {
57
53
  addDecision(turn: OpenTurn | undefined, dimensions: RouteDimensions, priorMessages: ChatMessage[] = []): string | undefined {
58
54
  if (!turn || turn.closed || this.turns.get(turn.context.turn) !== turn) return undefined;
59
55
  const id = randomUUID();
60
- turn.decisions.set(id, { id, dimensions: { ...dimensions }, baselineFingerprints: batchFingerprints(priorMessages) });
56
+ const baseline = priorFailureContext(priorMessages);
57
+ turn.decisions.set(id, { id, dimensions: { ...dimensions }, baselineFingerprints: baseline });
61
58
  this.decisionOwners.set(id, turn);
62
59
  return id;
63
60
  }
@@ -72,13 +69,14 @@ export class RouteLabelTracker {
72
69
  const decision = turn.decisions.get(decisionId);
73
70
  if (!decision) return;
74
71
 
75
- const batch = normalizeConversation([assistant, ...tools]);
76
- const signals = extractToolSignals(batch, Math.max(3, tools.length));
77
- const severity = discreteSeverity(signals.severity);
78
- const tests = signals.testsPassed ? "pass" : testFailure(assistant, tools) ? "fail" : "none";
79
- const fingerprints = batchFingerprints([assistant, ...tools]);
80
- const repeat = [...fingerprints].some((fingerprint) => decision.baselineFingerprints.has(fingerprint));
81
- decision.next = { severity, tests, repeat };
72
+ const baseline = decision.baselineFingerprints;
73
+ if (!baseline) { delete decision.next; return; }
74
+ const projection = projectOutcomeWithContext(assistant, tools, baseline);
75
+ if (!projection) { delete decision.next; return; }
76
+ const outcome = projection.outcome, digests = new Set(baseline.map(entry => entry.digest));
77
+ const repeat = outcome.failureDigests.some(digest => digests.has(digest));
78
+ decision.baselineFingerprints = projection.retained;
79
+ decision.next = { severity: outcome.severity, tests: outcome.tests, repeat };
82
80
  }
83
81
 
84
82
  observeAdvisor(decisionId: string | undefined, verdict: RouteAdvisorOutcome): void {
@@ -111,57 +109,3 @@ export class RouteLabelTracker {
111
109
  turn.decisions.clear();
112
110
  }
113
111
  }
114
-
115
- function batchFingerprints(messages: ChatMessage[]): Set<string> {
116
- const conversation = normalizeConversation(messages);
117
- const result = new Set<string>();
118
- for (const message of conversation.messages) {
119
- for (const tool of message.toolResults) {
120
- if (!tool.content) continue;
121
- const call = conversation.messages.flatMap(item => item.toolCalls).find(item => item.id === tool.toolCallId);
122
- const matchedAssistant: ChatMessage = {
123
- role: "assistant", content: null,
124
- tool_calls: call ? [{ id: call.id, type: "function", function: { name: call.name, arguments: safeJson(call.arguments) } }] : [],
125
- };
126
- const signals = extractToolSignals(normalizeConversation([matchedAssistant, {
127
- role: "tool", tool_call_id: tool.toolCallId, content: tool.content, ...(tool.isError ? { is_error: true } : {}),
128
- }]), 3);
129
- if (signals.severity === 0) continue;
130
- const value = fingerprint(tool.content, tool.isError === true);
131
- if (value !== undefined) result.add(sha256(value));
132
- }
133
- }
134
- return result;
135
- }
136
-
137
- function testFailure(assistant: ChatMessage, tools: ChatMessage[]): boolean {
138
- const conversation = normalizeConversation([assistant, ...tools]);
139
- const calls = conversation.messages.flatMap(message => message.toolCalls);
140
- const results = conversation.messages.flatMap(message => message.toolResults);
141
- for (const result of results) {
142
- const call = calls.find(item => item.id === result.toolCallId);
143
- if (!call) continue;
144
- const args = safeJson(call.arguments);
145
- const isTestCall = /\b(test|tests|spec|specs|pytest|vitest|jest|cargo test|go test)\b/iu.test(call.name)
146
- || /\b(bun test|pytest|vitest|jest|cargo test|go test|npm test|pnpm test|yarn test)\b/iu.test(args);
147
- if (!isTestCall && !/\btests?\b/iu.test(result.content)) continue;
148
- const matchedAssistant: ChatMessage = {
149
- role: "assistant", content: null,
150
- tool_calls: [{ id: call.id, type: "function", function: { name: call.name, arguments: args } }],
151
- };
152
- const outcomeSignals = extractToolSignals(normalizeConversation([matchedAssistant, {
153
- role: "tool", tool_call_id: result.toolCallId, content: result.content, ...(result.isError ? { is_error: true } : {}),
154
- }]), 3);
155
- if (!result.isError && outcomeSignals.readCount > 0) continue;
156
- const severity = outcomeSignals.severity;
157
- const numericFailures = /\b[1-9]\d*\s+(?:tests?\s+)?(?:failed|failures|errors?)\b/iu.test(result.content)
158
- || /\b(?:failed|failures|errors?)\b[^\n\d]{0,20}[1-9]\d*/iu.test(result.content);
159
- if (numericFailures || severity > 0) return true;
160
- }
161
- return false;
162
- }
163
-
164
- function safeJson(value: unknown): string {
165
- try { return typeof value === "string" ? value : JSON.stringify(value) ?? ""; }
166
- catch { return ""; }
167
- }
@@ -0,0 +1,250 @@
1
+ import { createHash } from "node:crypto";
2
+ import { types } from "node:util";
3
+ import { captureJudgeConversation, type JudgeMessage } from "./conversation-view.ts";
4
+ import { captureStageInput, estimateStageInputTokens } from "./stage-input.ts";
5
+ import { diagnoseStageResult, type StageDiagnostic } from "./stage-diagnostics.ts";
6
+
7
+ export interface ToolObservation {
8
+ name: string;
9
+ command?: string;
10
+ resultText?: string;
11
+ isError?: boolean;
12
+ source?: string;
13
+ }
14
+ export interface ObservationOutcome {
15
+ severity: 0 | 0.3 | 0.7 | 1;
16
+ tests: "pass" | "fail" | "none";
17
+ failureDigests: readonly string[];
18
+ }
19
+ type Severity = ObservationOutcome["severity"];
20
+ export interface RetainedObservationFailure { digest: string; operation?: string | null }
21
+ interface Failure { digest: string; test: boolean; severity: Severity; observation: number; operation: string | null }
22
+ interface ResultFacts {
23
+ operation: string | null;
24
+ explicitCommand: boolean;
25
+ readOnly: boolean;
26
+ nativeError: boolean;
27
+ assertionDiagnostic: boolean;
28
+ testInvocation: boolean;
29
+ testMention: boolean;
30
+ diagnostic: StageDiagnostic;
31
+ text: string;
32
+ }
33
+ const WIRE_BYTES = 2_000_000;
34
+ const OPERATION_BYTES = 256;
35
+ const unavailable = Symbol("observation unavailable");
36
+ const digest = (value: string): string => createHash("sha256").update(value).digest("hex");
37
+ const testName = /\b(?:test|tests|spec|specs|pytest|vitest|jest|cargo test|go test)\b|^(?:run_tests|run_test|unittest)$/iu;
38
+ // Local lexical evidence only, never an executable/exit-status attestation.
39
+ const testCommand = /\b(?:bun test|pytest|vitest|jest|cargo test|go test|npm test|pnpm test|yarn test)\b|(?:^|[\s;&|])(?:(?:bun|npm|pnpm|yarn)\s+(?:run\s+)?test(?:$|[\s:])|python(?:3(?:\.\d+)?)?\s+-m\s+(?:pytest|unittest)\b|(?:make|just)\s+test\b)/iu;
40
+
41
+ function own(value: object, key: string): unknown {
42
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
43
+ if (descriptor && !("value" in descriptor)) throw unavailable;
44
+ return descriptor?.value;
45
+ }
46
+ function plain(value: unknown): value is Record<string, unknown> {
47
+ return !!value && typeof value === "object" && !types.isProxy(value) && !Array.isArray(value)
48
+ && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
49
+ }
50
+ function dataArray(value: unknown): value is unknown[] {
51
+ return !!value && typeof value === "object" && !types.isProxy(value) && Array.isArray(value)
52
+ && Object.getPrototypeOf(value) === Array.prototype;
53
+ }
54
+ function text(value: unknown): value is string {
55
+ return typeof value === "string" && value.length <= WIRE_BYTES && Buffer.byteLength(value) <= WIRE_BYTES;
56
+ }
57
+ function command(argumentsText: string): { value?: string; explicit: boolean } {
58
+ try {
59
+ const args: unknown = JSON.parse(argumentsText);
60
+ if (!plain(args)) return { explicit: true };
61
+ const value = own(args, "command");
62
+ return { explicit: Object.hasOwn(args, "command"), ...(typeof value === "string" ? { value } : {}) };
63
+ } catch { return { explicit: true }; }
64
+ }
65
+ function facts(name: string, value: string, nativeError: boolean, invocation?: string, readFamily = false,
66
+ explicitCommand = invocation !== undefined): ResultFacts {
67
+ const readOnly = readFamily || /^(?:read|read_file|readfile|glob|grep|search|list|ls|lookup)(?:_|$)/i.test(name)
68
+ || name.toLowerCase() === "text_editor" && invocation === "view";
69
+ return {
70
+ operation: name && Buffer.byteLength(name) <= OPERATION_BYTES ? name : null, explicitCommand,
71
+ readOnly, nativeError, text: value,
72
+ assertionDiagnostic: /\bassertion(?:error| failed)\b/i.test(value),
73
+ testInvocation: testName.test(name) || invocation !== undefined && testCommand.test(invocation),
74
+ testMention: /\btests?\b|\bassertion(?:error| failed)\b/i.test(value),
75
+ diagnostic: diagnoseStageResult({ text: value, error: nativeError, family: readOnly ? "read" : "other", associated: true }),
76
+ };
77
+ }
78
+
79
+ /** Inspect the entire validated batch; the recent R1 window supplies no completeness claim. */
80
+ function associatedResults(messages: readonly JudgeMessage[]): ResultFacts[] | undefined {
81
+ let pending: { calls: Map<string, NonNullable<JudgeMessage["tool_calls"]>[number]>; seen: Set<string> } | undefined;
82
+ const results: ResultFacts[] = [];
83
+ const complete = (): boolean => !pending || pending.calls.size === pending.seen.size;
84
+ for (const message of messages) {
85
+ if (message.role === "assistant") {
86
+ if (!complete()) return undefined;
87
+ pending = { calls: new Map(), seen: new Set() };
88
+ for (const call of message.tool_calls ?? []) {
89
+ if (!call.id || pending.calls.has(call.id)) return undefined;
90
+ pending.calls.set(call.id, call);
91
+ }
92
+ } else if (message.role === "tool") {
93
+ const id = message.tool_call_id;
94
+ if (!id || !pending || pending.seen.has(id) || typeof message.content !== "string") return undefined;
95
+ const call = pending.calls.get(id);
96
+ if (!call) return undefined;
97
+ // Reuse the owned R1 identity/family oracle on one already-associated pair.
98
+ // Use the FULL original result for diagnostics, not the oracle's bounded text projection.
99
+ const pair = captureStageInput([{ role: "assistant", content: null, tool_calls: [call] }, message]);
100
+ const result = pair?.results[0];
101
+ if (!result?.associated) return undefined;
102
+ pending.seen.add(id);
103
+ const invocation = command(call.function.arguments);
104
+ results.push(facts(call.function.name, message.content, message.is_error === true || message.isError === true,
105
+ invocation.value, result.family === "read", invocation.explicit));
106
+ } else if (message.role === "user") {
107
+ if (!complete()) return undefined;
108
+ pending = undefined;
109
+ }
110
+ }
111
+ return complete() ? results : undefined;
112
+ }
113
+
114
+ /** Separate a reported operation failure from a test-count report in the same result. */
115
+ function otherReportedDiagnostic(value: string): StageDiagnostic {
116
+ const remainder = value
117
+ .replace(/\b\d+\s+(?:tests?\s+)?(?:fail(?:ed|ures)?|pass(?:ed)?)\b/gi, "")
118
+ .replace(/\btests?\s+(?:failed|passed|pass|failures?)\b/gi, "");
119
+ return diagnoseStageResult({ text: remainder, error: false, family: "other", associated: true });
120
+ }
121
+ function fold(results: readonly ResultFacts[], prior: readonly RetainedObservationFailure[] = []): {
122
+ outcome: ObservationOutcome; failures: Failure[]; retained: RetainedObservationFailure[];
123
+ } {
124
+ let failures: Failure[] = [], passed = false;
125
+ let retained = [...prior];
126
+ for (const [observation, result] of results.entries()) {
127
+ if (result.readOnly && !result.nativeError) continue;
128
+ const diagnostic = result.diagnostic, context = result.testInvocation || result.testMention;
129
+ const inherited = !context && !result.explicitCommand && result.operation !== null
130
+ && (retained.some(failure => failure.operation === result.operation)
131
+ || failures.some(failure => failure.test && failure.operation === result.operation));
132
+ const genuinePass = (context || inherited) && !result.nativeError && diagnostic.fault === "none" && diagnostic.test === "pass";
133
+ if (genuinePass) {
134
+ failures = failures.filter(failure => !failure.test || inherited && failure.operation !== result.operation);
135
+ retained = retained.filter(failure => failure.operation === undefined || inherited && failure.operation !== result.operation);
136
+ passed = true;
137
+ }
138
+ if (diagnostic.fault === "none" || diagnostic.fingerprint === undefined) continue;
139
+ const qualifiedTest = context;
140
+ const stronger = result.nativeError || result.assertionDiagnostic || diagnostic.fault === "exception";
141
+ const independent = diagnostic.fault === "reported" && !stronger && diagnostic.test === "fail"
142
+ ? otherReportedDiagnostic(result.text) : undefined;
143
+ const testOnly = qualifiedTest && diagnostic.test === "fail" && independent?.fault === "none";
144
+ const severity: Severity = diagnostic.fault === "critical" ? 1 : stronger ? 0.7 : testOnly ? 0 : 0.3;
145
+ const fingerprint = digest(diagnostic.fingerprint);
146
+ failures.push({ digest: fingerprint, test: qualifiedTest, severity, observation, operation: result.operation });
147
+ if (qualifiedTest && independent && independent.fault !== "none") {
148
+ failures.push({ digest: fingerprint, test: false, severity: 0.3, observation, operation: result.operation });
149
+ }
150
+ }
151
+ const severity = failures.reduce<Severity>((prior, failure) => failure.severity > prior ? failure.severity : prior, 0);
152
+ return { outcome: { severity, tests: failures.some(failure => failure.test) ? "fail" : passed ? "pass" : "none",
153
+ failureDigests: [...new Set(failures.map(failure => failure.digest))] }, failures, retained };
154
+ }
155
+
156
+ export function projectOutcomeBatch(assistant: unknown, tools: readonly unknown[]): ObservationOutcome | undefined {
157
+ return projectOutcomeWithContext(assistant, tools)?.outcome;
158
+ }
159
+
160
+ /** Private tracker metadata, never a message/event field or retained result body. */
161
+ export function projectOutcomeWithContext(assistant: unknown, tools: readonly unknown[], prior: readonly RetainedObservationFailure[] = []): {
162
+ outcome: ObservationOutcome; retained: readonly RetainedObservationFailure[];
163
+ } | undefined {
164
+ try {
165
+ if (!dataArray(tools) || tools.length > WIRE_BYTES / 20 || !dataArray(prior) || prior.length > WIRE_BYTES / 20) return undefined;
166
+ for (const entry of prior) {
167
+ if (!plain(entry) || Object.keys(entry).some(key => key !== "digest" && key !== "operation")
168
+ || typeof own(entry, "digest") !== "string" || !/^[a-f0-9]{64}$/.test(own(entry, "digest") as string)) return undefined;
169
+ if (Object.hasOwn(entry, "operation")) {
170
+ const name = own(entry, "operation");
171
+ if (name !== null && (typeof name !== "string" || !name || Buffer.byteLength(name) > OPERATION_BYTES)) return undefined;
172
+ }
173
+ }
174
+ const source: unknown[] = [assistant];
175
+ for (let index = 0; index < tools.length; index++) source.push(own(tools, String(index)));
176
+ const conversation = captureJudgeConversation(source);
177
+ if (!conversation || conversation.messages.length !== source.length || conversation.messages[0]?.role !== "assistant"
178
+ || conversation.messages.slice(1).some(message => message.role !== "tool")) return undefined;
179
+ const results = associatedResults(conversation.messages);
180
+ if (!results) return undefined;
181
+ const projected = fold(results, prior);
182
+ return { outcome: projected.outcome, retained: projected.retained };
183
+ } catch { return undefined; }
184
+ }
185
+
186
+ export function priorFailureDigests(messages: readonly unknown[]): readonly string[] | undefined {
187
+ const entries = priorFailureContext(messages);
188
+ return entries && [...new Set(entries.map(entry => entry.digest))];
189
+ }
190
+
191
+ export function priorFailureContext(messages: readonly unknown[]): readonly RetainedObservationFailure[] | undefined {
192
+ const conversation = captureJudgeConversation(messages);
193
+ if (!conversation) return undefined;
194
+ const results = associatedResults(conversation.messages);
195
+ if (!results) return undefined;
196
+ const retained = new Map<string, RetainedObservationFailure>();
197
+ for (const failure of fold(results).failures) {
198
+ const entry = { digest: failure.digest, ...(failure.test ? { operation: failure.operation } : {}) };
199
+ retained.set(`${entry.digest}:${failure.test ? JSON.stringify(failure.operation) : "unqualified"}`, entry);
200
+ if (retained.size > WIRE_BYTES / 20) return undefined;
201
+ }
202
+ return [...retained.values()];
203
+ }
204
+
205
+ /** Only the digest escapes; R1's diagnostic/fingerprint text remains transient. */
206
+ export function failureFingerprint(value: string, isError: boolean): string | undefined {
207
+ if (!text(value) || typeof isError !== "boolean") return undefined;
208
+ const diagnostic = diagnoseStageResult({ text: value, error: isError, family: "other", associated: true });
209
+ return diagnostic.fingerprint === undefined ? undefined : digest(diagnostic.fingerprint);
210
+ }
211
+
212
+ export function repeatedObservationFailure(observations: readonly ToolObservation[]): boolean | undefined {
213
+ try {
214
+ if (!dataArray(observations) || observations.length > WIRE_BYTES / 20) return undefined;
215
+ const copied: Record<string, unknown>[] = [];
216
+ let remaining = WIRE_BYTES;
217
+ const charge = (bytes: number): void => { remaining -= bytes; if (remaining < 0) throw unavailable; };
218
+ const inspectedText = (value: unknown): value is string => {
219
+ if (typeof value !== "string" || value.length > WIRE_BYTES) return false;
220
+ charge(Buffer.byteLength(value)); return true;
221
+ };
222
+ // Lower-bound aggregate admission precedes every diagnostic/fingerprint operation.
223
+ for (let index = 0; index < observations.length; index++) {
224
+ charge(20);
225
+ const item = own(observations, String(index));
226
+ if (!plain(item)) return undefined;
227
+ const name = own(item, "name"), resultText = own(item, "resultText"), invocation = own(item, "command"),
228
+ isError = own(item, "isError"), source = own(item, "source");
229
+ if (!inspectedText(name) || !name || resultText !== undefined && !inspectedText(resultText) || invocation !== undefined && !inspectedText(invocation)
230
+ || source !== undefined && !inspectedText(source) || isError !== undefined && typeof isError !== "boolean") return undefined;
231
+ if (["resultText", "command", "isError", "source"].some(key => Object.hasOwn(item, key) && own(item, key) === undefined)) return undefined;
232
+ copied.push({ role: "tool", content: resultText ?? "", name, ...(invocation === undefined ? {} : { command: invocation }),
233
+ ...(source === undefined ? {} : { source }), ...(isError === undefined ? {} : { isError }) });
234
+ }
235
+ if (estimateStageInputTokens(copied) === undefined) return undefined;
236
+ const results = copied.map(item => facts(item.name as string, item.content as string,
237
+ item.isError === true, item.command as string | undefined));
238
+ const counts = new Map<string, number>();
239
+ const seen = new Set<string>();
240
+ for (const failure of fold(results).failures) {
241
+ const occurrence = `${failure.observation}:${failure.digest}`;
242
+ if (seen.has(occurrence)) continue;
243
+ seen.add(occurrence);
244
+ const count = (counts.get(failure.digest) ?? 0) + 1;
245
+ if (count > 1) return true;
246
+ counts.set(failure.digest, count);
247
+ }
248
+ return false;
249
+ } catch { return undefined; }
250
+ }
@@ -0,0 +1,27 @@
1
+ import { diagnoseStageResult } from "./stage-diagnostics.ts";
2
+ import type { RouteConversationView } from "./conversation-view.ts";
3
+ import { ScopeStore, type ScopeStoreOptions } from "./turn-state.ts";
4
+
5
+ export interface PlanPhaseSnapshot {
6
+ phase: "planning" | "executing";
7
+ fallbackTier: "efficient" | "capable";
8
+ addPlanningInstruction: boolean;
9
+ }
10
+
11
+ /** Deterministic host phase fallback; optional model/effort proposals do not apply here. */
12
+ export class PlanPhase {
13
+ private readonly executing: ScopeStore<boolean>;
14
+ constructor(options: ScopeStoreOptions = {}) { this.executing = new ScopeStore(options); }
15
+
16
+ observe(view: RouteConversationView | undefined, scope: string): PlanPhaseSnapshot {
17
+ let executing = this.executing.get(scope) === true;
18
+ if (!executing && view?.results.some(({ input, sourceTextComplete }) => sourceTextComplete
19
+ && input.associated && input.family === "mutation" && !input.error
20
+ && diagnoseStageResult(input).fault === "none"
21
+ && !/\b(?:denied|refused|cancell?ed|not permitted)\b/i.test(input.text))) {
22
+ executing = true;
23
+ this.executing.set(scope, true);
24
+ }
25
+ return { phase: executing ? "executing" : "planning", fallbackTier: executing ? "efficient" : "capable", addPlanningInstruction: !executing };
26
+ }
27
+ }