@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,358 @@
1
+ import { createHash } from "node:crypto";
2
+ import { types } from "node:util";
3
+ import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
4
+
5
+ /** Published V1 format/admission bounds, not native execution guarantees. */
6
+ export const GUIDANCE_PROBE_LIMITS = Object.freeze({ recordBytes: 32768, snapshotBytes: 32768,
7
+ storageBytes: 1073741824, workerAttempts: 4, editorAttempts: 5, slots: 9, hashLength: 64 });
8
+ const registrationScaffoldBytes = Buffer.byteLength(JSON.stringify({ manifest: 0, snapshots: { task: "", baselineContext: "", dataPolicy: 0, systemPolicy: "", improverContext: "" } }));
9
+ /** Closed composition bounds, separate from each admitted manifest/snapshot ceiling. */
10
+ export const GUIDANCE_PROBE_REGISTRATION_BYTES = GUIDANCE_PROBE_LIMITS.recordBytes + GUIDANCE_PROBE_LIMITS.snapshotBytes
11
+ + 4 * 2 * GUIDANCE_PROBE_LIMITS.snapshotBytes + registrationScaffoldBytes;
12
+ export const GUIDANCE_PROBE_SESSION_BYTES = 4 * GUIDANCE_PROBE_LIMITS.recordBytes;
13
+ export const GUIDANCE_PROBE_STOP_TIMEOUT_MS = 5000;
14
+ export const GUIDANCE_PROBE_FENCE_INTERVAL_MS = 250;
15
+ export const GUIDANCE_PROBE_MODEL = "qwen27b/qwen3.8-27b";
16
+ export type ProbeInteger = number;
17
+ export type ProbeSha256 = string;
18
+ export type ProbeId = string;
19
+ export type ProbeTree = { objectFormat: "sha1"; oid: string } | { objectFormat: "sha256"; oid: string };
20
+ export interface ProbeSnapshotRef { sha256: string; bytes: number }
21
+ export interface ProbeRoleIdentity { id: string; layer: "shipped" | "project"; baselineSha256: string }
22
+ export type ProbeArm = "baseline" | "candidate1" | "candidate2" | "successor";
23
+ export type ProbeStage = "baseline" | "proposal1" | "candidate1" | "proposal2" | "candidate2" | "compose" | "successor" | "select" | "reflect";
24
+ export interface ProbeSlot { id: string; stage: ProbeStage; role: "worker" | "proposal" | "compose" | "select" | "reflect"; arm: ProbeArm | "none"; retryOf?: string }
25
+ export interface GuidanceProbeManifestV1 {
26
+ v: 1; projectKey: string; experimentId: string;
27
+ task: { id: number; created: number; flowRevision: number };
28
+ role: ProbeRoleIdentity;
29
+ inputs: { task: ProbeSnapshotRef; baselineContext: ProbeSnapshotRef; dataPolicy: ProbeSnapshotRef; systemPolicy: ProbeSnapshotRef; codeTree: ProbeTree };
30
+ runtime: { runtimeSha256: string; toolsetSha256: string; modelConfigSha256: string };
31
+ model: { requested: typeof GUIDANCE_PROBE_MODEL; expectedServed: typeof GUIDANCE_PROBE_MODEL };
32
+ guidance: { baselineSha256: string };
33
+ improverContextHash?: string; improverContextBytes?: number;
34
+ slots: readonly ProbeSlot[];
35
+ limits: { modelCalls: number; toolCalls: number; elapsedMs: number; tokens?: number; inputBytes: number; scratchBytes: number; outputBytes: number };
36
+ taskOrderSeed?: number;
37
+ }
38
+ export interface ProbeDataPolicyV1 {
39
+ v: 1;
40
+ allowedWrites: readonly { root: "scratch" | "output"; relative: string }[];
41
+ admittedData: readonly { id: string; sha256: string; bytes: number }[];
42
+ roles: {
43
+ worker: { dataIds: readonly string[]; guidanceOnlyExperience: true };
44
+ proposal: { dataIds: readonly string[]; improverContext: boolean };
45
+ compose: { dataIds: readonly string[]; improverContext: boolean };
46
+ select: { dataIds: readonly string[]; anonymizedDeliverables: true };
47
+ reflect: { dataIds: readonly string[]; closedRoundOnly: true };
48
+ };
49
+ }
50
+ export interface ProbePrivateSnapshots { task: string; baselineContext: string; dataPolicy: ProbeDataPolicyV1; systemPolicy: string; improverContext?: string }
51
+ export interface ProbeRegistrationV1 { manifest: GuidanceProbeManifestV1; snapshots: ProbePrivateSnapshots }
52
+ export type ProbeState = "declared" | "active" | "closing" | "closed_fixture" | "failed_fixture" | "unknown_held";
53
+ export type ProbeSessionState = "planned" | "reserved" | "running" | "failed_known" | "closed_fixture" | "not_needed" | "unknown_held";
54
+ export type ProbeBudgetUnit = "model_calls" | "tool_calls" | "tokens" | "input_bytes" | "scratch_bytes" | "output_bytes";
55
+ export interface ProbeKey { projectKey: string; id: string }
56
+ export interface ProbeHostBinding {
57
+ projectKey: string; actor: string; task: { id: number; created: number; flowRevision: number }; role: ProbeRoleIdentity;
58
+ baselineGuidance: string; sessionGeneration: number | string; nativeSession: string | null; requestConnectionId: string;
59
+ }
60
+ export interface ProbeChildBinding {
61
+ variantId: string; candidateSha256: string; guidanceSha256: string; task: ProbeHostBinding["task"]; role: ProbeRoleIdentity; guidance: string;
62
+ authoring: "admitted_fixture" | "uncontrolled"; sourceSessionId: string | null;
63
+ }
64
+ export interface ProbeAdmissionRecheck { host: ProbeHostBinding; child?: ProbeChildBinding }
65
+ /** Hash/size of the exact frame built once by the trusted host before atomic admission. */
66
+ export interface ProbePreparedFrame { slotId: string; sha256: string; bytes: number }
67
+ export interface ProbePreparedWorkerFrame { inputFrame: string; nonGuidanceInputSha256: string }
68
+ export type ProbeWorkerFramePreparer = (state: ProbeStoredState, slot: ProbeSlot, guidance: string) => ProbePreparedWorkerFrame | Promise<ProbePreparedWorkerFrame>;
69
+ export interface ProbeResourceCharges { inputBytes?: number; scratchBytes?: number; outputBytes?: number }
70
+ export interface ProbeSessionAdmission {
71
+ key: ProbeKey; expectedRevision: number; host: ProbeHostBinding; child?: ProbeChildBinding; preparedFrame?: ProbePreparedFrame; now: number;
72
+ }
73
+ export interface ProbeReservation { key: ProbeKey; slotId: string; generation: number; revision: number }
74
+ export interface ProbeStartSelector {
75
+ requestedRevision: number; slotId: string; variantId: string | null; inputFrameSha256: string | null; inputFrameBytes: number;
76
+ actor: string; sessionGeneration: number | string; nativeSession: string | null; requestConnectionId: string;
77
+ }
78
+ export interface ProbeReceipt { id: string; revision: number; state: ProbeState; already: boolean }
79
+ export type ProbeReservationResult = { kind: "granted"; reservation: ProbeReservation } | { kind: "existing"; receipt: ProbeReceipt };
80
+ export interface ProbeEffectAdmission { reservation: ProbeReservation; sequence: number; unit: ProbeBudgetUnit; amount: number; reservedTokens?: number; charges?: ProbeResourceCharges; descriptorSha256: string; now: number }
81
+ export type ProbeEffectAdmissionResult = { kind: "granted"; admission: ProbeEffectAdmission } | { kind: "existing"; state: "pending" | "settled" | "unknown" };
82
+ export interface ProbeEffectSettlement { admission: ProbeEffectAdmission; outcome: "settled" | "unknown" }
83
+ export interface ProbeSessionSettlement { reservation: ProbeReservation; outcome: "closed_fixture" | "failed_known" | "unknown"; candidateArtifactSha256: string | null; now: number }
84
+ export interface ProbeSessionCoverage {
85
+ inputFrameSha256: string | null; inputFrameBytes: number; launchExposed: boolean; preLaunchFailure: boolean;
86
+ modelCalls: number; modelUsageKnown: number; toolCalls: number; toolUsageKnown: number;
87
+ usageUnknown: boolean; coverageVerified: boolean;
88
+ }
89
+ export interface ProbeUsageObservation { admission: ProbeEffectAdmission; observed: number | null; observationSha256: string }
90
+ export interface ProbeCancellation { key: ProbeKey; expectedRevision: number; host: ProbeHostBinding }
91
+ export interface ProbeCounters {
92
+ workerAttempts: number; editorAttempts: number; modelCalls: number; toolCalls: number; tokensReserved: number; tokensObservedKnown: number;
93
+ inputBytes: number; scratchBytes: number; outputBytes: number; elapsedHighWaterMs: number; usageUnknown: boolean;
94
+ }
95
+ export interface ProbeSession {
96
+ slotId: string; generation: number; revision: number; state: ProbeSessionState; candidateArtifactSha256: string | null;
97
+ child?: ProbeChildBinding;
98
+ start?: ProbeStartSelector;
99
+ coverage: ProbeSessionCoverage;
100
+ }
101
+ export interface ProbeStoredState {
102
+ registration: ProbeRegistrationV1; binding: ProbeHostBinding; receipt: ProbeReceipt; counters: ProbeCounters;
103
+ firstReservedAt: number | null; admissionHold: "none" | "elapsed" | "observation" | "usage"; cancelRequested: boolean; notNeeded: number; sessions: readonly ProbeSession[];
104
+ }
105
+ export interface ProbeIntegrity { experiments: number; sessions: number; digest: string }
106
+ export interface ProbeFakeLaunch { reservation: ProbeReservation; slot: ProbeSlot; manifest: GuidanceProbeManifestV1; inputFrame: string; inputSha256: string; nonGuidanceInputSha256: string; purpose: "guidance_probe" }
107
+ export interface ProbeFakeObservation {
108
+ reservation: ProbeReservation; outcome: "closed_fixture" | "failed_known" | "unknown"; servedModel: string | null;
109
+ inputFrameHash: string | null;
110
+ workerEffectiveInputHash: string | null; nonGuidanceInputSha256: string | null; candidateArtifactSha256: string | null; usage: "known_fixture" | "unknown";
111
+ }
112
+ export interface ProbeFakeStop { reservation: ProbeReservation }
113
+ export interface ProbeFakeStopObservation { reservation: ProbeReservation; stopped: "known_fixture" | "unknown" }
114
+ export interface ProbeFakeEffectRequest { sequence: number; unit: "model_calls" | "tool_calls" | "resources"; descriptorSha256: string; reservedTokens?: number; charges?: ProbeResourceCharges }
115
+ export interface ProbeFakeEffectValue<T> { value: T; usage: number | null; observationSha256: string }
116
+ export type ProbeFakeEffectResult<T> = { kind: "executed"; value: T } | { kind: "existing"; state: "pending" | "settled" | "unknown" };
117
+ export interface ProbeFakeEffects {
118
+ /** Fresh captured actor/G1/ledger fence; no authority is reconstructed from metadata. */
119
+ current(): void;
120
+ runEffect<T>(request: ProbeFakeEffectRequest, effect: (signal: AbortSignal) => Promise<ProbeFakeEffectValue<T>>): Promise<ProbeFakeEffectResult<T>>;
121
+ }
122
+ /** Host test constructor only: never selected by manifest, configuration or a wire field. */
123
+ export interface GuidanceProbeFakePorts {
124
+ launch(input: ProbeFakeLaunch, effects: ProbeFakeEffects, signal: AbortSignal): Promise<ProbeFakeObservation>;
125
+ stop(input: ProbeFakeStop, signal: AbortSignal): Promise<ProbeFakeStopObservation>;
126
+ }
127
+ export interface ProbePublicReceipt extends ProbeReceipt { experimentId: string; taskId: number; evidence: "declaration" | "fixture" | "unknown" }
128
+ export interface ProbePublicStatus extends ProbePublicReceipt { counters: ProbeCounters; cancelRequested: boolean; notNeeded: number; comparable: boolean; authoring: "admitted_fixture" | "uncontrolled" | "unknown" }
129
+ export type GuidanceProbeCommand = { op: "register"; file: string; json: boolean }
130
+ | { op: "start"; id: string; revision: number; variantId?: string; json: boolean }
131
+ | { op: "show"; id: string; json: boolean } | { op: "cancel"; id: string; revision: number; json: boolean };
132
+
133
+ export class GuidanceProbeError extends Error {
134
+ constructor(readonly reason: "invalid" | "changed" | "budget" | "held" | "runner" | "storage") {
135
+ super({ invalid: "invalid probe fields or bounds; reload the closed V1 declaration before retrying",
136
+ changed: "probe binding or revision changed; read the current task, G1 and probe before retrying",
137
+ budget: "probe aggregate budget is exhausted or unknown; inspect the retained accounting before a separate experiment",
138
+ held: "probe outcome is uncertain or already active; inspect retained state without replaying work",
139
+ runner: "probe runner is unavailable in production T1; use fake-only fixtures, not a live launch",
140
+ storage: "probe storage is invalid or unavailable; inspect retained probe state before retrying" }[reason]);
141
+ this.name = "GuidanceProbeError";
142
+ }
143
+ }
144
+ const invalid = (): never => { throw new GuidanceProbeError("invalid"); };
145
+ export const probeHash = (text: string): string => createHash("sha256").update(text, "utf8").digest("hex");
146
+ export const probeInteger = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
147
+ export const probeSha256 = (value: unknown): value is string => typeof value === "string" && value.length === GUIDANCE_PROBE_LIMITS.hashLength && /^[a-f0-9]+$/.test(value);
148
+ const identity = (value: unknown): value is string => executionText(value, EXECUTION_REFERENCE_LIMITS.id) && !/\p{Cf}/u.test(value);
149
+ export const probeSessionGeneration = (value: unknown): value is number | string => probeInteger(value) || identity(value);
150
+ const required = (condition: unknown): void => { if (!condition) invalid(); };
151
+
152
+ /** Bounded inert copy: no getter, iterator, proxy, toJSON, sparse array or cycle is evaluated. */
153
+ function inert(value: unknown, maximum: number): unknown {
154
+ let remaining = maximum;
155
+ const seen = new Set<object>();
156
+ const charge = (bytes: number) => { remaining -= bytes; if (remaining < 0) invalid(); };
157
+ const copy = (item: unknown): unknown => {
158
+ if (item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) { charge(Buffer.byteLength(JSON.stringify(item))); return item; }
159
+ if (typeof item === "string") { if (item.length > remaining) invalid(); charge(Buffer.byteLength(JSON.stringify(item))); return item; }
160
+ if (!item || typeof item !== "object" || types.isProxy(item) || seen.has(item)) return invalid();
161
+ const array = Array.isArray(item), proto = Object.getPrototypeOf(item);
162
+ if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) return invalid();
163
+ const keys = Reflect.ownKeys(item);
164
+ if (keys.length > remaining) return invalid();
165
+ seen.add(item); charge(2);
166
+ if (array) {
167
+ const length = Object.getOwnPropertyDescriptor(item, "length")?.value;
168
+ if (!probeInteger(length) || keys.length !== length + 1) return invalid();
169
+ const result: unknown[] = [];
170
+ for (let index = 0; index < length; index++) {
171
+ const field = Object.getOwnPropertyDescriptor(item, String(index));
172
+ if (!field || !("value" in field) || !field.enumerable) return invalid();
173
+ if (index) charge(1); result.push(copy(field.value));
174
+ }
175
+ seen.delete(item); return result;
176
+ }
177
+ const result: Record<string, unknown> = Object.create(null);
178
+ let index = 0;
179
+ for (const key of keys) {
180
+ if (typeof key !== "string") return invalid();
181
+ const field = Object.getOwnPropertyDescriptor(item, key);
182
+ if (!field || !("value" in field) || !field.enumerable) return invalid();
183
+ charge(Buffer.byteLength(JSON.stringify(key)) + 1 + (index++ ? 1 : 0)); result[key] = copy(field.value);
184
+ }
185
+ seen.delete(item); return result;
186
+ };
187
+ return copy(value);
188
+ }
189
+ function object(value: unknown, keys: readonly string[], optional: readonly string[] = []): Record<string, unknown> {
190
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
191
+ const fields = value as Record<string, unknown>;
192
+ if (Object.keys(fields).some(key => !keys.includes(key) && !optional.includes(key)) || keys.some(key => !Object.hasOwn(fields, key))) return invalid();
193
+ return fields;
194
+ }
195
+ function canonical(value: unknown): string {
196
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
197
+ if (value && typeof value === "object") return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`).join(",")}}`;
198
+ return JSON.stringify(value);
199
+ }
200
+ export const guidanceProbeCanonical = (value: unknown, maximum: number = GUIDANCE_PROBE_LIMITS.recordBytes): string => canonical(inert(value, maximum));
201
+ function ref(value: unknown): void { const fields = object(value, ["sha256", "bytes"]); required(probeSha256(fields.sha256) && probeInteger(fields.bytes) && fields.bytes <= GUIDANCE_PROBE_LIMITS.snapshotBytes); }
202
+ function role(value: unknown): void { const fields = object(value, ["id", "layer", "baselineSha256"]); required(identity(fields.id) && ["shipped", "project"].includes(fields.layer as string) && probeSha256(fields.baselineSha256)); }
203
+ const graph: readonly [ProbeStage, ProbeSlot["role"], ProbeSlot["arm"]][] = [
204
+ ["baseline", "worker", "baseline"], ["proposal1", "proposal", "none"], ["candidate1", "worker", "candidate1"],
205
+ ["proposal2", "proposal", "none"], ["candidate2", "worker", "candidate2"], ["compose", "compose", "none"],
206
+ ["successor", "worker", "successor"], ["select", "select", "none"], ["reflect", "reflect", "none"] ];
207
+ function slots(value: unknown): void {
208
+ required(Array.isArray(value) && value.length > 0 && value.length <= GUIDANCE_PROBE_LIMITS.slots);
209
+ const list = value as ProbeSlot[], ids = new Set<string>(), counts = new Map<string, number>();
210
+ let last = -1;
211
+ for (const slot of list) {
212
+ const fields = object(slot, ["id", "stage", "role", "arm"], ["retryOf"]), position = graph.findIndex(item => item[0] === fields.stage);
213
+ required(identity(fields.id) && !ids.has(fields.id as string) && position >= 0);
214
+ required(graph[position]![1] === fields.role && graph[position]![2] === fields.arm);
215
+ if (Object.hasOwn(fields, "retryOf")) {
216
+ const prior = list[ids.size - 1];
217
+ required(identity(fields.retryOf) && prior && prior.id === fields.retryOf && prior.stage === fields.stage && position === last);
218
+ } else { required(position > last); last = position; }
219
+ ids.add(slot.id); counts.set(slot.role, (counts.get(slot.role) ?? 0) + 1);
220
+ }
221
+ required(list[0]!.stage === "baseline" && list.some(item => item.stage === "candidate1"));
222
+ required(!list.some(item => item.stage === "proposal2") || list.some(item => item.stage === "candidate2"));
223
+ required(!list.some(item => item.stage === "compose") || list.some(item => item.stage === "successor"));
224
+ required((counts.get("worker") ?? 0) <= GUIDANCE_PROBE_LIMITS.workerAttempts && (counts.get("proposal") ?? 0) <= 2
225
+ && ["compose", "select", "reflect"].every(key => (counts.get(key) ?? 0) <= 1)
226
+ && list.filter(item => item.role !== "worker").length <= GUIDANCE_PROBE_LIMITS.editorAttempts);
227
+ }
228
+ function manifest(value: unknown): GuidanceProbeManifestV1 {
229
+ const fields = object(value, ["v", "projectKey", "experimentId", "task", "role", "inputs", "runtime", "model", "guidance", "slots", "limits"], ["improverContextHash", "improverContextBytes", "taskOrderSeed"]);
230
+ required(fields.v === 1 && identity(fields.projectKey) && identity(fields.experimentId));
231
+ const task = object(fields.task, ["id", "created", "flowRevision"]); required(probeInteger(task.id) && task.id > 0 && probeInteger(task.created) && probeInteger(task.flowRevision)); role(fields.role);
232
+ const inputs = object(fields.inputs, ["task", "baselineContext", "dataPolicy", "systemPolicy", "codeTree"]);
233
+ for (const key of ["task", "baselineContext", "dataPolicy", "systemPolicy"]) ref(inputs[key]);
234
+ const tree = object(inputs.codeTree, ["objectFormat", "oid"]), oidLength = tree.objectFormat === "sha1" ? 40 : tree.objectFormat === "sha256" ? GUIDANCE_PROBE_LIMITS.hashLength : 0;
235
+ required(typeof tree.oid === "string" && oidLength > 0 && tree.oid.length === oidLength && /^[a-f0-9]+$/.test(tree.oid));
236
+ const runtime = object(fields.runtime, ["runtimeSha256", "toolsetSha256", "modelConfigSha256"]); required(Object.values(runtime).every(probeSha256));
237
+ const model = object(fields.model, ["requested", "expectedServed"]); required(model.requested === GUIDANCE_PROBE_MODEL && model.expectedServed === GUIDANCE_PROBE_MODEL);
238
+ required(probeSha256(object(fields.guidance, ["baselineSha256"]).baselineSha256));
239
+ const limits = object(fields.limits, ["modelCalls", "toolCalls", "elapsedMs", "inputBytes", "scratchBytes", "outputBytes"], ["tokens"]);
240
+ required(Object.values(limits).every(probeInteger));
241
+ let bytes = GUIDANCE_PROBE_LIMITS.storageBytes;
242
+ for (const key of ["inputBytes", "scratchBytes", "outputBytes"]) { required((limits[key] as number) <= bytes); bytes -= limits[key] as number; }
243
+ required(Object.hasOwn(fields, "improverContextHash") === Object.hasOwn(fields, "improverContextBytes"));
244
+ if (Object.hasOwn(fields, "improverContextHash")) { required(probeSha256(fields.improverContextHash)); required(probeInteger(fields.improverContextBytes) && fields.improverContextBytes <= GUIDANCE_PROBE_LIMITS.snapshotBytes); }
245
+ if (Object.hasOwn(fields, "taskOrderSeed")) required(probeInteger(fields.taskOrderSeed));
246
+ slots(fields.slots);
247
+ return fields as unknown as GuidanceProbeManifestV1;
248
+ }
249
+ export function parseGuidanceProbeManifest(value: unknown): GuidanceProbeManifestV1 | undefined {
250
+ try { return manifest(inert(value, GUIDANCE_PROBE_LIMITS.recordBytes)); } catch { return undefined; }
251
+ }
252
+ export function guidanceProbeManifestKey(value: GuidanceProbeManifestV1): string {
253
+ const parsed = parseGuidanceProbeManifest(value); if (!parsed) return invalid();
254
+ return probeHash(`agent-hub.guidance-probe.v1\n${guidanceProbeCanonical(parsed)}`);
255
+ }
256
+ function policy(value: unknown): ProbeDataPolicyV1 {
257
+ const fields = object(value, ["v", "allowedWrites", "admittedData", "roles"]); required(fields.v === 1 && Array.isArray(fields.allowedWrites) && Array.isArray(fields.admittedData));
258
+ const ids = new Set<string>(), writes = new Set<string>();
259
+ for (const write of fields.allowedWrites as unknown[]) {
260
+ const row = object(write, ["root", "relative"]); required(["scratch", "output"].includes(row.root as string) && identity(row.relative));
261
+ const name = row.relative as string; required(!name.includes("\\") && !name.startsWith("/") && !/^[a-z]:/i.test(name) && name.split("/").every(part => part && part !== "." && part !== ".."));
262
+ const key = `${row.root}/${name}`; required(!writes.has(key)); writes.add(key);
263
+ }
264
+ for (const data of fields.admittedData as unknown[]) { const row = object(data, ["id", "sha256", "bytes"]); required(identity(row.id) && !ids.has(row.id as string) && probeSha256(row.sha256) && probeInteger(row.bytes)); ids.add(row.id as string); }
265
+ const roles = object(fields.roles, ["worker", "proposal", "compose", "select", "reflect"]);
266
+ for (const [name, flag] of [["worker", "guidanceOnlyExperience"], ["proposal", "improverContext"], ["compose", "improverContext"], ["select", "anonymizedDeliverables"], ["reflect", "closedRoundOnly"]] as const) {
267
+ const row = object(roles[name], ["dataIds", flag]); required(Array.isArray(row.dataIds) && typeof row[flag] === "boolean" && (flag === "improverContext" || row[flag] === true));
268
+ const used = new Set<string>(); for (const id of row.dataIds as unknown[]) { required(identity(id) && ids.has(id as string) && !used.has(id as string)); used.add(id as string); }
269
+ }
270
+ return fields as unknown as ProbeDataPolicyV1;
271
+ }
272
+ export function parseGuidanceProbeRegistration(value: unknown): ProbeRegistrationV1 | undefined {
273
+ try {
274
+ // Inspect envelope/snapshot descriptors before any potentially large nested traversal.
275
+ if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)
276
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return undefined;
277
+ const names = Reflect.ownKeys(value);
278
+ if (names.length !== 2 || !names.includes("manifest") || !names.includes("snapshots")) return undefined;
279
+ const envelope = Object.getOwnPropertyDescriptors(value);
280
+ if (Object.values(envelope).some(item => !("value" in item) || !item.enumerable)) return undefined;
281
+ const parsed = parseGuidanceProbeManifest(envelope.manifest?.value); if (!parsed) return undefined;
282
+ const raw = envelope.snapshots?.value;
283
+ if (!raw || typeof raw !== "object" || types.isProxy(raw) || Array.isArray(raw) || ![Object.prototype, null].includes(Object.getPrototypeOf(raw))) return undefined;
284
+ const snapshots: Record<string, unknown> = Object.create(null), keys = Reflect.ownKeys(raw);
285
+ if (keys.length > 5) return undefined;
286
+ for (const key of keys) {
287
+ if (typeof key !== "string" || !["task", "baselineContext", "dataPolicy", "systemPolicy", "improverContext"].includes(key)) return undefined;
288
+ const descriptor = Object.getOwnPropertyDescriptor(raw, key); if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) return undefined;
289
+ if (key === "dataPolicy") snapshots[key] = policy(inert(descriptor.value, GUIDANCE_PROBE_LIMITS.snapshotBytes));
290
+ else { const text = descriptor.value; required(typeof text === "string" && Buffer.byteLength(text) <= GUIDANCE_PROBE_LIMITS.snapshotBytes
291
+ && !/[\p{Cc}\p{Cs}]/u.test(text.replace(/[\t\r\n]/g, ""))); snapshots[key] = text; }
292
+ }
293
+ object(snapshots, ["task", "baselineContext", "dataPolicy", "systemPolicy"], ["improverContext"]);
294
+ required(Object.hasOwn(snapshots, "improverContext") === Object.hasOwn(parsed, "improverContextHash"));
295
+ let total = 0;
296
+ for (const key of ["task", "baselineContext", "dataPolicy", "systemPolicy", "improverContext"] as const) {
297
+ if (!Object.hasOwn(snapshots, key)) continue;
298
+ const text = key === "dataPolicy" ? guidanceProbeCanonical(snapshots[key]) : snapshots[key] as string;
299
+ const expected = key === "improverContext" ? { sha256: parsed.improverContextHash, bytes: parsed.improverContextBytes } : parsed.inputs[key];
300
+ required(Buffer.byteLength(text) === expected.bytes && probeHash(text) === expected.sha256); total += Buffer.byteLength(text);
301
+ }
302
+ required(total <= parsed.limits.inputBytes);
303
+ const result = { manifest: parsed, snapshots: snapshots as unknown as ProbePrivateSnapshots };
304
+ if (Buffer.byteLength(JSON.stringify(result)) > GUIDANCE_PROBE_REGISTRATION_BYTES) return undefined;
305
+ return result;
306
+ } catch { return undefined; }
307
+ }
308
+
309
+ export function parseGuidanceProbeCommand(args: readonly string[]): GuidanceProbeCommand | undefined {
310
+ const op = args[0]; if (!["register", "start", "show", "cancel"].includes(op ?? "")) return undefined;
311
+ const fields = new Map<string, string>(), allowed = op === "register" ? ["--file"] : op === "show" ? ["--id"] : op === "start" ? ["--id", "--revision", "--variant"] : ["--id", "--revision"];
312
+ let json = false;
313
+ for (let index = 1; index < args.length; index++) {
314
+ const key = args[index]!; if (key === "--json" && !json) { json = true; continue; }
315
+ const value = args[++index]; if (!allowed.includes(key) || fields.has(key) || !value || value.startsWith("--")) return undefined; fields.set(key, value);
316
+ }
317
+ if (op === "register") return fields.has("--file") ? { op, file: fields.get("--file")!, json } : undefined;
318
+ const id = fields.get("--id"); if (!probeSha256(id)) return undefined;
319
+ if (op === "show") return { op, id, json };
320
+ const raw = fields.get("--revision"), revision = raw && /^(?:0|[1-9][0-9]*)$/.test(raw) ? Number(raw) : NaN;
321
+ if (!probeInteger(revision)) return undefined;
322
+ if (op === "cancel") return { op, id, revision, json };
323
+ const variantId = fields.get("--variant"); if (variantId !== undefined && !probeSha256(variantId)) return undefined;
324
+ return { op: "start", id, revision, ...(variantId === undefined ? {} : { variantId }), json };
325
+ }
326
+ export function parseGuidanceProbeSubcommand(args: readonly string[]): GuidanceProbeCommand | undefined {
327
+ if (args[0] !== "probe") return undefined;
328
+ return parseGuidanceProbeCommand(args.slice(1)) ?? invalid();
329
+ }
330
+
331
+ const probeStates: readonly ProbeState[] = ["declared", "active", "closing", "closed_fixture", "failed_fixture", "unknown_held"];
332
+ const publicEvidence = (value: unknown): value is ProbePublicReceipt["evidence"] => ["declaration", "fixture", "unknown"].includes(value as string);
333
+ function publicReceipt(value: unknown, status: boolean): ProbePublicReceipt | ProbePublicStatus | undefined {
334
+ try {
335
+ const extra = status ? ["counters", "cancelRequested", "notNeeded", "comparable", "authoring"] : [];
336
+ const fields = object(value, ["id", "revision", "state", "already", "taskId", "experimentId", "evidence", ...extra]);
337
+ required(probeSha256(fields.id) && probeInteger(fields.revision) && probeStates.includes(fields.state as ProbeState)
338
+ && typeof fields.already === "boolean" && probeInteger(fields.taskId) && fields.taskId > 0
339
+ && typeof fields.experimentId === "string" && fields.experimentId.length <= 256 && publicEvidence(fields.evidence));
340
+ if (!status) return fields as unknown as ProbePublicReceipt;
341
+ const counters = object(fields.counters, ["workerAttempts", "editorAttempts", "modelCalls", "toolCalls", "tokensReserved", "tokensObservedKnown",
342
+ "inputBytes", "scratchBytes", "outputBytes", "elapsedHighWaterMs", "usageUnknown"]);
343
+ required(Object.entries(counters).every(([key, item]) => key === "usageUnknown" ? typeof item === "boolean" : probeInteger(item))
344
+ && typeof fields.cancelRequested === "boolean" && probeInteger(fields.notNeeded) && typeof fields.comparable === "boolean"
345
+ && ["admitted_fixture", "uncontrolled", "unknown"].includes(fields.authoring as string));
346
+ return fields as unknown as ProbePublicStatus;
347
+ } catch { return undefined; }
348
+ }
349
+ export const parseGuidanceProbePublicReceipt = (value: unknown): ProbePublicReceipt | undefined => publicReceipt(value, false) as ProbePublicReceipt | undefined;
350
+ export const parseGuidanceProbePublicStatus = (value: unknown): ProbePublicStatus | undefined => publicReceipt(value, true) as ProbePublicStatus | undefined;
351
+
352
+ /** Explicit worker-visible bytes; no host identity, arm label or improver side channel. */
353
+ export function guidanceProbeWorkerFrame(task: string, baselineContext: string, systemPolicy: string, guidance: string): string {
354
+ if ([task, baselineContext, systemPolicy].some(text => typeof text !== "string" || Buffer.byteLength(text) > GUIDANCE_PROBE_LIMITS.snapshotBytes)
355
+ || typeof guidance !== "string") return invalid();
356
+ return JSON.stringify({ task, baselineContext, systemPolicy, guidance });
357
+ }
358
+ export const guidanceProbeNonGuidanceInputHash = (task: string, baselineContext: string, systemPolicy: string): string => probeHash(JSON.stringify({ task, baselineContext, systemPolicy }));