@staix/agent-hub 0.36.0 → 0.38.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 (121) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +6 -2
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +13 -3
  5. package/docs/agent-notes/daemon.md +4 -4
  6. package/docs/agent-notes/local-worker.md +1 -0
  7. package/docs/agent-notes/models.md +2 -1
  8. package/docs/agent-notes/tasks.md +1 -1
  9. package/docs/agent-notes/tests.md +1 -2
  10. package/docs/contracts/companion-cli-v1.json +70 -0
  11. package/docs/design/adapters.md +43 -2
  12. package/docs/design/agent-hub-architecture.md +9 -1
  13. package/docs/design/guidance-probes.md +1167 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +12 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +123 -151
  19. package/docs/profiles.md +1 -1
  20. package/docs/quickstart.md +15 -3
  21. package/docs/research.md +1 -1
  22. package/docs/sdlc.md +5 -3
  23. package/docs/security.md +25 -1
  24. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  25. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  26. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  27. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  28. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  29. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  30. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  31. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  32. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  33. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  34. package/docs/verified.json +25 -25
  35. package/package.json +3 -4
  36. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  37. package/plugins/agent-hub/kimi-hook.js +2403 -1444
  38. package/plugins/agent-hub/server.js +2480 -1509
  39. package/src/adapters/channel-peer.ts +7 -1
  40. package/src/adapters/claude-channel.ts +2 -1
  41. package/src/adapters/compat.ts +1 -1
  42. package/src/adapters/local-probe.ts +233 -0
  43. package/src/adapters/local-worker.ts +232 -21
  44. package/src/cli/console-state.ts +25 -6
  45. package/src/cli/console-versions.ts +99 -0
  46. package/src/cli/console.ts +13 -1
  47. package/src/cli/help.ts +2 -1
  48. package/src/cli/init.ts +3 -1
  49. package/src/cli/install-paths.ts +7 -2
  50. package/src/cli/main.ts +78 -7
  51. package/src/cli/output.ts +8 -4
  52. package/src/cli/runtime-version-warning.ts +2 -2
  53. package/src/cli/sdlc-output.ts +9 -5
  54. package/src/cli/upgrade-runtime.ts +1 -1
  55. package/src/hub/bus.ts +2 -2
  56. package/src/hub/config-apply.ts +4 -2
  57. package/src/hub/config-trust.ts +6 -1
  58. package/src/hub/control-client.ts +5 -2
  59. package/src/hub/daemon.ts +195 -13
  60. package/src/hub/envelope.ts +6 -1
  61. package/src/hub/events.ts +3 -2
  62. package/src/hub/guidance-probe-store.ts +1044 -0
  63. package/src/hub/guidance-probes.ts +692 -0
  64. package/src/hub/inference.ts +18 -5
  65. package/src/hub/manager.ts +24 -1
  66. package/src/hub/operational-authority.ts +14 -1
  67. package/src/hub/peers.ts +5 -0
  68. package/src/hub/person-command.ts +25 -0
  69. package/src/hub/ports.ts +1 -1
  70. package/src/hub/progress.ts +23 -16
  71. package/src/hub/report.ts +2 -0
  72. package/src/hub/research.ts +1 -0
  73. package/src/hub/restart.ts +7 -0
  74. package/src/hub/sdlc-release-authorization.ts +139 -17
  75. package/src/hub/sdlc-release-policy.ts +100 -0
  76. package/src/hub/sdlc-release.ts +59 -7
  77. package/src/hub/supervision.ts +3 -2
  78. package/src/hub/tasks.ts +363 -7
  79. package/src/local/probe-errors.ts +28 -0
  80. package/src/local/probe-sandbox.ts +224 -0
  81. package/src/local/probe-types.ts +110 -0
  82. package/src/local/probe-workspace.ts +426 -0
  83. package/src/local/sandbox.ts +71 -2
  84. package/src/local/tools.ts +135 -9
  85. package/src/models/route/advisor-trigger.ts +88 -0
  86. package/src/models/route/config.ts +21 -17
  87. package/src/models/route/conversation-view.ts +179 -0
  88. package/src/models/route/decision-evidence.ts +1 -1
  89. package/src/models/route/decision.ts +114 -19
  90. package/src/models/route/escalation-control.ts +30 -0
  91. package/src/models/route/hub-prompts.ts +97 -0
  92. package/src/models/route/judge-choice.ts +155 -0
  93. package/src/models/route/judge-replies.ts +102 -0
  94. package/src/models/route/labels.ts +14 -70
  95. package/src/models/route/observation-signals.ts +250 -0
  96. package/src/models/route/plan-execute-choice.ts +27 -0
  97. package/src/models/route/relay-selector.ts +2 -2
  98. package/src/models/route/runtime.ts +115 -52
  99. package/src/models/route/turn-state.ts +77 -0
  100. package/src/omniroute/client.ts +3 -0
  101. package/src/ui/guidance-panel.ts +34 -2
  102. package/src/ui/guidance-view.ts +33 -0
  103. package/src/ui/plugin.ts +80 -23
  104. package/src/version.ts +4 -0
  105. package/templates/AGENTS.block.md +14 -14
  106. package/templates/adec/README.md +32 -0
  107. package/templates/adec/ahub.plan-execute.json +23 -0
  108. package/templates/adec/ahub.stage.json +23 -0
  109. package/templates/profiles/general.json +1 -1
  110. package/templates/profiles/research.json +1 -1
  111. package/templates/profiles/writing.json +1 -1
  112. package/LICENSES/Apache-2.0.txt +0 -204
  113. package/src/models/route/advisor.ts +0 -102
  114. package/src/models/route/escalation.ts +0 -82
  115. package/src/models/route/judge.ts +0 -23
  116. package/src/models/route/normalize.ts +0 -103
  117. package/src/models/route/plan-execute.ts +0 -52
  118. package/src/models/route/prompts.ts +0 -8
  119. package/src/models/route/signals.ts +0 -247
  120. package/src/models/route/state.ts +0 -54
  121. package/src/models/route/text.ts +0 -61
@@ -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
+ }
@@ -2,7 +2,7 @@ import type { ModelBackend, ModelRelayOptions, RelayRequest } from "../relay.ts"
2
2
  import { captureStageInput } from "./stage-input.ts";
3
3
  import { buildStageEvidence } from "./stage-evidence.ts";
4
4
  import { selectFallbackStage, planStageSwitch, type FallbackStageState as StageState, type StageSwitchTrace as SwitchTrace, type StageTier as Tier } from "./stage-fallback.ts";
5
- import { SessionState } from "./state.ts";
5
+ import { ScopeStore } from "./turn-state.ts";
6
6
 
7
7
  type RelaySelectorOptions = Pick<ModelRelayOptions, "mlx" | "selectBackend" | "routeSessionKey" | "allowedDGXmodels" | "staySwitch"> & { dgxMaxInputTokens: number };
8
8
  type RouteSource = "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin";
@@ -18,7 +18,7 @@ export interface AutoChoice { backend: ModelBackend; route: RelayRouteEvent; mov
18
18
 
19
19
  /** Stage selection for the relay's virtual `hub/auto` model. */
20
20
  export class AutoRouteSelector {
21
- private readonly states = new SessionState<AutoState>(512, 60 * 60_000);
21
+ private readonly states = new ScopeStore<AutoState>({ maxEntries: 512, ttlMs: 60 * 60_000 });
22
22
 
23
23
  constructor(
24
24
  private readonly options: RelaySelectorOptions,