@staix/agent-hub 0.35.0 → 0.36.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 (104) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +21 -4
  3. package/docs/agent-notes/README.md +60 -0
  4. package/docs/agent-notes/adapters.md +5 -2
  5. package/docs/agent-notes/bus.md +1 -0
  6. package/docs/agent-notes/daemon.md +5 -4
  7. package/docs/agent-notes/models.md +4 -3
  8. package/docs/agent-notes/tasks.md +8 -1
  9. package/docs/agent-notes/tests.md +1 -0
  10. package/docs/design/adapters.md +72 -0
  11. package/docs/design/agent-hub-architecture.md +1 -1
  12. package/docs/design/bus.md +8 -0
  13. package/docs/design/execution-reference.md +171 -11
  14. package/docs/design/guidance-experiments.md +438 -0
  15. package/docs/design/model-routes.md +628 -0
  16. package/docs/design/supervision.md +121 -0
  17. package/docs/design/task-board.md +111 -0
  18. package/docs/dogfood.md +15 -4
  19. package/docs/operations.md +291 -22
  20. package/docs/profiles.md +2 -2
  21. package/docs/quickstart.md +106 -1
  22. package/docs/research.md +4 -2
  23. package/docs/sdlc.md +108 -4
  24. package/docs/security.md +67 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +5 -4
  26. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  27. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  28. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  29. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  30. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  31. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  32. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  33. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  34. package/docs/verified.json +27 -27
  35. package/package.json +1 -1
  36. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  37. package/plugins/agent-hub/kimi-hook.js +1201 -368
  38. package/plugins/agent-hub/server.js +1682 -431
  39. package/src/adapters/claude-channel.ts +7 -4
  40. package/src/adapters/compat.ts +10 -10
  41. package/src/adapters/local-worker.ts +1 -1
  42. package/src/adapters/qwen-dual.ts +324 -44
  43. package/src/cli/guidance.ts +67 -0
  44. package/src/cli/help.ts +10 -3
  45. package/src/cli/identity.ts +10 -3
  46. package/src/cli/init-prompt.ts +15 -2
  47. package/src/cli/init-required-checks.ts +122 -0
  48. package/src/cli/init-settings.ts +10 -4
  49. package/src/cli/init.ts +39 -3
  50. package/src/cli/lineage.ts +78 -0
  51. package/src/cli/main.ts +111 -10
  52. package/src/cli/setup-research.ts +10 -0
  53. package/src/hub/autonomy-defaults.ts +20 -9
  54. package/src/hub/board.ts +346 -4
  55. package/src/hub/build-entry.ts +11 -0
  56. package/src/hub/bus.ts +12 -0
  57. package/src/hub/ci-watch.ts +4 -4
  58. package/src/hub/config-apply.ts +2 -1
  59. package/src/hub/config-trust.ts +1 -0
  60. package/src/hub/control-client.ts +1 -1
  61. package/src/hub/daemon.ts +342 -20
  62. package/src/hub/delivery-hints.ts +4 -2
  63. package/src/hub/delivery-journal.ts +50 -2
  64. package/src/hub/delivery-public.ts +51 -0
  65. package/src/hub/dogfood-profile.ts +8 -4
  66. package/src/hub/execution-lineage-owner.ts +272 -0
  67. package/src/hub/execution-lineage.ts +52 -8
  68. package/src/hub/execution-links.ts +85 -0
  69. package/src/hub/guidance-variants.ts +398 -0
  70. package/src/hub/handoff.ts +1 -0
  71. package/src/hub/hub-tools.ts +43 -2
  72. package/src/hub/manager.ts +44 -2
  73. package/src/hub/memory-policy.ts +2 -2
  74. package/src/hub/peers.ts +1 -1
  75. package/src/hub/planning.ts +1 -1
  76. package/src/hub/progress.ts +24 -7
  77. package/src/hub/restart.ts +13 -0
  78. package/src/hub/roles.ts +26 -0
  79. package/src/hub/routing.ts +4 -1
  80. package/src/hub/sdlc-merge.ts +39 -1
  81. package/src/hub/sdlc-release.ts +1 -1
  82. package/src/hub/sdlc.ts +62 -11
  83. package/src/hub/settings.ts +2 -0
  84. package/src/hub/supervision-proposals.ts +405 -0
  85. package/src/hub/supervision-rules.ts +388 -0
  86. package/src/hub/supervision.ts +2 -0
  87. package/src/hub/task-approval.ts +2 -2
  88. package/src/hub/task-repository.ts +5 -0
  89. package/src/hub/tasks.ts +603 -50
  90. package/src/memory/capture.ts +2 -2
  91. package/src/models/relay.ts +9 -2
  92. package/src/models/route/config.ts +27 -0
  93. package/src/models/route/decision.ts +87 -15
  94. package/src/models/route/relay-selector.ts +8 -7
  95. package/src/models/route/runtime.ts +22 -16
  96. package/src/models/route/stage-diagnostics.ts +22 -0
  97. package/src/models/route/stage-evidence.ts +55 -0
  98. package/src/models/route/stage-fallback.ts +58 -0
  99. package/src/models/route/stage-input.ts +155 -0
  100. package/src/models/route/stage.ts +5 -147
  101. package/src/ui/guidance-panel.ts +156 -0
  102. package/src/ui/guidance-view.ts +43 -0
  103. package/src/ui/lineage-view.ts +34 -0
  104. package/src/ui/plugin.ts +71 -7
@@ -0,0 +1,155 @@
1
+ /** Local bounded observation, deliberately separate from the whole forwarded wire. */
2
+ export type StageTurn = "user" | "tool_result" | "compaction" | "other";
3
+ export interface StageResultInput { text: string; error: boolean; family: "read" | "mutation" | "execution" | "other"; associated: boolean; assistantTurn?: number }
4
+ export interface StageInput { turn: StageTurn; incomplete: boolean; assistantTurns: number; results: StageResultInput[] }
5
+ const MESSAGE_LIMIT = 64, RESULT_LIMIT = 16, CALL_LIMIT = 32, PART_LIMIT = 32;
6
+ const TEXT_BYTES = 64 * 1024, ID_BYTES = 128, NAME_BYTES = 64;
7
+
8
+ /** Accessors are not part of a transport record; capture never invokes them. */
9
+ function field(value: unknown, key: string): unknown {
10
+ if (!value || typeof value !== "object") return undefined;
11
+ return Object.getOwnPropertyDescriptor(value, key)?.value;
12
+ }
13
+ function boundedString(value: unknown, bytes: number): string | undefined {
14
+ return typeof value === "string" && value.length <= bytes && Buffer.byteLength(value) <= bytes ? value : undefined;
15
+ }
16
+ function family(name: string | undefined): StageResultInput["family"] {
17
+ if (!name) return "other";
18
+ if (/^(bash|exec_command)$/i.test(name)) return "execution";
19
+ if (/^(read|read_file|readfile|glob|grep|search|list|ls|lookup)(_|$)/i.test(name)) return "read";
20
+ if (/^(write|write_file|edit|apply_patch|patch|delete|create|replace)(_|$)/i.test(name)) return "mutation";
21
+ return "other";
22
+ }
23
+
24
+ export function captureStageInput(source: unknown): StageInput | undefined {
25
+ try {
26
+ const messages = Array.isArray(source) ? source : field(source, "messages");
27
+ if (!Array.isArray(messages)) return undefined;
28
+ let incomplete = messages.length > MESSAGE_LIMIT, bytes = 0, parts = 0, inspectedCalls = 0;
29
+ const text = (value: unknown): string => {
30
+ if (typeof value === "string") {
31
+ if (value.length > TEXT_BYTES || bytes + Buffer.byteLength(value) > TEXT_BYTES) { incomplete = true; return ""; }
32
+ bytes += Buffer.byteLength(value); return value;
33
+ }
34
+ if (!Array.isArray(value)) return "";
35
+ const kept: string[] = [];
36
+ const available = PART_LIMIT - parts;
37
+ for (let index = 0; index < value.length && parts < PART_LIMIT; index++, parts++) {
38
+ const part = field(value, String(index));
39
+ if (field(part, "type") === "text" && typeof field(part, "text") === "string") kept.push(text(field(part, "text")));
40
+ }
41
+ if (value.length > available) incomplete = true;
42
+ return kept.join("\n");
43
+ };
44
+ const calls = new Map<string, { name?: string; index: number } | null>();
45
+ const observations: { id?: string; text: string; error: boolean; index: number }[] = [];
46
+ let turn: StageTurn = "other", assistantTurns = 0, turnCaptured = false;
47
+ for (let index = messages.length - 1; index >= Math.max(0, messages.length - MESSAGE_LIMIT); index--) {
48
+ const message = field(messages, String(index)), role = field(message, "role");
49
+ if (role === "system" || role === "developer") continue;
50
+ if (role !== "user" && role !== "assistant" && role !== "tool") {
51
+ incomplete = true;
52
+ if (!turnCaptured) { turnCaptured = true; turn = "other"; }
53
+ continue;
54
+ }
55
+ if (!turnCaptured) {
56
+ turnCaptured = true;
57
+ turn = role === "tool" ? "tool_result" : role === "user" ? "user" : "other";
58
+ if (role === "user") {
59
+ const latest = text(field(message, "content"));
60
+ if (/\b(compact(?:ed|ion)?|context summary|conversation summary)\b|continued[\s\S]*(?:previous conversation|ran out of context)/i.test(latest)) turn = "compaction";
61
+ }
62
+ }
63
+ if (role === "assistant") {
64
+ assistantTurns++;
65
+ const entries = field(message, "tool_calls");
66
+ if (Array.isArray(entries)) {
67
+ const availableCalls = CALL_LIMIT - inspectedCalls;
68
+ for (let at = entries.length - 1; at >= 0 && inspectedCalls < CALL_LIMIT; at--, inspectedCalls++) {
69
+ const call = field(entries, String(at));
70
+ const id = boundedString(field(call, "id"), ID_BYTES);
71
+ const name = boundedString(field(field(call, "function"), "name"), NAME_BYTES);
72
+ if (id) calls.set(id, calls.has(id) ? null : { name, index });
73
+ else incomplete = true;
74
+ }
75
+ if (entries.length > availableCalls) incomplete = true;
76
+ }
77
+ }
78
+ if (role === "tool") {
79
+ if (observations.length === RESULT_LIMIT) { incomplete = true; continue; }
80
+ const id = boundedString(field(message, "tool_call_id"), ID_BYTES);
81
+ observations.push({ id, index, text: text(field(message, "content")), error: field(message, "is_error") === true || field(message, "isError") === true });
82
+ }
83
+ }
84
+ const resultIds = new Set<string>(), duplicates = new Set<string>();
85
+ for (const result of observations) if (result.id) { if (resultIds.has(result.id)) duplicates.add(result.id); resultIds.add(result.id); }
86
+ const results = observations.reverse().map(result => {
87
+ const call = result.id && !duplicates.has(result.id) ? calls.get(result.id) : undefined;
88
+ const associated = !!call && call.index < result.index;
89
+ return { text: result.text, error: result.error, family: associated ? family(call!.name) : "other" as const, associated, ...(associated ? { assistantTurn: call!.index } : {}) };
90
+ });
91
+ return { turn, incomplete, assistantTurns, results };
92
+ } catch { return undefined; }
93
+ }
94
+
95
+ /** Closed failure for numeric compatibility callers; never convert an unavailable size to zero. */
96
+ export class StageSizingUnavailableError extends Error {
97
+ constructor() { super("model input size is unavailable; provide bounded JSON messages and tool schemas"); }
98
+ }
99
+ const WIRE_BYTES = 2_000_000;
100
+ /** Whole-wire UTF-8 estimate. This is not the bounded stage evidence capture. */
101
+ export function estimateStageInputTokens(messages: readonly unknown[], tools?: readonly unknown[]): number | undefined {
102
+ try {
103
+ if (!Array.isArray(messages) || tools !== undefined && !Array.isArray(tools)) return undefined;
104
+ const envelope = { messages, ...(tools === undefined ? {} : { tools }) };
105
+ const active = new Set<object>();
106
+ let bytes = 0, inspected = 0;
107
+ const append = (part: string): void => {
108
+ bytes += Buffer.byteLength(part);
109
+ if (bytes > WIRE_BYTES) throw new StageSizingUnavailableError();
110
+ };
111
+ const encode = (value: unknown, depth: number): void => {
112
+ if (++inspected > WIRE_BYTES || depth > 128) throw new StageSizingUnavailableError();
113
+ if (value === null || typeof value === "boolean") { append(String(value)); return; }
114
+ if (typeof value === "string") {
115
+ if (value.length > WIRE_BYTES) throw new StageSizingUnavailableError();
116
+ append(JSON.stringify(value)); return;
117
+ }
118
+ if (typeof value === "number" && Number.isFinite(value)) { append(JSON.stringify(value)); return; }
119
+ if (!value || typeof value !== "object" || active.has(value)) throw new StageSizingUnavailableError();
120
+ const array = Array.isArray(value);
121
+ if (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new StageSizingUnavailableError();
122
+ if (Object.getOwnPropertyDescriptor(value, "toJSON")) throw new StageSizingUnavailableError();
123
+ active.add(value);
124
+ try {
125
+ append(array ? "[" : "{");
126
+ let count = 0;
127
+ const keys = array ? undefined : Object.keys(value);
128
+ const length = Array.isArray(value) ? value.length : keys!.length;
129
+ if (length > WIRE_BYTES) throw new StageSizingUnavailableError();
130
+ for (let index = 0; index < length; index++) {
131
+ const key = array ? String(index) : keys![index]!;
132
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
133
+ if (descriptor && !("value" in descriptor)) throw new StageSizingUnavailableError();
134
+ const item: unknown = descriptor?.value;
135
+ if (!array && item === undefined) continue;
136
+ if (count++) append(",");
137
+ if (!array) {
138
+ if (key.length > WIRE_BYTES) throw new StageSizingUnavailableError();
139
+ append(JSON.stringify(key)); append(":");
140
+ }
141
+ encode(item === undefined ? null : item, depth + 1);
142
+ }
143
+ append(array ? "]" : "}");
144
+ } finally { active.delete(value); }
145
+ };
146
+ encode(envelope, 0);
147
+ const estimate = Math.ceil(bytes / 4);
148
+ return Number.isSafeInteger(estimate) ? estimate : undefined;
149
+ } catch { return undefined; }
150
+ }
151
+ export function estimateInputTokens(messages: readonly unknown[], tools?: readonly unknown[]): number {
152
+ const estimate = estimateStageInputTokens(messages, tools);
153
+ if (estimate === undefined) throw new StageSizingUnavailableError();
154
+ return estimate;
155
+ }
@@ -1,147 +1,5 @@
1
- // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
- // Ported to TypeScript from NVIDIA NeMo Switchyard crates/libsy/src/algorithms/util/stage.rs at c8848511, modified.
4
-
5
- import type { ToolSignals, TurnKind } from './signals.ts';
6
-
7
- export type Tier = 'capable' | 'efficient';
8
- export type PickerMode = 'capable_first' | 'efficient_first';
9
- export type DecisionSource = 'override' | 'capable_hold' | 'dimensions' | 'ambiguous' | 'llm-classifier' | 'fall_open';
10
- export interface CodingAgentDimensions { severity:number; spinning:number; exploring:number; productionIntensity:number }
11
- export interface ScoreResult { score:number; confidence:number }
12
- export type PickOutcome =
13
- | {kind:'resolved';tier:Tier;source:DecisionSource;probability:number;confidence:number|null}
14
- | {kind:'consult_classifier';probability:number;confidence:number;defaultTier:Tier};
15
- export interface StageState { capableHoldTurnsRemaining:number }
16
- export interface HandoffNoteConfig {
17
- escalationNote: string;
18
- deescalationNote?: string;
19
- onlyOnWrongSignalEscalation?: boolean;
20
- }
21
- export interface StageOptions { mode?:PickerMode; confidenceThreshold?:number; capableHoldTurns?:number; handoffNotes?:HandoffNoteConfig }
22
- /** `hardOverride` (#197, not ported): pickTier's override predicate holds, even when a capable hold answered first. */
23
- export interface StageDecision { tier:Tier|undefined; defaultTier:Tier; source:DecisionSource; probability:number; confidence:number; score:number; dimensions:CodingAgentDimensions; note?:string; state:StageState; hardOverride:boolean }
24
-
25
- const STALL_MIN_TURN_DEPTH=8;
26
- const SCORE_GAIN=5;
27
- const HARD_SEVERITY=0.7;
28
- const SIGNAL_UNIT=0.1;
29
- const SEVERITY_CRITICAL=1;
30
-
31
- export function dimensionsFromSignal(signal:ToolSignals):CodingAgentDimensions {
32
- const recentOps=signal.recentWriteCount+signal.recentEditCount+signal.recentReadCount+signal.recentTodowriteCount;
33
- const deep=signal.turnDepth>=STALL_MIN_TURN_DEPTH;
34
- const noProduction=signal.recentWriteCount===0&&signal.recentEditCount===0;
35
- const investigating=signal.recentReadCount>=1||signal.recentTodowriteCount>=1;
36
- const newActivity=signal.recentNewCount>=1;
37
- const spinning=deep&&noProduction&&!investigating&&!newActivity;
38
- const exploring=deep&&noProduction&&investigating&&!newActivity;
39
- const production=recentOps===0?0:(signal.recentWriteCount+signal.recentEditCount)/recentOps;
40
- return {severity:signal.severity,spinning:spinning?1:0,exploring:exploring?1:0,productionIntensity:production};
41
- }
42
-
43
- export function scoreSignal(signal:ToolSignals):ScoreResult {
44
- const d=dimensionsFromSignal(signal);
45
- const raw=SIGNAL_UNIT*(d.severity/HARD_SEVERITY+d.spinning+d.exploring-d.productionIntensity);
46
- const score=Math.tanh(SCORE_GAIN*raw);
47
- return {score,confidence:Math.abs(score)};
48
- }
49
-
50
- /** Compaction, critical severity or a repeated failure: capable whatever the scores say. */
51
- export function hardOverride(signal:ToolSignals):boolean {
52
- return signal.compacted||signal.severity>=SEVERITY_CRITICAL||signal.repeatedFailure;
53
- }
54
-
55
- export function pickTier(signal:ToolSignals, mode:PickerMode='efficient_first', confidenceThreshold=0.5):PickOutcome {
56
- const defaultTier:Tier=mode==='capable_first'?'capable':'efficient';
57
- if(hardOverride(signal))
58
- return {kind:'resolved',tier:'capable',source:'override',probability:0.5,confidence:1};
59
- const scored=scoreSignal(signal); const probability=(scored.score+1)/2; const half=confidenceThreshold/2;
60
- if(probability>0.5+half||probability<0.5-half)
61
- return {kind:'resolved',tier:probability>0.5?'capable':'efficient',source:'dimensions',probability,confidence:scored.confidence};
62
- return {kind:'consult_classifier',probability,confidence:scored.confidence,defaultTier};
63
- }
64
-
65
- export function handoffNoteFor(tier:Tier, source:DecisionSource, config:HandoffNoteConfig):string|undefined {
66
- if(tier==='capable') {
67
- const signalDriven=source==='override'||source==='dimensions';
68
- return (config.onlyOnWrongSignalEscalation??true)&&!signalDriven ? undefined : config.escalationNote;
69
- }
70
- return config.deescalationNote;
71
- }
72
-
73
- /** Apply stage hard rules, dimension scoring, and the capable recovery hold. */
74
- export function selectStage(signal:ToolSignals, options:StageOptions={}, state:StageState={capableHoldTurnsRemaining:0}):StageDecision {
75
- const mode=options.mode??'efficient_first'; const defaultTier:Tier=mode==='capable_first'?'capable':'efficient';
76
- const holdTurns=Math.max(0,Math.trunc(options.capableHoldTurns??2));
77
- let remaining=Math.max(0,Math.trunc(state.capableHoldTurnsRemaining));
78
- const cleanTestPass=signal.testsPassed&&signal.noErrorStreak>0;
79
- if(cleanTestPass)remaining=0;
80
- let outcome:PickOutcome;
81
- if(!cleanTestPass&&remaining>0){remaining--;outcome={kind:'resolved',tier:'capable',source:'capable_hold',probability:0.5,confidence:1};}
82
- else outcome=pickTier(signal,mode,options.confidenceThreshold??0.5);
83
- if(outcome.kind==='resolved'&&outcome.tier==='capable'&&(outcome.source==='override'||outcome.source==='dimensions'))remaining=holdTurns;
84
- const dimensions=dimensionsFromSignal(signal); const score=scoreSignal(signal).score;
85
- const note = outcome.kind === 'resolved' && options.handoffNotes
86
- ? handoffNoteFor(outcome.tier, outcome.source, options.handoffNotes)
87
- : undefined;
88
- return {
89
- tier: outcome.kind === 'resolved' ? outcome.tier : undefined,
90
- defaultTier,
91
- source: outcome.kind === 'consult_classifier' ? 'ambiguous' : outcome.source,
92
- probability: outcome.probability,
93
- confidence: outcome.confidence ?? 0,
94
- score,
95
- dimensions,
96
- ...(note === undefined ? {} : { note }),
97
- state: { capableHoldTurnsRemaining: remaining },
98
- hardOverride: hardOverride(signal),
99
- };
100
- }
101
-
102
- // Session-aware stay/switch (#197): not ported from Switchyard; the rules follow Weave Router's planner, without its
103
- // history summary on a switch.
104
- export type StaySwitchMode = 'off' | 'shadow' | 'enforce';
105
- /** The routing.toml keys the planner reads. */
106
- export interface StaySwitchPolicy { stay_switch: StaySwitchMode; max_switch_prefill_tokens: number }
107
- // ponytail: an unmeasured prefill bound; #197 AC6 measures prefill before enforce becomes the default.
108
- export const DEFAULT_STAY_SWITCH: StaySwitchPolicy = { stay_switch: 'shadow', max_switch_prefill_tokens: 32_000 };
109
- export type SwitchReason = 'new_pin' | 'compaction' | 'context_fit' | 'same_tier' | 'override' | 'tool_loop' | 'prefill_bound' | 'user_turn';
110
- export interface SwitchCost { inputTokens: number; maxSwitchPrefillTokens: number; fits: (tier: Tier) => boolean }
111
- /** Input tokens a backend would prefill for a conversation, 4 characters each; the relay and local routes share it. */
112
- export function estimateInputTokens(messages: unknown, tools?: unknown[]): number {
113
- return Math.ceil(JSON.stringify({ messages, tools }).length / 4);
114
- }
115
- export interface SwitchPlan { plan: 'stay' | 'switch'; tier: Tier; reason: SwitchReason }
116
- /** What a route event records about the planner; never prompt text. */
117
- export interface SwitchTrace { turnType: TurnKind; prefillTokens: number; staySwitch?: 'shadow' | 'enforce'; plan?: 'stay' | 'switch'; reason?: SwitchReason }
118
-
119
- /**
120
- * Stay on the session's pinned tier or switch to this call's stage decision. A new session or a compaction starts a fresh
121
- * pin, a hard override escalates on any turn, a tool loop keeps its tier, and other changes wait for a user turn; a
122
- * de-escalation that makes the efficient backend prefill more than the bound stays. A tier whose backend cannot hold the
123
- * conversation is never chosen: nothing here summarizes or trims the history to make a switch fit.
124
- */
125
- export function planSwitch(pin: Tier | undefined, fresh: Pick<StageDecision, 'tier' | 'defaultTier' | 'source'> & { hardOverride?: boolean }, turn: TurnKind, cost: SwitchCost): SwitchPlan {
126
- const wanted = fresh.tier ?? fresh.defaultTier, other: Tier = wanted === 'capable' ? 'efficient' : 'capable';
127
- const want = cost.fits(wanted) || !cost.fits(other) ? wanted : other;
128
- const plan = (tier: Tier, reason: SwitchReason): SwitchPlan => ({ plan: pin === undefined || pin === tier ? 'stay' : 'switch', tier, reason });
129
- if (pin === undefined) return plan(want, 'new_pin');
130
- if (turn === 'compaction') return plan(want, 'compaction');
131
- if (want !== wanted || !cost.fits(pin)) return plan(want, 'context_fit');
132
- if (want === pin) return plan(pin, 'same_tier');
133
- // A hold answers before pickTier's overrides, so the override is read on its own: it escalates even during a hold.
134
- if (fresh.source === 'override' || fresh.hardOverride) return plan(want, 'override');
135
- if (turn === 'tool_result') return plan(pin, 'tool_loop');
136
- if (want === 'efficient' && cost.inputTokens > cost.maxSwitchPrefillTokens) return plan(pin, 'prefill_bound');
137
- return plan(want, 'user_turn');
138
- }
139
-
140
- /** The one place hub/auto and local stage routes apply the mode, so both record the same trace. `shadow` and `off` keep the stage tier. */
141
- export function stayOrSwitch(policy: StaySwitchPolicy | undefined, pin: Tier | undefined, fresh: StageDecision, turn: TurnKind, cost: Omit<SwitchCost, 'maxSwitchPrefillTokens'>): { tier: Tier; pin?: Tier; trace: SwitchTrace } {
142
- const { stay_switch: mode, max_switch_prefill_tokens: maxSwitchPrefillTokens } = policy ?? DEFAULT_STAY_SWITCH;
143
- const tier = fresh.tier ?? fresh.defaultTier, trace: SwitchTrace = { turnType: turn, prefillTokens: cost.inputTokens };
144
- if (mode === 'off') return { tier, trace };
145
- const planned = planSwitch(pin, fresh, turn, { ...cost, maxSwitchPrefillTokens });
146
- return { tier: mode === 'enforce' ? planned.tier : tier, pin: planned.tier, trace: { ...trace, staySwitch: mode, plan: planned.plan, reason: planned.reason } };
147
- }
1
+ /** Compatibility path for existing consumers; implementation is authored in stage-only units. */
2
+ export { estimateInputTokens } from "./stage-input.ts";
3
+ export type { CodingAgentDimensions } from "./stage-evidence.ts";
4
+ export { AMBIGUOUS_BAND_DEFAULT, AMBIGUOUS_BAND_MAX, DEFAULT_STAY_SWITCH, ambiguousStage } from "./stage-fallback.ts";
5
+ export type { StageTier as Tier, FallbackStageState as StageState, StaySwitchMode, StaySwitchPolicy, StageSwitchTrace as SwitchTrace } from "./stage-fallback.ts";
@@ -0,0 +1,156 @@
1
+ /** The producer console owns transport and authority. This module owns only its scoped public read view. */
2
+ export function guidancePanelAssets(): { js: string; css: string } {
3
+ const js = String.raw`
4
+ export default (host) => {
5
+ const doc = host.mount.ownerDocument;
6
+ const node = (tag, text, className) => {
7
+ const element = doc.createElement(tag);
8
+ if (text !== undefined) element.textContent = text;
9
+ if (className) element.className = className;
10
+ return element;
11
+ };
12
+ const root = node('div', undefined, 'ahub-guidance');
13
+ root.hidden = true;
14
+ const title = node('h2', 'Guidance');
15
+ const introduction = node('p', 'Inspect task-bound declarations and editable-section diffs. Source evidence is a declaration; actual handoff, testing and model consumption are unknown.');
16
+ const instructions = node('p', 'Create or withdraw with the authorized ahub guidance CLI or MCP tools. This panel only reads declarations.');
17
+ const scopeForm = node('form', undefined, 'ahub-guidance-scope');
18
+ const field = (label, control) => {
19
+ const wrapper = node('label');
20
+ wrapper.append(node('span', label), control);
21
+ scopeForm.append(wrapper);
22
+ return control;
23
+ };
24
+ const project = field('Project', node('select'));
25
+ project.append(node('option', 'Select a running project'));
26
+ project.options[0].value = '';
27
+ const task = field('Task ID', node('input'));
28
+ const epoch = field('Task creation epoch', node('input'));
29
+ for (const input of [task, epoch]) {
30
+ input.type = 'text'; input.inputMode = 'numeric'; input.required = true;
31
+ input.autocomplete = 'off'; input.pattern = '[0-9]+';
32
+ }
33
+ const listButton = node('button', 'List declarations'); listButton.type = 'submit';
34
+ const projectsButton = node('button', 'Refresh projects'); projectsButton.type = 'button';
35
+ scopeForm.append(listButton, projectsButton);
36
+ const notice = node('p', 'Select a project, task ID and task creation epoch.');
37
+ notice.setAttribute('role', 'status'); notice.setAttribute('aria-live', 'polite');
38
+ const recordList = node('div', undefined, 'ahub-guidance-records');
39
+ const next = node('button', 'Next page'); next.type = 'button'; next.hidden = true;
40
+ const output = node('pre', undefined, 'ahub-guidance-output');
41
+ output.tabIndex = 0; output.setAttribute('aria-label', 'Guidance public details');
42
+ root.append(title, introduction, instructions, scopeForm, notice, recordList, next, output);
43
+ host.mount.append(root);
44
+ let generation = 0, disposed = false, visible = false, projects = [], cursor, busy = false;
45
+ const state = (message) => { notice.textContent = message; };
46
+ const update = () => {
47
+ listButton.disabled = busy;
48
+ projectsButton.disabled = busy;
49
+ next.disabled = busy;
50
+ for (const button of recordList.querySelectorAll('button')) button.disabled = busy;
51
+ root.setAttribute('aria-busy', busy ? 'true' : 'false');
52
+ };
53
+ const invalidate = () => {
54
+ generation++; busy = false; cursor = undefined;
55
+ recordList.replaceChildren(); output.textContent = ''; next.hidden = true;
56
+ update();
57
+ };
58
+ const scope = () => {
59
+ const selected = projects.find(row => row.id === project.value);
60
+ if (!selected || typeof selected.instanceId !== 'string' || !selected.instanceId
61
+ || !/^[0-9]+$/.test(task.value) || !/^[0-9]+$/.test(epoch.value)) return;
62
+ const taskId = Number(task.value), taskCreated = Number(epoch.value);
63
+ if (!Number.isSafeInteger(taskId) || taskId < 1 || !Number.isSafeInteger(taskCreated) || taskCreated < 0) return;
64
+ return { projectId: selected.id, instanceId: selected.instanceId, taskId, taskCreated };
65
+ };
66
+ const active = (token) => !disposed && visible && token === generation;
67
+ const failure = () => state('Guidance unavailable. Refresh the selected task scope or check access and guidance_views support.');
68
+ const track = (work) => { void work.catch(() => {}); };
69
+ async function refreshProjects(wanted) {
70
+ invalidate();
71
+ const token = generation;
72
+ busy = true; update(); state('Reading running projects...');
73
+ try {
74
+ const result = await host.snapshot({ panel: 'board', after: 0 });
75
+ if (!active(token)) return;
76
+ if (!result || result.ok === false || !Array.isArray(result.projects)) { failure(); return; }
77
+ const previous = typeof wanted === 'string' ? wanted : project.value;
78
+ projects = result.projects.filter(row => row && typeof row.id === 'string' && row.state === 'running'
79
+ && typeof row.instanceId === 'string' && row.instanceId);
80
+ const empty = node('option', 'Select a running project'); empty.value = '';
81
+ project.replaceChildren(empty);
82
+ for (const row of projects) { const option = node('option', row.id); option.value = row.id; project.append(option); }
83
+ project.value = projects.some(row => row.id === previous) ? previous : '';
84
+ state(projects.length ? 'Select an explicit task ID and creation epoch, then list declarations.' : 'No running projects are available.');
85
+ } catch { if (active(token)) failure(); }
86
+ finally { if (active(token)) { busy = false; update(); } }
87
+ }
88
+ async function read(op, id, after) {
89
+ const selected = scope();
90
+ if (!selected) { state('Select a running project and enter a valid task ID and creation epoch.'); return; }
91
+ const token = ++generation;
92
+ busy = true; next.hidden = true; update();
93
+ state(op === 'show' ? 'Reading declaration diff...' : 'Reading declarations...');
94
+ recordList.replaceChildren(); output.textContent = ''; cursor = undefined;
95
+ try {
96
+ const result = await host.snapshot({ panel: 'guidance', op, ...selected,
97
+ ...(id === undefined ? {} : { id }), ...(after === undefined ? {} : { cursor: after }) });
98
+ if (!active(token)) return;
99
+ if (!result || result.ok !== true || !result.guidance || result.guidance.state !== 'available') { failure(); return; }
100
+ const value = result.guidance;
101
+ if (value.current?.taskId !== selected.taskId || value.current?.taskCreated !== selected.taskCreated) { failure(); return; }
102
+ if (op === 'show' && value.record?.id !== id || op === 'list' && !Array.isArray(value.records)) { failure(); return; }
103
+ if (!Array.isArray(result.lines) || result.lines.some(line => typeof line !== 'string')) { failure(); return; }
104
+ output.textContent = result.lines.join('\n');
105
+ if (op === 'list') {
106
+ for (const record of value.records) {
107
+ const row = node('div', undefined, 'ahub-guidance-record');
108
+ const identity = node('code', record.id);
109
+ const status = node('span', record.status + '; applicable: ' + (record.applicable ? 'yes' : 'no'));
110
+ const show = node('button', 'Show diff'); show.type = 'button';
111
+ show.addEventListener('click', () => track(read('show', record.id)));
112
+ row.append(identity, status, show); recordList.append(row);
113
+ }
114
+ if (value.truncated && typeof value.cursor === 'string' && value.cursor) {
115
+ cursor = value.cursor; next.hidden = false;
116
+ }
117
+ }
118
+ state(op === 'show' ? 'Public editable-section diff. Protected section bodies remain private.'
119
+ : value.truncated ? 'Page read. Use Next page to read more, or list again to refresh.' : 'Page complete.');
120
+ } catch { if (active(token)) failure(); }
121
+ finally { if (active(token)) { busy = false; update(); } }
122
+ }
123
+ scopeForm.addEventListener('submit', event => { event.preventDefault(); track(read('list')); });
124
+ projectsButton.addEventListener('click', () => track(refreshProjects()));
125
+ next.addEventListener('click', () => { if (cursor) track(read('list', undefined, cursor)); });
126
+ for (const input of [project, task, epoch]) input.addEventListener('input', () => {
127
+ invalidate(); state('Task scope changed. List declarations to read the selected scope.');
128
+ });
129
+ return {
130
+ show(_panel, params) {
131
+ if (disposed) return;
132
+ visible = true; root.hidden = false;
133
+ if (typeof params?.taskId === 'string') task.value = params.taskId;
134
+ if (typeof params?.taskCreated === 'string') epoch.value = params.taskCreated;
135
+ track(refreshProjects(typeof params?.project === 'string' ? params.project : undefined));
136
+ },
137
+ hide() { visible = false; invalidate(); root.hidden = true; },
138
+ destroy() { disposed = true; visible = false; invalidate(); root.remove(); },
139
+ };
140
+ };
141
+ `;
142
+ const css = `.ahub-guidance{color:inherit;font:inherit;padding:20px;max-width:1100px;-webkit-font-smoothing:antialiased}
143
+ .ahub-guidance h2{margin:0 0 8px;text-wrap:balance}.ahub-guidance p{max-width:85ch;line-height:1.5;text-wrap:pretty}
144
+ .ahub-guidance-scope{display:flex;flex-wrap:wrap;gap:12px;align-items:end;margin:20px 0}
145
+ .ahub-guidance label{display:grid;gap:6px;min-width:160px}.ahub-guidance label span{font-size:.875em}
146
+ .ahub-guidance input,.ahub-guidance select,.ahub-guidance button{font:inherit;color:inherit;background:transparent;border:1px solid currentColor;border-radius:6px;min-height:40px;padding:8px 12px}
147
+ .ahub-guidance input{width:18ch;max-width:100%;box-sizing:border-box;font-variant-numeric:tabular-nums}
148
+ .ahub-guidance button{cursor:pointer}.ahub-guidance button:disabled{opacity:.5;cursor:default}
149
+ .ahub-guidance :is(button,input,select,pre):focus-visible{outline:2px solid currentColor;outline-offset:3px}
150
+ .ahub-guidance-records{display:grid;gap:8px;margin:12px 0}.ahub-guidance-record{display:flex;flex-wrap:wrap;gap:12px;align-items:center;padding:12px;border:1px solid currentColor;border-radius:10px}
151
+ .ahub-guidance-record code{overflow-wrap:anywhere;flex:1 1 30ch}.ahub-guidance-record span{font-size:.875em}
152
+ .ahub-guidance-output{white-space:pre-wrap;overflow-wrap:anywhere;font-size:.875em;line-height:1.55;font-variant-numeric:tabular-nums;padding:16px;border:1px solid currentColor;border-radius:10px;max-height:65vh;overflow:auto}
153
+ .ahub-guidance-output:empty{display:none}.ahub-guidance [hidden]{display:none!important}
154
+ @media(max-width:600px){.ahub-guidance{padding:12px}.ahub-guidance-scope>label{width:100%}.ahub-guidance input{width:100%}}`;
155
+ return { js, css };
156
+ }
@@ -0,0 +1,43 @@
1
+ import type { GuidanceDiffResult, GuidancePageResult, GuidanceWriteReceipt } from "../hub/guidance-variants.ts";
2
+ import { sanitize } from "../hub/envelope.ts";
3
+
4
+ /** Shared public projection only. These lines neither reconstruct private role bytes nor attest to a handoff. */
5
+ export function guidanceLines(value: GuidancePageResult | GuidanceDiffResult): string[] {
6
+ const text = (raw: string): string => sanitize(raw).replace(/[\p{Cc}\p{Cf}]/gu, character => character === "\n" ? character : "");
7
+ const field = (label: string, raw: string): string[] => [label + " (untrusted advisory text):", ...text(raw).split("\n").map(line => `> ${line}`)];
8
+ if (value.state !== "available") return ["Guidance unavailable. Refresh the selected task scope or check access and guidance_views support."];
9
+ const current = value.current;
10
+ const lines = ["Guidance declarations (advisory)", `Current task #${current.taskId}; epoch ${current.taskCreated}; flow ${current.flowRevision}.`,
11
+ "Source evidence is declared or unavailable. Actual handoff, testing and model consumption are unknown."];
12
+ const records = "record" in value ? [value.record] : value.records;
13
+ if (!records.length) lines.push("No guidance declarations in this page.");
14
+ for (const record of records) {
15
+ lines.push(`Variant ${record.id}`, `Task #${record.taskId}; epoch ${record.taskCreated}; declaration flow ${record.flowRevision}.`,
16
+ `Status: ${record.status}; currently applicable: ${record.applicable ? "yes" : "no"}.`,
17
+ `Role: ${record.roleId} (${record.layer}); author: ${record.author}.`,
18
+ `Baseline SHA-256: ${record.baselineSha256}`, `Candidate SHA-256: ${record.candidateSha256}`,
19
+ `Bytes: baseline ${record.bytes.baseline}; candidate ${record.bytes.candidate}; record ${record.bytes.record}.`,
20
+ `Changed sections: ${record.changedSections.join(", ") || "none"}.`,
21
+ ...field("Experiment label", record.experimentId),
22
+ ...field("Problem hypothesis", record.rationale.problemHypothesis),
23
+ ...field("Expected observable difference", record.rationale.expectedObservableDifference));
24
+ for (const evidence of record.evidence) lines.push(`Evidence digest ${evidence.key}: ${evidence.status} (declaration only).`);
25
+ if (!record.evidence.length) lines.push("No source evidence declarations.");
26
+ }
27
+ if ("sections" in value) {
28
+ for (const section of value.sections) lines.push(`${section.section} diff`, ...field("Before", section.before), ...field("After", section.after));
29
+ lines.push(`Protected sections unchanged by construction: ${value.protectedSections.join(", ")}.`,
30
+ "Diff text is a screened public presentation, not the exact private bytes for a new record.");
31
+ } else {
32
+ lines.push(value.truncated ? "More declarations are available. Request the next page explicitly." : "Page complete.");
33
+ }
34
+ return lines;
35
+ }
36
+
37
+ /** A receipt confirms only its recorded declaration status, never execution or model use. */
38
+ export function guidanceReceiptLines(receipt: GuidanceWriteReceipt): string[] {
39
+ const experiment = sanitize(receipt.experimentId).replace(/[\p{Cc}\p{Cf}]/gu, "");
40
+ return [`Guidance ${receipt.status}${receipt.already ? " (already recorded)" : ""}.`, `Variant ${receipt.id}; task #${receipt.taskId}.`,
41
+ "Experiment label (untrusted advisory text):", `> ${experiment}`,
42
+ "Actual handoff, testing and model consumption are unknown."];
43
+ }
@@ -0,0 +1,34 @@
1
+ import type { ExecutionReferenceV1 } from "../hub/execution-reference.ts";
2
+ import type { LineageResult } from "../hub/execution-lineage.ts";
3
+
4
+ /**
5
+ * The one lineage view, shared by `ahub lineage show` and the acon provider (#1220 T3), so both
6
+ * surfaces show the same admitted page. Pure: no IO, clocks, probes or imports of a CLI module.
7
+ * Every string rendered here comes from a result that passed `parseLineageResult` and
8
+ * `parseExecutionReference`, which reject `\p{Cc}`; a terminal surface still strips at its own
9
+ * boundary (`renderExecutionLineage` in src/cli/lineage.ts).
10
+ */
11
+ export const executionLineageAddress = (ref: ExecutionReferenceV1): string =>
12
+ `${ref.tool}:${ref.kind} ${ref.id} (project ${ref.projectKey}${ref.revision === undefined ? "" : `, revision ${ref.revision}`}${ref.sha256 === undefined ? "" : `, sha256 ${ref.sha256}`})`;
13
+
14
+ type Unavailable = Extract<LineageResult, { state: "unavailable" }>;
15
+ const REPAIR: Record<NonNullable<Unavailable["reason"]>, string> = {
16
+ corrupt: "trusted source state could not be read; inspect ahub recovery status and the trusted source state before retrying ahub lineage show",
17
+ cursor_invalid: "the cursor is stale or does not match this source snapshot; refresh the same root and bounds without --cursor",
18
+ invalid: "the execution reference or page bounds are invalid; run ahub help lineage, correct the reference or bounds and retry",
19
+ withheld: "source metadata is withheld by policy; ask an authorized person to check the policy and select a public task scope before retrying ahub lineage show",
20
+ missing: "the root is not recorded in this admitted source; check the task or attempt identity and task scope, then retry ahub lineage show",
21
+ unsupported: "this source cannot project the requested root or scope within its supported bounds; select a supported root or smaller task scope, or upgrade the source before retrying ahub lineage show",
22
+ };
23
+
24
+ export function executionLineageLines(result: LineageResult): string[] {
25
+ if (result.state === "unavailable") {
26
+ // An unavailable source is never an empty successful graph: the reason is shown only when the
27
+ // source admitted diagnostics, and its absence keeps the unqualified refusal.
28
+ if (result.reason === undefined) return ["Lineage unavailable; check the root reference and your source-read access, then retry ahub lineage show."];
29
+ return [`Lineage unavailable (${result.reason}): ${REPAIR[result.reason]}.`];
30
+ }
31
+ return ["Execution lineage (metadata only)", ...result.nodes.map(node => `${executionLineageAddress(node.ref)}: ${node.state}, ${node.strength}`),
32
+ ...result.edges.map(edge => `${executionLineageAddress(edge.from)} -> ${executionLineageAddress(edge.to)}: ${edge.relation}, ${edge.strength}`),
33
+ ...(result.truncated ? [`Page truncated; retry the same root and bounds with --cursor ${result.cursor}.`] : ["Page complete."])];
34
+ }