@staix/agent-hub 0.37.0 → 0.39.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.
- package/CHANGELOG.md +55 -0
- package/README.md +17 -7
- package/docs/adding-an-ai-tool.md +6 -4
- package/docs/agent-notes/README.md +16 -0
- package/docs/agent-notes/adapters.md +4 -2
- package/docs/agent-notes/budget.md +8 -0
- package/docs/agent-notes/daemon.md +15 -8
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/security-review.md +55 -0
- package/docs/agent-notes/tasks.md +15 -4
- package/docs/agent-notes/tests.md +3 -2
- package/docs/design/adapters.md +51 -0
- package/docs/design/agent-hub-architecture.md +29 -1
- package/docs/design/guidance-probes.md +365 -0
- package/docs/design/task-board.md +151 -5
- package/docs/dogfood.md +22 -7
- package/docs/events.md +3 -3
- package/docs/memory.md +5 -5
- package/docs/operations.md +189 -32
- package/docs/profiles.md +101 -9
- package/docs/quickstart.md +38 -4
- package/docs/research.md +6 -3
- package/docs/roles.md +52 -0
- package/docs/sdlc.md +187 -1
- package/docs/security.md +56 -13
- package/docs/text-projection.md +1 -0
- package/docs/verification/2026-11-11-0.38.0.md +41 -0
- package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
- package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
- package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
- package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
- package/docs/verification/2026-11-14-0.39.0.md +51 -0
- package/docs/verified.json +48 -25
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +1989 -474
- package/plugins/agent-hub/server.js +2056 -512
- package/src/adapters/acp-model-policy.ts +1 -1
- package/src/adapters/acp-session-model.ts +35 -0
- package/src/adapters/acp.ts +14 -0
- package/src/adapters/agy/definition.ts +1 -1
- package/src/adapters/agy/hooks.ts +7 -0
- package/src/adapters/claude-channel.ts +3 -2
- package/src/adapters/claude-implementer.ts +8 -0
- package/src/adapters/claude-print-child.ts +26 -2
- package/src/adapters/claude-print.ts +4 -0
- package/src/adapters/codex-appserver.ts +90 -16
- package/src/adapters/codex-review-isolation.ts +2 -0
- package/src/adapters/compat.ts +4 -4
- package/src/adapters/conformance/fakes/acp-server.ts +11 -2
- package/src/adapters/conformance/fakes/app-server.ts +5 -1
- package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
- package/src/adapters/definitions/builtin-metadata.ts +6 -6
- package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
- package/src/adapters/definitions/native-quota.ts +122 -0
- package/src/adapters/definitions/native-recovery.ts +3 -0
- package/src/adapters/definitions/qwen.ts +1 -1
- package/src/adapters/kimi-review.ts +23 -0
- package/src/adapters/kimi-wire-usage.ts +39 -16
- package/src/adapters/local-probe.ts +65 -6
- package/src/adapters/local-worker.ts +6 -3
- package/src/adapters/pi-state-model.ts +12 -0
- package/src/adapters/pi.ts +22 -0
- package/src/adapters/print-result-model.ts +24 -0
- package/src/adapters/registry-types.ts +10 -1
- package/src/adapters/registry.ts +19 -2
- package/src/adapters/reviewer-print.ts +130 -15
- package/src/adapters/role-eligibility.ts +99 -0
- package/src/adapters/same-directory.ts +16 -0
- package/src/cli/agy-mcp.ts +18 -7
- package/src/cli/console-state.ts +3 -1
- package/src/cli/free-text.ts +20 -0
- package/src/cli/handoff-args.ts +1 -1
- package/src/cli/help.ts +61 -6
- package/src/cli/identity.ts +10 -4
- package/src/cli/init-prompt.ts +31 -2
- package/src/cli/init-roles.ts +156 -0
- package/src/cli/init-settings.ts +24 -2
- package/src/cli/init.ts +141 -17
- package/src/cli/main.ts +216 -56
- package/src/cli/model.ts +1 -1
- package/src/cli/output.ts +64 -5
- package/src/cli/preview.ts +1 -1
- package/src/cli/recovery-launch.ts +114 -0
- package/src/cli/recovery-package.ts +14 -7
- package/src/cli/recovery-version-preflight.ts +104 -0
- package/src/cli/role-doctor.ts +39 -0
- package/src/cli/sdlc-output.ts +66 -1
- package/src/cli/study-output.ts +54 -0
- package/src/cli/study.ts +14 -1
- package/src/cli/terminal-recovery.ts +14 -0
- package/src/cli/upgrade-presentation.ts +4 -0
- package/src/cli/upgrade-restore-state.ts +12 -3
- package/src/cli/upgrade-runtime.ts +41 -3
- package/src/cli/upgrade.ts +8 -4
- package/src/hub/advisor-survey.ts +139 -0
- package/src/hub/audit-source.ts +66 -0
- package/src/hub/board.ts +479 -14
- package/src/hub/budget.ts +54 -4
- package/src/hub/bus.ts +2 -2
- package/src/hub/conductor.ts +14 -8
- package/src/hub/config-apply.ts +2 -1
- package/src/hub/config-edit-host.ts +77 -5
- package/src/hub/considered-findings.ts +47 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +373 -66
- package/src/hub/deliverable-files.ts +17 -1
- package/src/hub/dogfood-profile.ts +3 -2
- package/src/hub/envelope.ts +6 -1
- package/src/hub/events.ts +23 -2
- package/src/hub/folder-trigger.ts +11 -4
- package/src/hub/guidance-probe-store.ts +345 -14
- package/src/hub/guidance-probes.ts +338 -4
- package/src/hub/hub-tools.ts +88 -16
- package/src/hub/kimi-usage.ts +34 -2
- package/src/hub/lifecycle-schema.ts +3 -3
- package/src/hub/manager.ts +24 -1
- package/src/hub/memory-profile.ts +9 -1
- package/src/hub/memory-sync-state.ts +1 -0
- package/src/hub/model-overrides.ts +2 -1
- package/src/hub/no-writes.ts +2 -0
- package/src/hub/operational-authority.ts +8 -2
- package/src/hub/operational-view.ts +5 -1
- package/src/hub/peers.ts +2 -0
- package/src/hub/person-command.ts +25 -0
- package/src/hub/plan-conformance.ts +20 -2
- package/src/hub/quota-account.ts +34 -0
- package/src/hub/recovery-policy.ts +18 -4
- package/src/hub/research-evidence.ts +51 -3
- package/src/hub/research.ts +77 -13
- package/src/hub/restart.ts +14 -0
- package/src/hub/review-budget.ts +88 -0
- package/src/hub/review-findings.ts +93 -12
- package/src/hub/reviewer-pool-config.ts +6 -2
- package/src/hub/reviewer-pool.ts +39 -6
- package/src/hub/routing.ts +7 -3
- package/src/hub/sdlc-merge.ts +1 -1
- package/src/hub/sdlc-queue.ts +14 -4
- package/src/hub/sdlc-release.ts +1 -1
- package/src/hub/sdlc.ts +10 -6
- package/src/hub/security-audit.ts +178 -0
- package/src/hub/security-pass.ts +115 -0
- package/src/hub/settings.ts +11 -5
- package/src/hub/source-read.ts +80 -2
- package/src/hub/sources.ts +57 -9
- package/src/hub/startup-event-seeds.ts +5 -3
- package/src/hub/startup-timing.ts +1 -0
- package/src/hub/supervision.ts +3 -2
- package/src/hub/synthesis-readiness.ts +279 -0
- package/src/hub/tasks.ts +1131 -72
- package/src/hub/text-projection.ts +11 -1
- package/src/local/probe-types.ts +2 -0
- package/src/local/probe-workspace.ts +191 -2
- package/src/memory/capture.ts +2 -1
- package/src/ui/guidance-panel.ts +34 -2
- package/src/ui/guidance-view.ts +33 -0
- package/src/ui/index.html +3 -0
- package/src/ui/office-model.ts +11 -3
- package/src/ui/office-space.ts +50 -30
- package/src/ui/plugin.ts +31 -14
- package/templates/AGENTS.block.md +14 -14
- package/templates/profiles/general.json +1 -1
- package/templates/profiles/research.json +1 -1
- package/templates/profiles/writing.json +1 -1
package/src/cli/output.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { ReviewGate, ReviewUnknownQuota } from "../hub/review-budget.ts";
|
|
2
|
+
import { quotaAccountReading } from "../hub/quota-account.ts";
|
|
1
3
|
import { projectModelStatus } from "./model.ts";
|
|
2
4
|
import type { RuntimeModelStatus } from "../hub/model-overrides.ts";
|
|
3
5
|
import type { QueueBackpressureStatus } from "../hub/queue-backpressure.ts";
|
|
@@ -13,6 +15,7 @@ import { schedulePeriodText, scheduleWhen } from "../hub/schedules.ts";
|
|
|
13
15
|
import { formatReport, formatTaskReport, type Report, type TaskReport } from "../hub/report.ts";
|
|
14
16
|
import type { Counter, LimitsResult, TotalResult, UsageResult } from "../hub/usage-rollup.ts";
|
|
15
17
|
import type { SpecsStatus } from "../hub/specs-task.ts";
|
|
18
|
+
import { queueResolveChoices, queueResolveCommand } from "../hub/person-command.ts";
|
|
16
19
|
|
|
17
20
|
export interface DoctorCheck { section: "Tools" | "Hub" | "Config" | "Models" | "Memory"; level: "ok" | "warn" | "fail" | "unknown"; name: string; detail: string }
|
|
18
21
|
export interface StatusOutput {
|
|
@@ -45,7 +48,7 @@ export interface StatusOutput {
|
|
|
45
48
|
tasks?: Record<string, number>; personRun?: number[]; models?: { backends?: any[] }; permissionDefaults?: any[]; deliveryError?: string; reviewInputHealth?: { state?: string; cause?: string | null }; crash?: string[];
|
|
46
49
|
}
|
|
47
50
|
/** `peers`: one note per peer that shows no number, and why (no quota, nothing read yet); absent from an older hub. */
|
|
48
|
-
export interface BudgetOutput { budget: Record<string, any>; gate?: number; peers?: { peer: string; kind?: string; note: string }[] }
|
|
51
|
+
export interface BudgetOutput { budget: Record<string, any>; gate?: number; review?: { gate: ReviewGate; unknown_quota: ReviewUnknownQuota; rule: string }; peers?: { peer: string; kind?: string; note: string }[] }
|
|
49
52
|
export interface RosterRow { peer: string; on: boolean; startMode: string; state: string; queued: number; tasks: number }
|
|
50
53
|
export function renderRuntimeModels(models: readonly RuntimeModelStatus[], columns?: number): Span[][] {
|
|
51
54
|
const out = rows(["PEER", "EFFECTIVE MODEL", "SOURCE", "STATE"], models.map(row => [span(row.peer, "info", true), span(row.effectiveModel ?? "not reported"), span(row.source), span(row.pendingNextTurn ? "pending next turn" : "current")]), columns);
|
|
@@ -58,6 +61,41 @@ export function renderRuntimeModels(models: readonly RuntimeModelStatus[], colum
|
|
|
58
61
|
export function renderRoster(data: RosterRow[], columns?: number): Span[][] {
|
|
59
62
|
return rows(["PEER", "ROSTER", "START", "STATE", "Q", "TASKS"], data.map(row => [span(row.peer, "info", true), span(row.on ? "on" : "off", row.on ? "success" : "muted", true), span(row.startMode, undefined, true), span(row.state, stateTone(row.state), true), span(row.queued, undefined, true), span(row.tasks, undefined, true)]), columns);
|
|
60
63
|
}
|
|
64
|
+
/** #1411 T2: who holds which flow role as the running hub settled them, from its status reply. */
|
|
65
|
+
export interface RolesView {
|
|
66
|
+
peers: { peer: string; roles: string[] }[];
|
|
67
|
+
planner: { peers: string[]; source: string } | null;
|
|
68
|
+
reviewFallback: { required: boolean; sameFamily: string } | null;
|
|
69
|
+
}
|
|
70
|
+
export function rolesView(status: any): RolesView {
|
|
71
|
+
const off = new Set((Array.isArray(status?.roster) ? status.roster : []).filter((row: any) => row?.on === false).map((row: any) => row.peer));
|
|
72
|
+
const info = status?.roleInfo && typeof status.roleInfo === "object" ? status.roleInfo : {};
|
|
73
|
+
const peers = Object.keys(info).filter(peer => !off.has(peer)).sort()
|
|
74
|
+
.map(peer => ({ peer, roles: Array.isArray(info[peer]?.flowRoles) ? info[peer].flowRoles.map(String) : [] }));
|
|
75
|
+
const planner = Array.isArray(status?.planner?.peers) ? { peers: status.planner.peers.map(String), source: String(status.planner.source ?? "unknown") } : null;
|
|
76
|
+
const fallback = status?.reviewFallback;
|
|
77
|
+
const reviewFallback = fallback && typeof fallback.required === "boolean" ? { required: fallback.required, sameFamily: String(fallback.sameFamily ?? "fallback") } : null;
|
|
78
|
+
return { peers, planner, reviewFallback };
|
|
79
|
+
}
|
|
80
|
+
/** Who reviews when no pool reviewer can run, as routing decides it (src/hub/routing.ts assign()); an older hub sends no settings, so unknown. */
|
|
81
|
+
function reviewFallbackLine(view: RolesView): string {
|
|
82
|
+
const fallback = view.reviewFallback;
|
|
83
|
+
if (!fallback || !view.planner) return "unknown: this hub does not report it; upgrade the running hub";
|
|
84
|
+
if (fallback.required && fallback.sameFamily !== "never") return "the person (review.pool is set)";
|
|
85
|
+
const planners = view.planner.peers.join(", ");
|
|
86
|
+
if (!planners) return "the person (no planner)";
|
|
87
|
+
return fallback.sameFamily === "never"
|
|
88
|
+
? `a planner of another family than the task's owner (${planners}), else the person`
|
|
89
|
+
: `a planner other than the task's owner (${planners}), another family first, else the person`;
|
|
90
|
+
}
|
|
91
|
+
export function renderRoles(view: RolesView, columns?: number): Span[][] {
|
|
92
|
+
return [
|
|
93
|
+
...rows(["PEER", "ROLES"], view.peers.map(row => [span(row.peer, peerTone(row.peer), true), span(row.roles.length ? row.roles.join(", ") : "-", row.roles.length ? undefined : "muted")]), columns),
|
|
94
|
+
[],
|
|
95
|
+
...lines(`planner: ${view.planner ? `${view.planner.peers.join(", ") || "nobody"} (${view.planner.source})` : "unknown"}`, columns),
|
|
96
|
+
...lines(`when no reviewer can run: ${reviewFallbackLine(view)}`, columns),
|
|
97
|
+
];
|
|
98
|
+
}
|
|
61
99
|
export function outputWidth(env: { isTTY: boolean; columns?: number; COLUMNS?: string }): number | undefined {
|
|
62
100
|
if (env.isTTY) return Math.max(80, Number.isFinite(env.columns) ? env.columns! : 80);
|
|
63
101
|
return env.COLUMNS && /^[1-9][0-9]*$/.test(env.COLUMNS) && Number.isSafeInteger(Number(env.COLUMNS)) ? Number(env.COLUMNS) : undefined;
|
|
@@ -328,7 +366,7 @@ export function renderStatus(data: StatusOutput, columns?: number, now = Date.no
|
|
|
328
366
|
for (const row of p.heldRows) out.push(...detail("held", `${id}: needs_review ${shortId(row.id, columns, full)}; from ${row.senders.join(",")}; kind ${row.kinds.join(",")}; age ${duration(Math.max(0, now - row.createdAt))}${row.context ? `; ${row.context}` : ""}; ahub queue show ${row.id}`, columns, "failure"));
|
|
329
367
|
} else if (p.heldBy) {
|
|
330
368
|
const note = flat(p.holdNote ?? "");
|
|
331
|
-
const command =
|
|
369
|
+
const command = `${queueResolveCommand({ id: p.heldBy, peer: id, state: "needs_review" })} (${queueResolveChoices("needs_review")})`;
|
|
332
370
|
const normalized = note.startsWith(`held by needs_review ${p.heldBy}`)
|
|
333
371
|
? note.replace(`held by needs_review ${p.heldBy}`, `by needs_review ${shortId(p.heldBy, columns, full)}`)
|
|
334
372
|
: `${shortId(p.heldBy, columns, full)}${note ? `: ${note}` : ""}`;
|
|
@@ -462,6 +500,7 @@ export function renderBoard(tasks: any[], columns?: number, now = Date.now(), fu
|
|
|
462
500
|
}
|
|
463
501
|
export function renderBudget(data: BudgetOutput, columns?: number, now = Date.now(), _full = false): Span[][] {
|
|
464
502
|
const out: Span[][] = [];
|
|
503
|
+
if (data.review) out.push(...detail("Reviewer admission", data.review.rule, columns));
|
|
465
504
|
// KIND names what the number is (#285): the provider's own (native), tokens the hub counted against a ceiling (count), or a person's (manual).
|
|
466
505
|
// A window without a kind, from an older hub, is classified by `windowKind`. A fresh window that does not gate says so in STATE.
|
|
467
506
|
const windows = Object.entries(data.budget).flatMap(([peer, b]) => (b.windows ?? []).map((w: any) => [span(peer, peerTone(peer)), span(w.id), span(`${Math.round(w.used * 100)}%`, "number"), span(typeof w.resetsAt === "number" ? relative(w.resetsAt, now) : "-", "muted"), span(windowKind({ id: w.id, source: w.source ?? "", kind: w.kind }), "muted"), span(w.source ?? "unknown", "muted"), span(typeof w.at === "number" ? relative(w.at, now) : "unknown", "muted"), span(w.stale ? "stale" : w.superseded ? "info only" : "fresh", w.stale ? "attention" : undefined)]));
|
|
@@ -470,6 +509,23 @@ export function renderBudget(data: BudgetOutput, columns?: number, now = Date.no
|
|
|
470
509
|
// A peer with no number says why, in its own line, so a peer without quota is not mistaken for one that has not reported.
|
|
471
510
|
for (const note of data.peers ?? []) out.push(...detail(note.peer, note.note, columns, peerTone(note.peer)));
|
|
472
511
|
for (const [peer, b] of Object.entries(data.budget)) if (b.paused) out.push(...detail(`paused ${peer}`, `${b.paused.reason ?? "budget"}${typeof b.paused.resetsAt === "number" ? `; resumes ${relative(b.paused.resetsAt, now)}` : ""}`, columns, "attention"));
|
|
512
|
+
for (const [peer, b] of Object.entries(data.budget)) {
|
|
513
|
+
const info = b.paused ? quotaAccountReading(b.accountUsage) : undefined;
|
|
514
|
+
if (!info) continue;
|
|
515
|
+
const parts: string[] = [];
|
|
516
|
+
if (info.resetCreditsAvailable !== undefined) {
|
|
517
|
+
const expiry = info.resetCreditsExpireAt !== undefined ? `expires ${new Date(info.resetCreditsExpireAt).toISOString().split("T")[0]}`
|
|
518
|
+
: info.resetCreditsExpiryKnown ? "no expiry" : "expiry unknown";
|
|
519
|
+
parts.push(`${plural(info.resetCreditsAvailable, "reset credit")} available${info.resetCreditsAvailable ? ` (${expiry})` : ""}`);
|
|
520
|
+
}
|
|
521
|
+
parts.push(info.ordinaryUsageAllowed === undefined ? "ordinary usage unknown" : info.ordinaryUsageAllowed ? "ordinary usage allowed" : "ordinary usage not allowed");
|
|
522
|
+
const flag = (value: boolean | undefined) => value === undefined ? "unknown" : value ? "yes" : "no";
|
|
523
|
+
parts.push(`credits available: ${flag(info.hasCredits)}`, `unlimited credits: ${flag(info.unlimited)}`);
|
|
524
|
+
if (info.stale) parts.push("stale snapshot");
|
|
525
|
+
else if (info.ordinaryUsageAllowed === false && (info.hasCredits === true || info.unlimited === true)) parts.push("turns would use paid credits");
|
|
526
|
+
out.push(...detail(peer, parts.join("; "), columns, "attention"));
|
|
527
|
+
}
|
|
528
|
+
|
|
473
529
|
return out;
|
|
474
530
|
}
|
|
475
531
|
function boardColumnContext(tasks: any[], allTasks: any[] | null): any[] {
|
|
@@ -591,14 +647,17 @@ function fields(value: unknown, columns: number | undefined, now: number, prefix
|
|
|
591
647
|
visit(value, prefix, prefix);
|
|
592
648
|
return rows(["FIELD", "VALUE"], leaves, columns);
|
|
593
649
|
}
|
|
594
|
-
export function renderQueueShow(delivery: any, columns?: number, now = Date.now()): Span[][] {
|
|
650
|
+
export function renderQueueShow(delivery: any, columns?: number, now = Date.now(), project?: string): Span[][] {
|
|
651
|
+
// #1399: the resolve line runs as printed: id, revision, a suggested action, a prefilled reason and the project that hosts the hub.
|
|
652
|
+
const messages: any[] = Array.isArray(delivery?.messages) ? delivery.messages : [];
|
|
653
|
+
const hint = () => queueResolveCommand({ id: delivery.id, revision: delivery.revision, state: delivery.state, peer: delivery.peer, senders: messages.map(m => String(m?.from ?? "")), kinds: messages.map(m => String(m?.kind ?? "")) }, project);
|
|
595
654
|
const out = [...lines("Delivery", columns, "strong"), ...fields(delivery, columns, now)];
|
|
596
655
|
if (delivery?.state === "failed" && delivery.failureCause === undefined) out.push(...detail("failure cause", "unknown (not recorded by this hub version)", columns, "muted"));
|
|
597
|
-
if (delivery?.state === "needs_review" && delivery.id) out.push([], ...detail("resolve",
|
|
656
|
+
if (delivery?.state === "needs_review" && delivery.id) out.push([], ...detail("resolve", `${hint()} (${queueResolveChoices("needs_review")})`, columns, "failure"));
|
|
598
657
|
// #1096: a failed row that no one has settled can be cleared by the person or the conductor; one a resolution already settled says what is left (nothing).
|
|
599
658
|
else if (delivery?.state === "failed" && delivery.id) {
|
|
600
659
|
if (delivery.resolvedBy) out.push([], ...detail("resolve", `already resolved by ${delivery.resolvedBy}; nothing is left to do for this row${delivery.resolvedBy === "retry" ? " (its redelivery is a separate delivery: ahub queue list)" : ""}`, columns, "muted"));
|
|
601
|
-
else out.push([], ...detail("resolve",
|
|
660
|
+
else out.push([], ...detail("resolve", `${hint()} (${queueResolveChoices("failed")}; the person or the conductor)`, columns, "failure"));
|
|
602
661
|
}
|
|
603
662
|
return out;
|
|
604
663
|
}
|
package/src/cli/preview.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { relayModelIds } from "../models/relay.ts";
|
|
|
10
10
|
import { buildPiLaunch } from "../pi/launch.ts";
|
|
11
11
|
|
|
12
12
|
/** Read-only builtin preview. Native redaction uses the same launch builders as actual startup. */
|
|
13
|
-
export function launcherPreview(tool:
|
|
13
|
+
export function launcherPreview(tool: string, raw: string[], cwd: string, stateDir: string, unattended: boolean, requestedInstance?: string) {
|
|
14
14
|
const config = loadConfig(cwd);
|
|
15
15
|
const selected = instanceLaunchArguments(tool, requestedInstance ? ["--as", requestedInstance, ...raw] : raw, config.instances);
|
|
16
16
|
const args = selected.args.filter(arg => !["--print-command", "--dry-run", "--json"].includes(arg));
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { constants, closeSync, fstatSync, linkSync, mkdtempSync, openSync, readSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { format } from "node:util";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { looksSecret } from "@staix/agent-mem";
|
|
7
|
+
import { loadConfig } from "../hub/daemon.ts";
|
|
8
|
+
import { loadRouting, detectSignals } from "../hub/routing.ts";
|
|
9
|
+
import { mentionsPrivatePath } from "../hub/memory-policy.ts";
|
|
10
|
+
import { sanitize } from "../hub/envelope.ts";
|
|
11
|
+
import { terminalText } from "./console-state.ts";
|
|
12
|
+
import { shellQuote } from "./shell-quote.ts";
|
|
13
|
+
|
|
14
|
+
export class RecoveryLaunchError extends Error {
|
|
15
|
+
constructor(readonly peer: string, readonly failure: RecoveryLaunchFailure, resume: string) { super(`${peer}: restoration launch ${failure.code} (exit ${failure.exitCode}): ${failure.firstLine}; fix the cause, then ${resume}`); }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RecoveryLaunchFailure {
|
|
19
|
+
code: "version_refused" | "launch_exit";
|
|
20
|
+
exitCode: number;
|
|
21
|
+
firstLine: string;
|
|
22
|
+
}
|
|
23
|
+
interface Capture { file: string; nonce: string; peer: string }
|
|
24
|
+
const CAPTURE_BYTES = 2048;
|
|
25
|
+
const OUTCOME_BYTES = 8192;
|
|
26
|
+
const LINE_POINTS = 512;
|
|
27
|
+
|
|
28
|
+
/** Existing private attempt directory only: never recreate it after the reader has disposed it. */
|
|
29
|
+
function publish(capture: Capture, exitCode: number, firstLine: string, complete: boolean): void {
|
|
30
|
+
if (!Number.isInteger(exitCode) || exitCode <= 0 || exitCode > 255) return;
|
|
31
|
+
const temp = `${capture.file}.${process.pid}.tmp`;
|
|
32
|
+
try {
|
|
33
|
+
writeFileSync(temp, JSON.stringify({ schemaVersion: 1, nonce: capture.nonce, peer: capture.peer, exitCode, firstLine, complete }), { flag: "wx", mode: 0o600 });
|
|
34
|
+
linkSync(temp, capture.file); // first complete producer wins, without replacing any existing inode
|
|
35
|
+
} catch { /* Capture is optional; a closed/ready attempt must not create new files. */ }
|
|
36
|
+
finally { try { unlinkSync(temp); } catch { /* absent or already disposed */ } }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Preloaded only in the hub CLI child, not its native child. TTY descriptors/properties stay unchanged. */
|
|
40
|
+
export function captureLaunchExit(capture: Capture): void {
|
|
41
|
+
let first = Buffer.alloc(0), complete = false;
|
|
42
|
+
const collect = (bytes: Buffer) => {
|
|
43
|
+
if (complete || first.length >= CAPTURE_BYTES) return;
|
|
44
|
+
const newline = bytes.indexOf(10), end = newline < 0 ? bytes.length : newline;
|
|
45
|
+
const remaining = CAPTURE_BYTES - first.length;
|
|
46
|
+
first = Buffer.concat([first, bytes.subarray(0, Math.min(end, remaining))]);
|
|
47
|
+
complete = newline >= 0 && end <= remaining;
|
|
48
|
+
};
|
|
49
|
+
// Bun's console writes directly to the descriptor, bypassing stderr.write.
|
|
50
|
+
const error = console.error.bind(console);
|
|
51
|
+
console.error = (...args: any[]) => { try { collect(Buffer.from(format(...args) + "\n")); } catch { /* original console behavior below */ } error(...args); };
|
|
52
|
+
const write = process.stderr.write.bind(process.stderr);
|
|
53
|
+
process.stderr.write = function(chunk: any, ...args: any[]) {
|
|
54
|
+
collect(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk instanceof Uint8Array ? chunk : String(chunk)));
|
|
55
|
+
return (write as (...parts: any[]) => boolean)(chunk, ...args);
|
|
56
|
+
} as typeof process.stderr.write;
|
|
57
|
+
process.once("exit", code => publish(capture, code, first.toString("utf8"), complete));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function screenedLine(raw: string, complete: boolean, cwd: string): string {
|
|
61
|
+
const withheld = "launch diagnostic unavailable or withheld by privacy policy; inspect the launch terminal";
|
|
62
|
+
if (!complete || raw.includes("�")) return withheld;
|
|
63
|
+
try {
|
|
64
|
+
const routing = loadRouting(cwd), config = loadConfig(cwd);
|
|
65
|
+
if (routing.signals.pii_screen !== "off" || looksSecret(raw)
|
|
66
|
+
|| detectSignals({ title: raw, detail: "", refs: {} }, routing, cwd).includes("pii")
|
|
67
|
+
|| mentionsPrivatePath(raw, [], config.pii?.paths ?? [], cwd)) return withheld;
|
|
68
|
+
return Array.from(sanitize(terminalText(raw)).replace(/[\p{Cc}\p{Cf}]/gu, " ").trim()).slice(0, LINE_POINTS).join("") || withheld;
|
|
69
|
+
} catch { return withheld; }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Bounded no-follow read; an outcome is diagnostic only, never proof of ownership or readiness. */
|
|
73
|
+
function readOutcome(capture: Capture, cwd: string): RecoveryLaunchFailure | undefined {
|
|
74
|
+
let fd: number | undefined;
|
|
75
|
+
try {
|
|
76
|
+
fd = openSync(capture.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
77
|
+
const stat = fstatSync(fd);
|
|
78
|
+
if (!stat.isFile() || stat.size > OUTCOME_BYTES) return;
|
|
79
|
+
const bytes = Buffer.alloc(OUTCOME_BYTES + 1), count = readSync(fd, bytes);
|
|
80
|
+
if (count > OUTCOME_BYTES) return;
|
|
81
|
+
const row = JSON.parse(bytes.subarray(0, count).toString("utf8"));
|
|
82
|
+
if (row?.schemaVersion !== 1 || row.nonce !== capture.nonce || row.peer !== capture.peer
|
|
83
|
+
|| !Number.isInteger(row.exitCode) || row.exitCode <= 0 || row.exitCode > 255
|
|
84
|
+
|| typeof row.firstLine !== "string" || Buffer.byteLength(row.firstLine) > CAPTURE_BYTES || typeof row.complete !== "boolean"
|
|
85
|
+
|| Object.keys(row).some(key => !["schemaVersion", "nonce", "peer", "exitCode", "firstLine", "complete"].includes(key))) return;
|
|
86
|
+
const firstLine = screenedLine(row.firstLine, row.complete, cwd);
|
|
87
|
+
const version = row.complete && /^(?:ahub: )?Version not verified: /.test(row.firstLine);
|
|
88
|
+
return { code: version ? "version_refused" : "launch_exit", exitCode: row.exitCode, firstLine };
|
|
89
|
+
} catch { return; }
|
|
90
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function prepareRecoveryLaunch(stateDir: string, peer: string, argv: readonly string[], env: Record<string, string>, cwd: string) {
|
|
94
|
+
if (argv.length < 2) throw new Error("restoration launch argv is missing; inspect the operation before resuming");
|
|
95
|
+
const dir = mkdtempSync(join(stateDir, "restore-launch-"));
|
|
96
|
+
const capture: Capture = { file: join(dir, "outcome.json"), nonce: randomUUID(), peer };
|
|
97
|
+
const module = fileURLToPath(import.meta.url), preload = join(dir, "capture.ts");
|
|
98
|
+
try {
|
|
99
|
+
writeFileSync(preload, `import { captureLaunchExit } from ${JSON.stringify(module)}; captureLaunchExit(${JSON.stringify(capture)});\n`, { flag: "wx", mode: 0o600 });
|
|
100
|
+
const prefix = ["env", ...Object.entries(env).map(([key, value]) => `${key}=${value}`)];
|
|
101
|
+
const launch = [...prefix, argv[0]!, "--preload", preload, ...argv.slice(1)].map(shellQuote).join(" ");
|
|
102
|
+
const record = [...prefix, process.execPath, module, JSON.stringify(capture), "--exit-code"].map(shellQuote).join(" ");
|
|
103
|
+
// A shell status observation adds no long-lived proxy or pipe to the native TTY.
|
|
104
|
+
const invoke = `ahub_restore_launch_${capture.nonce.replaceAll("-", "")}`;
|
|
105
|
+
const command = `${invoke}() { "$@"; ahub_restore_exit=$?; if [ "$ahub_restore_exit" -ne 0 ]; then ${record} "$ahub_restore_exit"; fi; return "$ahub_restore_exit"; }; ${invoke} ${launch}`;
|
|
106
|
+
return { command, read: () => readOutcome(capture, cwd), dispose: () => rmSync(dir, { recursive: true, force: true }) };
|
|
107
|
+
} catch (error) { rmSync(dir, { recursive: true, force: true }); throw error; }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (import.meta.main) {
|
|
111
|
+
const [raw, marker, status] = process.argv.slice(2);
|
|
112
|
+
if (!raw || marker !== "--exit-code" || !status || !/^[0-9]+$/.test(status)) throw new Error("invalid private restoration launch outcome");
|
|
113
|
+
publish(JSON.parse(raw) as Capture, Number(status), "", false);
|
|
114
|
+
}
|
|
@@ -7,23 +7,30 @@ import { hubHome, realPath } from "../hub/project.ts";
|
|
|
7
7
|
import { Registry } from "../hub/registry.ts";
|
|
8
8
|
|
|
9
9
|
export type CommandResult = { code: number; stdout: string; stderr: string };
|
|
10
|
-
export type RunCommand = (args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }) => Promise<CommandResult>;
|
|
10
|
+
export type RunCommand = (args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; input?: string; pipeExitGraceMs?: number }) => Promise<CommandResult>;
|
|
11
11
|
export const runCommand: RunCommand = (args, options = {}) => new Promise((resolve, reject) => {
|
|
12
|
-
const child = spawn(args[0]!, args.slice(1), { cwd: options.cwd, env: options.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
12
|
+
const child = spawn(args[0]!, args.slice(1), { cwd: options.cwd, env: options.env, stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"] });
|
|
13
|
+
if (options.input !== undefined) { child.stdin?.on("error", () => {}); child.stdin?.end(options.input); }
|
|
13
14
|
let stdout = "", stderr = "", exceeded = false;
|
|
14
15
|
const append = (old: string, value: unknown) => {
|
|
15
16
|
const next = old + String(value);
|
|
16
17
|
if (next.length > 2_000_000) { exceeded = true; child.kill("SIGTERM"); }
|
|
17
18
|
return next.slice(-2_000_000);
|
|
18
19
|
};
|
|
19
|
-
child.stdout
|
|
20
|
-
child.stderr
|
|
21
|
-
let timedOut = false;
|
|
20
|
+
child.stdout!.on("data", (v) => { stdout = append(stdout, v); });
|
|
21
|
+
child.stderr!.on("data", (v) => { stderr = append(stderr, v); });
|
|
22
|
+
let timedOut = false, incomplete = false;
|
|
23
|
+
let exitGrace: ReturnType<typeof setTimeout> | undefined;
|
|
24
|
+
// ponytail: a probe descendant may retain a pipe after exit; close bounded readers without signaling an unproven descendant. Upgrade: owned process-group proof, as for native probes.
|
|
25
|
+
if (options.pipeExitGraceMs !== undefined) child.once("exit", () => {
|
|
26
|
+
exitGrace = setTimeout(() => { incomplete = true; child.stdout?.destroy(); child.stderr?.destroy(); }, options.pipeExitGraceMs);
|
|
27
|
+
});
|
|
22
28
|
const timer = setTimeout(() => { timedOut = true; child.kill("SIGTERM"); }, options.timeoutMs ?? 60_000);
|
|
23
29
|
const hardTimer = setTimeout(() => child.kill("SIGKILL"), (options.timeoutMs ?? 60_000) + 3000);
|
|
24
|
-
child.on("error", (e) => { clearTimeout(timer); clearTimeout(hardTimer); reject(e); });
|
|
30
|
+
child.on("error", (e) => { clearTimeout(timer); clearTimeout(hardTimer); clearTimeout(exitGrace); reject(e); });
|
|
25
31
|
child.on("close", (code) => {
|
|
26
|
-
clearTimeout(timer); clearTimeout(hardTimer);
|
|
32
|
+
clearTimeout(timer); clearTimeout(hardTimer); clearTimeout(exitGrace);
|
|
33
|
+
if (incomplete) return reject(new Error("command output remained open after its process exited; inspect the executable before retrying"));
|
|
27
34
|
if (timedOut || exceeded) reject(new Error(`command ${args[0]} ${timedOut ? "timed out" : "exceeded output limit"}; inspect state before retrying`));
|
|
28
35
|
else resolve({ code: code ?? 1, stdout, stderr });
|
|
29
36
|
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { isAbsolute, join } from "node:path";
|
|
2
|
+
import type { CompatId } from "../adapters/compat.ts";
|
|
3
|
+
import type { AdapterDefinition } from "../adapters/registry-types.ts";
|
|
4
|
+
import { childEnv } from "../hub/child-process.ts";
|
|
5
|
+
import { withoutOrcaEnv } from "../hub/orca-env.ts";
|
|
6
|
+
import type { RunCommand } from "./recovery-package.ts";
|
|
7
|
+
import type { PlannedProject } from "./upgrade.ts";
|
|
8
|
+
|
|
9
|
+
/** Host-selected native launch gates, never inferred from a peer's spelling or a reviewer policy. */
|
|
10
|
+
export interface RecoveryVersionGate { peer: string; compatId: CompatId; command?: readonly string[] }
|
|
11
|
+
export interface RecoveryVersionObservation {
|
|
12
|
+
peer: string;
|
|
13
|
+
compatId: CompatId;
|
|
14
|
+
state: "accepted" | "refused" | "unknown";
|
|
15
|
+
version?: string;
|
|
16
|
+
/** Fixed guidance only: never native output, executable paths or target exception text. */
|
|
17
|
+
message: string;
|
|
18
|
+
}
|
|
19
|
+
export interface RecoveryVersionPorts {
|
|
20
|
+
run: RunCommand;
|
|
21
|
+
/** The caller revalidates the verified target root/digest and its own authority across awaits. */
|
|
22
|
+
current(): boolean;
|
|
23
|
+
}
|
|
24
|
+
const MAX_GATES = 64;
|
|
25
|
+
const MAX_OUTPUT_BYTES = 64 * 1024;
|
|
26
|
+
const PROBE_TIMEOUT_MS = 10_000;
|
|
27
|
+
const PROBE_EXIT_GRACE_MS = 250;
|
|
28
|
+
const PEER = /^[a-z][a-z0-9_-]{0,63}$/;
|
|
29
|
+
const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
30
|
+
|
|
31
|
+
/** The caller supplies its startup-bound project resolver and current configured executable argv. */
|
|
32
|
+
export function recoveryVersionGates(
|
|
33
|
+
planned: PlannedProject,
|
|
34
|
+
definition: (peer: string) => AdapterDefinition | undefined,
|
|
35
|
+
commands: Partial<Record<CompatId, readonly string[]>> = {},
|
|
36
|
+
): RecoveryVersionGate[] {
|
|
37
|
+
const gates: RecoveryVersionGate[] = [], seen = new Set<string>();
|
|
38
|
+
for (const peer of planned.source.peers) {
|
|
39
|
+
if (peer.state === "offline" || planned.reconnectOnly?.includes(peer.id) || seen.has(peer.id)) continue;
|
|
40
|
+
seen.add(peer.id);
|
|
41
|
+
const adapter = definition(peer.id), compatId = adapter?.session.restoreVersionGate;
|
|
42
|
+
if (!adapter || !compatId || adapter.session.recoveryRefusal?.(peer, "plan")) continue;
|
|
43
|
+
if (gates.length >= MAX_GATES) throw new Error("recovery version preflight has too many native gates");
|
|
44
|
+
gates.push({ peer: peer.id, compatId, ...(commands[compatId] ? { command: [...commands[compatId]!] } : {}) });
|
|
45
|
+
}
|
|
46
|
+
return gates;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const plain = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
50
|
+
const words = (value: unknown): value is string[] => Array.isArray(value) && value.length > 0 && value.length <= 32
|
|
51
|
+
&& value.every(word => typeof word === "string" && word.length > 0 && word.length <= 4096 && !/[\p{Cc}\p{Cf}]/u.test(word));
|
|
52
|
+
const unknown = (gate: RecoveryVersionGate): RecoveryVersionObservation => ({ peer: gate.peer, compatId: gate.compatId, state: "unknown",
|
|
53
|
+
message: `${gate.peer}: target version acceptance is unknown; check its configured executable and the target's ahub agents policy before restoring it` });
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Read an already verified target's own policy, probe only the selected executable, then assess with that target's current machine trust.
|
|
57
|
+
* No result is cached or grants startup authority. The caller must run this again before pre-commit effects, including cached staging.
|
|
58
|
+
* Every command crosses the injected port; synthetic tests never execute a native CLI or import an arbitrary target in this process.
|
|
59
|
+
*/
|
|
60
|
+
export async function readRecoveryVersionPreflight(
|
|
61
|
+
targetRoot: string,
|
|
62
|
+
projectRoot: string,
|
|
63
|
+
gates: readonly RecoveryVersionGate[],
|
|
64
|
+
ports: RecoveryVersionPorts,
|
|
65
|
+
): Promise<RecoveryVersionObservation[]> {
|
|
66
|
+
if (!isAbsolute(targetRoot) || !isAbsolute(projectRoot) || !Array.isArray(gates) || gates.length > MAX_GATES
|
|
67
|
+
|| gates.some(gate => !PEER.test(gate.peer) || !/^[a-z][a-z0-9-]{0,63}$/.test(gate.compatId)
|
|
68
|
+
|| gate.command !== undefined && !words(gate.command))) throw new Error("invalid recovery version preflight scope");
|
|
69
|
+
const module = JSON.stringify(join(targetRoot, "src/adapters/compat.ts"));
|
|
70
|
+
const env = withoutOrcaEnv(childEnv({ ...process.env, JCODE_NO_TELEMETRY: "1", JCODE_DISABLE_CLAUDE_MCP: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "1" }));
|
|
71
|
+
const run = async (argv: string[], input?: string) => {
|
|
72
|
+
if (!ports.current()) throw new Error("recovery version preflight authority changed");
|
|
73
|
+
const result = await ports.run(argv, { cwd: projectRoot, env, timeoutMs: PROBE_TIMEOUT_MS, pipeExitGraceMs: PROBE_EXIT_GRACE_MS, ...(input === undefined ? {} : { input }) });
|
|
74
|
+
if (!ports.current()) throw new Error("recovery version preflight authority changed");
|
|
75
|
+
if (result.code !== 0 || typeof result.stdout !== "string" || Buffer.byteLength(result.stdout) > MAX_OUTPUT_BYTES) return undefined;
|
|
76
|
+
return result.stdout;
|
|
77
|
+
};
|
|
78
|
+
const results: RecoveryVersionObservation[] = [];
|
|
79
|
+
for (const gate of gates) {
|
|
80
|
+
let observation = unknown(gate);
|
|
81
|
+
try {
|
|
82
|
+
// This target import is allowed only after the caller verified the package's retained root and digest.
|
|
83
|
+
const policyText = await run([process.execPath, "-e", `// recovery-version-policy\nimport { COMPAT } from ${module}; const id = ${JSON.stringify(gate.compatId)}; const p = Object.hasOwn(COMPAT, id) ? COMPAT[id] : undefined; console.log(JSON.stringify(p ? { probe: p.probe } : null));`]);
|
|
84
|
+
const policy: unknown = policyText === undefined ? undefined : JSON.parse(policyText);
|
|
85
|
+
if (!plain(policy) || !words(policy.probe)) { results.push(observation); continue; }
|
|
86
|
+
const [executable, ...prefix] = gate.command ?? [policy.probe[0]!];
|
|
87
|
+
const native = await run([executable!, ...prefix, ...policy.probe.slice(1)]);
|
|
88
|
+
if (native === undefined) { results.push(observation); continue; }
|
|
89
|
+
const assessment = await run([process.execPath, "-e", `// recovery-version-assess\nimport { COMPAT, assessVersion, readTrust } from ${module}; const id = ${JSON.stringify(gate.compatId)}; const p = Object.hasOwn(COMPAT, id) ? COMPAT[id] : undefined; const observed = await Bun.stdin.text(); const v = p ? assessVersion(id, p.parse(observed), readTrust()) : undefined; console.log(JSON.stringify(v ? { ok: v.ok, state: v.state, version: v.version } : null));`], native);
|
|
90
|
+
const verdict: unknown = assessment === undefined ? undefined : JSON.parse(assessment);
|
|
91
|
+
if (plain(verdict) && typeof verdict.version === "string" && verdict.version.length <= 64 && SEMVER.test(verdict.version)) {
|
|
92
|
+
const version = verdict.version;
|
|
93
|
+
if (verdict.ok === true && ["verified", "trusted", "in-line"].includes(String(verdict.state))) observation = { ...observation, state: "accepted", version,
|
|
94
|
+
message: `${gate.peer}: target accepts installed version ${version}` };
|
|
95
|
+
else if (verdict.ok === false && verdict.state === "refused") observation = { ...observation, state: "refused", version,
|
|
96
|
+
message: `${gate.peer}: target refuses installed version ${version}; install a verified version, or accept this exact version on this machine with: ahub agents trust ${gate.compatId} ${version}` };
|
|
97
|
+
}
|
|
98
|
+
} catch { /* A failed policy/probe is unknown, never accepted or a leaked native exception. */ }
|
|
99
|
+
// A changed target or authority invalidates all earlier observations, not merely the final gate.
|
|
100
|
+
if (!ports.current()) return gates.map(unknown);
|
|
101
|
+
results.push(observation);
|
|
102
|
+
}
|
|
103
|
+
return ports.current() ? results : gates.map(unknown);
|
|
104
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { roleEligibility } from "../adapters/role-eligibility.ts";
|
|
2
|
+
import { conductorPeer } from "../hub/conductor.ts";
|
|
3
|
+
import type { StartMode } from "../hub/start-mode.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* #1408 R2: `ahub doctor`'s `roles` row. Pure: the caller passes what the loader settled (`roles`, after every ceiling), what the config declared before the ceilings, each peer's effective
|
|
7
|
+
* start mode and the roster. A warning, never a failure, like the other advisory rows: doctor's exit code stays what it was for a project that has not looked at this yet.
|
|
8
|
+
*/
|
|
9
|
+
export interface RolesRowInput {
|
|
10
|
+
/** `roles` after the loader's ceilings (what the hub holds). */
|
|
11
|
+
roles: Readonly<Record<string, readonly string[]>>;
|
|
12
|
+
/** The raw `roles` block of the config layers merged, before any ceiling, or undefined when none is declared. */
|
|
13
|
+
declared?: Readonly<Record<string, readonly string[]>>;
|
|
14
|
+
startMode: (peer: string) => StartMode | undefined;
|
|
15
|
+
rostered: (peer: string) => boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface RolesRow { ok: boolean | undefined; detail: string }
|
|
18
|
+
|
|
19
|
+
const holders = (roles: RolesRowInput["roles"], role: string, rostered: (peer: string) => boolean) => Object.keys(roles).filter(peer => roles[peer]!.includes(role) && rostered(peer)).sort();
|
|
20
|
+
|
|
21
|
+
export function rolesRow(input: RolesRowInput): RolesRow {
|
|
22
|
+
const conductor = conductorPeer(input.roles), planners = holders(input.roles, "planner", input.rostered), reviewers = holders(input.roles, "reviewer", input.rostered);
|
|
23
|
+
const warnings: string[] = [];
|
|
24
|
+
// A declared conductor that the loader dropped is the case the person most needs to hear about: nobody else holds the role.
|
|
25
|
+
let ignored: string | null = null;
|
|
26
|
+
try { ignored = input.declared ? conductorPeer(input.declared) : null; } catch { ignored = null; }
|
|
27
|
+
if (ignored && ignored !== conductor) {
|
|
28
|
+
const verdict = roleEligibility(ignored, "conductor", input.startMode(ignored));
|
|
29
|
+
warnings.push(`conductor ${ignored} is ignored${verdict.reason ? `: ${verdict.reason}` : ""}${verdict.fix ? `; ${verdict.fix}` : ""}`);
|
|
30
|
+
}
|
|
31
|
+
if (!planners.length) warnings.push("no rostered planner is eligible (the hub falls back to the first eligible rostered kind, or has none)");
|
|
32
|
+
if (!reviewers.length) warnings.push("no rostered reviewer can run: reviews go to the person");
|
|
33
|
+
else {
|
|
34
|
+
const unfit = reviewers.filter(peer => !roleEligibility(peer, "reviewer").eligible);
|
|
35
|
+
if (unfit.length) warnings.push(`${unfit.join(", ")} cannot receive hub_review`);
|
|
36
|
+
}
|
|
37
|
+
const text = `conductor ${conductor ?? "none (the person conducts from ahub console)"}; planner ${planners.join(", ") || "none"}; reviewer ${reviewers.join(", ") || "the person"}`;
|
|
38
|
+
return warnings.length ? { ok: undefined, detail: `${text}. ${warnings.join(". ")}` } : { ok: true, detail: text };
|
|
39
|
+
}
|
package/src/cli/sdlc-output.ts
CHANGED
|
@@ -5,6 +5,44 @@
|
|
|
5
5
|
import { duration, plural, relative, table, terminalText, wrap, type Span, type Tone } from "./console-state.ts";
|
|
6
6
|
|
|
7
7
|
type Line = Span[];
|
|
8
|
+
/** Configuration remains restart-bound; the claim is caller provenance, not inferred release consent. */
|
|
9
|
+
export function renderSdlcConfiguration(value: unknown, columns?: number): Span[][] {
|
|
10
|
+
const row = value as any;
|
|
11
|
+
const out = heading(list(row?.restartPending).length ? "SDLC configuration saved; restart pending" : "SDLC configuration saved", columns);
|
|
12
|
+
out.push(...pair("actor", row?.by ?? "unknown", columns, 12));
|
|
13
|
+
out.push(...pair("instruction", "person's explicit instruction claimed for this session", columns, 12));
|
|
14
|
+
for (const line of list(row?.lines)) out.push(...para(String(line), columns));
|
|
15
|
+
if (row?.backup) out.push(...pair("backup", row.backup, columns, 12));
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
/** Survey fields already passed the host's task and security disclosure policy. */
|
|
19
|
+
export function renderSdlcSurvey(value: unknown, columns?: number): Span[][] {
|
|
20
|
+
const row = value as any;
|
|
21
|
+
if (!row) return [[s("no advisor survey", "muted")]];
|
|
22
|
+
const out: Span[][] = [...heading(`Advisor survey, task ${row.task ?? "unknown"}`, columns)];
|
|
23
|
+
for (const field of ["survey", "ref", "focus"]) if (row[field] !== undefined) out.push(...pair(field, row[field], columns, 12));
|
|
24
|
+
if (row.withheld || row.status === "private") return [...out, [s("report withheld by current privacy", "attention")]];
|
|
25
|
+
for (const item of list(row.items)) {
|
|
26
|
+
const finding = item.finding ?? item;
|
|
27
|
+
out.push(...pair("finding", finding.id, columns, 12));
|
|
28
|
+
if (finding.withheld || item.withheld) { out.push(...pair("details", "withheld", columns, 12)); continue; }
|
|
29
|
+
for (const field of ["evidence", "impact", "effort", "risk", "confidence", "fix_sketch"]) if (finding[field] !== undefined) out.push(...pair(field, finding[field], columns, 12));
|
|
30
|
+
if (item.decision) out.push(...pair("decision", item.decision.verdict, columns, 12));
|
|
31
|
+
else if (item.verdict) out.push(...pair("decision", item.verdict, columns, 12));
|
|
32
|
+
if (item.rejectedBefore?.rejectedBefore || item.rejectedBefore === true) out.push(...pair("history", "rejected before", columns, 12, "attention"));
|
|
33
|
+
for (const rejected of list(item.rejected)) {
|
|
34
|
+
out.push(...pair("rejected before", rejected.id, columns, 16));
|
|
35
|
+
if (rejected.change === "unknown") out.push(...pair("change", "unknown (suppression retained)", columns, 16, "attention"));
|
|
36
|
+
if (!rejected.withheld && rejected.reason) out.push(...pair("reason", rejected.reason, columns, 16));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
for (const rejected of list(row.rejected)) {
|
|
40
|
+
out.push(...pair("rejected before", rejected.id, columns, 16));
|
|
41
|
+
if (rejected.status === "unknown" || rejected.change === "unknown") out.push(...pair("change", "unknown (suppression retained)", columns, 16, "attention"));
|
|
42
|
+
if (!rejected.withheld && rejected.reason) out.push(...pair("reason", rejected.reason, columns, 16));
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
8
46
|
export const s = (value: unknown, tone?: Tone): Span => ({ text: terminalText(value).replace(/[\n\t]/g, " "), ...(tone ? { tone } : {}) });
|
|
9
47
|
const room = (columns?: number) => columns ?? Infinity;
|
|
10
48
|
const list = (value: unknown): any[] => Array.isArray(value) ? value : [];
|
|
@@ -104,7 +142,7 @@ function taskBlock(row: any, columns: number | undefined, detail: boolean): Line
|
|
|
104
142
|
if (row.definition?.name || row.definition?.id) out.push(...pair("stage", row.definition.name ?? row.definition.id, columns, 11, undefined, " "));
|
|
105
143
|
out.push(...bullets("entry", list(row.entry), columns, undefined, " "), ...bullets("exit", list(row.exit), columns, undefined, " "));
|
|
106
144
|
const f = row.findings;
|
|
107
|
-
if (f) out.push(...pair("findings", `${plural(f.important ?? 0, "important")} (${f.openImportant ?? 0} open), ${plural(f.nit ?? 0, "nit")} (${f.openNit ?? 0} open), ${f.fixed ?? 0} fixed, ${f.falsePositive ?? 0} false positive, ${f.accepted ?? 0} accepted`, columns, 11, f.openImportant ? "attention" : undefined, " "));
|
|
145
|
+
if (f) out.push(...pair("findings", `${plural(f.important ?? 0, "important")} (${f.openImportant ?? 0} open), ${plural(f.nit ?? 0, "nit")} (${f.openNit ?? 0} open), ${f.fixed ?? 0} fixed, ${f.falsePositive ?? 0} false positive, ${f.accepted ?? 0} accepted${f.needsValidation ? `, ${f.needsValidation} needs validation (not blocking)` : ""}${f.preExisting ? `, ${f.preExisting} pre-existing (not blocking)` : ""}`, columns, 11, f.openImportant ? "attention" : undefined, " "));
|
|
108
146
|
const p = row.planConformance;
|
|
109
147
|
if (p) {
|
|
110
148
|
out.push(...pair("plan files", `${p.state}${p.accepted ? ", departure accepted" : ""}, ${list(p.outside).length} outside the plan, ${list(p.untouched).length} planned and untouched`, columns, 11, p.state === "departure" && !p.accepted ? "attention" : undefined, " "));
|
|
@@ -115,6 +153,13 @@ function taskBlock(row: any, columns: number | undefined, detail: boolean): Line
|
|
|
115
153
|
out.push(...pair("tests", `${t.applicability === "bug" ? "bug fix" : t.applicability === "not_bug" ? "not a bug fix" : "bug status unknown"}, red-first ${String(t.redFirst).replace("_", " ")}, files ${t.fileState}`, columns, 11, undefined, " "));
|
|
116
154
|
out.push(...bullets("modified tests", list(t.modifiedTests), columns, undefined, " "), ...bullets("test blockers", list(t.blockers), columns, "attention", " "));
|
|
117
155
|
}
|
|
156
|
+
const sp = row.securityPass;
|
|
157
|
+
if (sp) {
|
|
158
|
+
const shown = sp.state === "required" ? `required (${sp.matched} sensitive path${sp.matched === 1 ? "" : "s"} changed), none recorded at this head`
|
|
159
|
+
: sp.state === "recorded" ? `recorded at this head (${sp.recorded?.covered ?? 0} covered, ${sp.recorded?.notCovered ?? 0} not covered)`
|
|
160
|
+
: sp.state === "unknown" ? "unknown (PR file inventory incomplete or unreadable)" : "not required";
|
|
161
|
+
out.push(...pair("security pass", `${shown}${list(sp.companions).length ? `; companions ${list(sp.companions).join(", ")}` : ""}`, columns, 11, sp.state === "required" || sp.state === "unknown" ? "attention" : undefined, " "));
|
|
162
|
+
}
|
|
118
163
|
const e = row.evalGate;
|
|
119
164
|
if (e) {
|
|
120
165
|
const shown = e.state === "not_configured" ? "eval check not configured (suite choice pending the person)" : e.state === "coverage_unknown" ? "PR file coverage unknown" : `${e.check} ${String(e.state)}${e.passRate !== undefined ? `, pass rate ${e.passRate}` : ""}${e.suite !== undefined ? `, suite ${e.suite}` : ""}`;
|
|
@@ -164,6 +209,24 @@ export function renderSdlcQueue(reply: unknown, columns?: number, _now = Date.no
|
|
|
164
209
|
if (list(report.conflicts).length) out.push(blank, ...bullets("file conflicts", list(report.conflicts).map((c: any) => `#${c.left} and #${c.right} share ${plural(c.files ?? 0, "file")} (${c.order === "person_required" ? "the person orders them" : "dependency order"})`), columns, "attention"));
|
|
165
210
|
return out;
|
|
166
211
|
}
|
|
212
|
+
/** One line for the audit's unit states, shared by `audit show` and the release readback. */
|
|
213
|
+
function auditStates(a: any): string {
|
|
214
|
+
const c = a?.counts ?? {};
|
|
215
|
+
return `${c.covered ?? 0} covered${a?.prior ? ` (${a.prior} prior)` : ""}, ${c.deferred ?? 0} deferred, ${c.out_of_scope ?? 0} out of scope, ${c.planned ?? 0} planned`;
|
|
216
|
+
}
|
|
217
|
+
/** `ahub sdlc audit show`: the ledger's counts first, then each unit, then the findings. An open important finding shows its id and status only, unless the caller is the person. */
|
|
218
|
+
export function renderSdlcAudit(reply: unknown, columns?: number, _now = Date.now()): Span[][] {
|
|
219
|
+
const a = (reply as any)?.audit;
|
|
220
|
+
if (!a) return [...heading("Security audit", columns), ...pair("audits", "none started: run ahub sdlc audit start", columns, 10, "muted")];
|
|
221
|
+
const out: Line[] = [...heading(`Security audit ${a.audit} (task #${a.task})`, columns)];
|
|
222
|
+
out.push(...pair("source", `${short(a.ref)}, profile ${a.profile}${a.scoped ? ", scoped" : ""}`, columns, 10), ...pair("coverage", `${a.partial ? "partial: " : ""}${auditStates(a)}`, columns, 10, a.partial || a.counts?.planned ? "attention" : undefined));
|
|
223
|
+
const f = a.findings ?? {};
|
|
224
|
+
out.push(...pair("findings", `${f.verified ?? 0} verified, ${f.candidate ?? 0} candidate (unverified), ${f.needsValidation ?? 0} needs validation, ${f.rejected ?? 0} rejected, ${f.settled ?? 0} settled, ${f.other ?? 0} other`, columns, 10, f.candidate ? "attention" : undefined));
|
|
225
|
+
for (const u of list(a.units)) out.push(...pair(String(u.state).replace("_", " "), `${u.unit}${u.prior ? ` (prior audit ${u.prior.audit})` : ""}${u.reason ? `: ${u.reason}` : ""}`, columns, 14, u.state === "planned" ? "attention" : undefined, " "));
|
|
226
|
+
for (const item of list(a.items)) out.push(...pair(String(item.status), `${item.id} (${item.severity}, ${item.disposition})${item.withheld ? ", details withheld" : item.path ? ` ${item.path}` : ""}`, columns, 14, item.status === "candidate" ? "attention" : undefined, " "));
|
|
227
|
+
if (a.withheld) out.push(...pair("withheld", `${a.withheld} open important finding${a.withheld === 1 ? "" : "s"}: boundary text is shown to the person only`, columns, 10, "muted"));
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
167
230
|
/** `ahub sdlc release <repo> [live-issue...]`: source, document, issue and authorization evidence, then what blocks the release. */
|
|
168
231
|
export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.now()): Span[][] {
|
|
169
232
|
const r = (reply as any)?.report ?? {};
|
|
@@ -185,6 +248,8 @@ export function renderSdlcRelease(reply: unknown, columns?: number, now = Date.n
|
|
|
185
248
|
if (a) out.push(blank, ...pair("authorization", `${a.state}: version ${a.receipt?.version ?? "unknown"} at ${short(a.receipt?.commit)}, approved ${moment(a.receipt?.at, now)}`, columns, w, a.state === "matched" ? "success" : "attention"));
|
|
186
249
|
else out.push(blank, ...pair("authorization", r.releasePolicy ? `none recorded for ${r.releasePolicy.versionSource}: run ahub sdlc authorize-release <version>` : "none recorded: run ahub sdlc authorize-release <version>", columns, w, "muted"));
|
|
187
250
|
for (const t of list(r.trains)) out.push(...pair(`train #${t.release?.id ?? "?"}`, `${t.readiness?.trigger ?? "unknown"}${list(t.readiness?.blockers).length ? `, ${list(t.readiness.blockers).join("; ")}` : ""}`, columns, w, list(t.readiness?.blockers).length ? "attention" : undefined));
|
|
251
|
+
const sa = r.securityAudit;
|
|
252
|
+
if (sa) out.push(blank, ...pair("security audit", `${short(sa.ref)} ${sa.profile}${sa.partial ? " (partial)" : ""}: ${auditStates(sa)}${sa.findings?.candidate ? `, ${sa.findings.candidate} unverified candidate${sa.findings.candidate === 1 ? "" : "s"}` : ""}`, columns, w, sa.partial || sa.counts?.planned ? "attention" : undefined));
|
|
188
253
|
const rm = r.releaseMetrics;
|
|
189
254
|
if (rm) {
|
|
190
255
|
const mean = (values: unknown[]) => { const known = values.filter((v): v is number => typeof v === "number" && Number.isFinite(v)); return known.length ? span(known.reduce((a, b) => a + b, 0) / known.length) : "unknown"; };
|
package/src/cli/study-output.ts
CHANGED
|
@@ -125,3 +125,57 @@ export function renderExperiments(view: unknown, columns?: number): Span[][] {
|
|
|
125
125
|
for (const row of attempts) if (row.eventsComplete === false && row.nextEventCursor !== undefined) out.push([s(`more events of ${row.id}: ahub study experiments --attempt ${row.id} --events-after ${row.nextEventCursor}; the values above come from the events shown so far`, "attention")]);
|
|
126
126
|
return out;
|
|
127
127
|
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
/** Screened passage or declared manifest-authoring metadata, never an entailment/quality claim. */
|
|
131
|
+
export function renderStudyEvidence(value: unknown, columns?: number): Span[][] {
|
|
132
|
+
const v = value as any;
|
|
133
|
+
if (v?.status !== "resolved" && v?.status !== "available") return [[s(`Evidence ${v?.status ?? "unavailable"}; use a visible research task and current public evidence`, "attention")]];
|
|
134
|
+
const out: Span[][] = [...heading(v.status === "resolved" ? `Evidence ${v.id} r${v.revision}` : `Declared evidence inventory, task ${v.taskId}`, columns)];
|
|
135
|
+
if (v.status === "resolved") {
|
|
136
|
+
out.push(...pair("status", "resolved provenance only; no entailment or source-quality certification", columns, 12));
|
|
137
|
+
out.push(...pair("source", v.link?.sourceId, columns, 12));
|
|
138
|
+
out.push(...pair("scalars", `${v.locator?.start}..${v.locator?.end}`, columns, 12));
|
|
139
|
+
out.push(...pair("passage", v.excerpt, columns, 12));
|
|
140
|
+
} else {
|
|
141
|
+
out.push(...pair("incarnation", v.taskCreated, columns, 12));
|
|
142
|
+
for (const artifact of list(v.deliverables)) out.push(...pair("artifact", `${artifact.id} ${artifact.format} ${artifact.sha256}`, columns, 12));
|
|
143
|
+
for (const claim of list(v.claims)) {
|
|
144
|
+
out.push(...pair("claim", `${claim.claimId} @ ${claim.claimRevision}`, columns, 12));
|
|
145
|
+
out.push(...pair("inventory", claim.complete && claim.inventory ? `r${claim.inventory.revision} ${claim.inventory.sha256}` : "unknown/incomplete: obtain complete inventory before checking", columns, 12));
|
|
146
|
+
for (const link of list(claim.evidence)) out.push(...pair("link", `${link.id} r${link.revision} ${link.status}`, columns, 12));
|
|
147
|
+
}
|
|
148
|
+
out.push([s("Declared bindings only. Select citation mappings in a synthesis manifest; invoke ahub study check explicitly.", "muted")]);
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const SYNTHESIS_NEXT: Record<string, string> = {
|
|
154
|
+
refresh_manifest: "refresh claim, link, inventory and artifact bindings in the manifest",
|
|
155
|
+
provide_artifact: "register unchanged public Markdown/BibTeX deliverables through the existing deliverable workflow",
|
|
156
|
+
repair_citations: "repair declared Markdown citation keys and their BibTeX entries",
|
|
157
|
+
record_evidence: "record current claim evidence with hub_evidence_record",
|
|
158
|
+
resolve_locator: "inspect ahub study evidence for current public registered projection/locator provenance",
|
|
159
|
+
record_person_judgment: "a person records the claim's verdict with ahub task claim; model labels do not count",
|
|
160
|
+
resolve_contradiction: "a person adjudicates or explicitly qualifies the current manifest-bound conclusion",
|
|
161
|
+
read_complete_inventory: "obtain a complete readable inventory; split oversized tasks or repair stored evidence before retrying",
|
|
162
|
+
complete_manifest_claims: "include every current declared task claim in the manifest",
|
|
163
|
+
};
|
|
164
|
+
export function renderSynthesisReadiness(value: unknown, columns?: number): Span[][] {
|
|
165
|
+
const v = value as any, out: Span[][] = [...heading(`Synthesis ${v?.status ?? "unavailable"}`, columns)];
|
|
166
|
+
if (v?.status === "private") return [...out, [s("Readiness withheld by current task/source/artifact privacy; no research content is disclosed.", "attention")]];
|
|
167
|
+
if (!v?.scope) {
|
|
168
|
+
const reason = v?.cause === "source_input_limit" ? "Source input exceeds this bounded check; split the synthesis into smaller tasks."
|
|
169
|
+
: "Inputs or policy changed/unavailable; refresh current public bindings and run ahub study check again.";
|
|
170
|
+
return [...out, [s(reason, "attention")]];
|
|
171
|
+
}
|
|
172
|
+
out.push(...pair("scope", "structural/provenance only; not truth, entailment or source-quality verification", columns, 12));
|
|
173
|
+
for (const key of ["manifestSha256", "binding", "claimCoverage", "deliverable", "bibliography"]) out.push(...pair(key, v[key], columns, 12));
|
|
174
|
+
out.push(...pair("citations", `${v.citations?.state} (cited ${v.citations?.cited ?? "unknown"}, missing ${v.citations?.missing ?? "unknown"})`, columns, 12));
|
|
175
|
+
for (const claim of list(v.claims)) {
|
|
176
|
+
out.push(...heading(claim.claimId, columns));
|
|
177
|
+
for (const key of ["claim", "inventory", "citationKey", "evidenceLink", "locator", "provenance", "judgment", "personVerdict", "contradictionHistory", "contradiction"]) out.push(...pair(key, claim[key], columns, 14));
|
|
178
|
+
}
|
|
179
|
+
for (const next of list(v.next)) out.push(...pair("next", SYNTHESIS_NEXT[next] ?? "inspect the current manifest bindings", columns, 12, "attention"));
|
|
180
|
+
return out;
|
|
181
|
+
}
|