@staix/agent-hub 0.44.0 → 0.45.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 +40 -0
- package/README.md +3 -8
- package/docs/agent-notes/adapters.md +2 -2
- package/docs/agent-notes/daemon.md +1 -1
- package/docs/agent-notes/local-worker.md +1 -1
- package/docs/agent-notes/security-review.md +1 -1
- package/docs/agent-notes/tasks.md +3 -1
- package/docs/agent-notes/tests.md +3 -2
- package/docs/design/adapters.md +4 -2
- package/docs/design/agent-hub.md +1 -1
- package/docs/design/roadmap.md +75 -2
- package/docs/design/supervision.md +21 -1
- package/docs/design/task-board.md +30 -2
- package/docs/dogfood.md +13 -4
- package/docs/events.md +5 -1
- package/docs/influences.md +7 -0
- package/docs/memory.md +4 -4
- package/docs/operations.md +51 -18
- package/docs/quickstart.md +8 -2
- package/docs/research.md +16 -0
- package/docs/roadmap.json +4 -0
- package/docs/roadmap.md +9 -0
- package/docs/sdlc.md +15 -3
- package/docs/security.md +3 -3
- package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
- package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
- package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
- package/docs/verification/2026-11-21-0.45.0.md +69 -0
- package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
- package/docs/verified.json +32 -26
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +472 -229
- package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
- package/plugins/agent-hub/server.js +513 -258
- package/scripts/check-docs.mjs +9 -1
- package/src/adapters/acp.ts +11 -1
- package/src/adapters/compat.ts +3 -3
- package/src/adapters/definitions/builtin-metadata.ts +2 -2
- package/src/adapters/definitions/native-context.ts +10 -0
- package/src/adapters/jcode.ts +10 -0
- package/src/adapters/local-worker.ts +3 -2
- package/src/adapters/pi.ts +15 -4
- package/src/cli/console-state.ts +3 -1
- package/src/cli/help.ts +3 -1
- package/src/cli/identity.ts +2 -1
- package/src/cli/main.ts +11 -5
- package/src/cli/recovery-package.ts +16 -3
- package/src/cli/roadmap-write.ts +59 -0
- package/src/cli/roadmap.ts +81 -4
- package/src/cli/sdlc-output.ts +4 -0
- package/src/cli/upgrade-runtime.ts +10 -6
- package/src/hub/agent-mem-range.ts +43 -0
- package/src/hub/board.ts +102 -1
- package/src/hub/check-runner.ts +25 -1
- package/src/hub/config-apply.ts +4 -2
- package/src/hub/config-trust.ts +1 -1
- package/src/hub/context-window.ts +1 -1
- package/src/hub/cost-governance.ts +11 -7
- package/src/hub/daemon.ts +253 -30
- package/src/hub/dogfood-read.ts +4 -2
- package/src/hub/edit-guard.ts +100 -0
- package/src/hub/events.ts +79 -8
- package/src/hub/facts.ts +57 -4
- package/src/hub/hub-tools.ts +2 -0
- package/src/hub/lifecycle.ts +6 -1
- package/src/hub/log-rotation.ts +130 -0
- package/src/hub/memory-profile.ts +137 -21
- package/src/hub/no-writes.ts +1 -0
- package/src/hub/operational-authority.ts +3 -2
- package/src/hub/operational-settings.ts +2 -2
- package/src/hub/recovery-store.ts +49 -21
- package/src/hub/research-experiments.ts +132 -0
- package/src/hub/research-quality.ts +8 -2
- package/src/hub/research-record.ts +35 -0
- package/src/hub/research.ts +128 -28
- package/src/hub/roadmap-check.ts +65 -0
- package/src/hub/roadmap-decompose.ts +80 -0
- package/src/hub/roadmap-export.ts +27 -0
- package/src/hub/roadmap-sync.ts +97 -0
- package/src/hub/roadmap.ts +40 -0
- package/src/hub/sdlc-branch-ci.ts +128 -0
- package/src/hub/sdlc-merge.ts +6 -3
- package/src/hub/sdlc-metrics.ts +19 -5
- package/src/hub/sdlc.ts +73 -5
- package/src/hub/settings.ts +1 -0
- package/src/hub/snapshots.ts +13 -1
- package/src/hub/startup-event-seeds.ts +21 -15
- package/src/hub/startup-timing.ts +3 -1
- package/src/hub/supervision-proposals.ts +10 -2
- package/src/hub/supervision-rules.ts +26 -3
- package/src/hub/supervision.ts +7 -0
- package/src/hub/task-pr.ts +47 -0
- package/src/hub/task-worktree.ts +18 -11
- package/src/hub/tasks.ts +502 -34
- package/src/hub/usage-rollup.ts +35 -20
- package/src/local/tools.ts +13 -1
- package/src/memory/client.ts +3 -2
- package/src/pi/extension.ts +15 -3
- package/src/pi/tool-receipts.ts +26 -0
package/scripts/check-docs.mjs
CHANGED
|
@@ -85,7 +85,7 @@ try {
|
|
|
85
85
|
} else noteNames = readdirSync(join(root, "docs/agent-notes"));
|
|
86
86
|
// #1268: every user-facing page directly under docs/ and docs/addons/ needs a stamp too; an absent directory lists nothing.
|
|
87
87
|
// The smoke ledger and the retired GSD analysis are dated records with their own evidence, like specs and the changelog.
|
|
88
|
-
const records = new Set(["docs/smoke.md", "docs/gsd-collaboration-analysis.md"]);
|
|
88
|
+
const records = new Set(["docs/smoke.md", "docs/gsd-collaboration-analysis.md", "docs/roadmap.md"]);
|
|
89
89
|
const pages = (dir) => {
|
|
90
90
|
if (!committed) return existsSync(join(root, dir)) ? readdirSync(join(root, dir)) : [];
|
|
91
91
|
const listed = git("ls-tree", "-z", "--name-only", `${headId}:${dir}`);
|
|
@@ -131,6 +131,14 @@ try {
|
|
|
131
131
|
if (commits || dirty.stdout) reports.push(`${doc}: stale (${commits} source commit${commits === 1 ? "" : "s"}${dirty.stdout ? "; uncommitted source changes" : ""})`);
|
|
132
132
|
}
|
|
133
133
|
} catch (error) { errors.push(error instanceof Error ? error.message : String(error)); }
|
|
134
|
+
// The gate opts into the roadmap validator; standalone release evidence stays self-contained.
|
|
135
|
+
if (process.env.AHUB_CHECK_ROADMAP === "1") {
|
|
136
|
+
const validator = join(dirname(fileURLToPath(import.meta.url)), "check-roadmap.mjs");
|
|
137
|
+
const result = spawnSync(process.execPath, [validator, root, ...(committed ? ["--committed"] : [])], { encoding: "utf8", timeout: 30_000, maxBuffer: 256 * 1024, env: process.env });
|
|
138
|
+
if (result.status !== 0) errors.push("roadmap validation failed");
|
|
139
|
+
if (!jsonOutput && result.stdout) process.stdout.write(result.stdout);
|
|
140
|
+
if (!jsonOutput && result.stderr) process.stderr.write(result.stderr);
|
|
141
|
+
}
|
|
134
142
|
if (!jsonOutput) for (const report of reports) console.log(`docs: ${report}`);
|
|
135
143
|
if (requireFresh && reports.length) errors.push("release requires fresh documentation stamps");
|
|
136
144
|
if (requireFresh && errors.length) errors.push("release refused: merge the release PR with a merge commit and verify all documentation stamps before tagging");
|
package/src/adapters/acp.ts
CHANGED
|
@@ -165,6 +165,11 @@ export interface AcpOptions {
|
|
|
165
165
|
* request then follows the permission mode as before). A verdict beats `autoApprove`, withholds `allow_always` and carries the approval text.
|
|
166
166
|
*/
|
|
167
167
|
actionGate?: (call: { names: readonly string[]; kind?: string; input: unknown }, session: string) => ActionGateVerdict | undefined;
|
|
168
|
+
/**
|
|
169
|
+
* #1601: the open-tool ceiling cancelled this turn. Carries the ceiling in milliseconds and nothing else, so a host can log the
|
|
170
|
+
* cause class and its minutes for a kind whose own log lines are withheld, without a tool title or any native text.
|
|
171
|
+
*/
|
|
172
|
+
onToolCeiling?: (info: { ceilingMs: number }) => void;
|
|
168
173
|
/** Transient person-only stream; no native update escapes through another observer. */
|
|
169
174
|
onActivity?: (item: Activity) => void;
|
|
170
175
|
isPrivateTurn?: () => boolean;
|
|
@@ -176,7 +181,9 @@ const HANDSHAKE_MS = 30_000;
|
|
|
176
181
|
/** Sessions whose command list may wait for the bind (see `earlyCommands`). */
|
|
177
182
|
const EARLY_COMMANDS_MAX = 8;
|
|
178
183
|
const TOOL_INPUT_CAP = 64;
|
|
179
|
-
|
|
184
|
+
/** #1601: 60 minutes, not the legacy 30, because this repository's own instructions expect a gate run to wait up to 50
|
|
185
|
+
* (`dot remote verify . --wait 50m`). A tool call that reports no progress for that long is still cancelled here. */
|
|
186
|
+
export const TOOL_CEILING_MS = 60 * 60_000;
|
|
180
187
|
export const ACTIVITY_BATCH_MS = 50;
|
|
181
188
|
|
|
182
189
|
export interface ManagedAcpLaunch {
|
|
@@ -793,6 +800,9 @@ export class AcpPeer extends BasePeer {
|
|
|
793
800
|
const ceiling = Math.max(this.watchdogMs, this.opts.toolCeilingMs ?? TOOL_CEILING_MS);
|
|
794
801
|
const remaining = ceiling - (Date.now() - this.lastSignAt);
|
|
795
802
|
if (remaining > 0) { this.touch(Math.min(this.watchdogMs, remaining)); return; }
|
|
803
|
+
// #1601: the host side of the cause, fired before anything that can throw or withhold. A configured kind replaces every one
|
|
804
|
+
// of this adapter's log lines with a fixed withheld sentence, so this port is how the ceiling and its minutes reach hub.log.
|
|
805
|
+
try { this.opts.onToolCeiling?.({ ceilingMs: ceiling }); } catch { /* a diagnostics sink never decides the cancellation */ }
|
|
796
806
|
// Privacy latches for the turn and fails closed, as in emitActivity; the title is agent-written, so one quoted line.
|
|
797
807
|
try { this.activityPrivate ||= this.opts.isPrivateTurn?.() === true; } catch { this.activityPrivate = true; }
|
|
798
808
|
const tools = this.activityPrivate ? "a tool call" : [...new Set(this.openTools.values())].map(title => JSON.stringify(activityText(title).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " ").slice(0, 80))).join(", ");
|
package/src/adapters/compat.ts
CHANGED
|
@@ -34,11 +34,11 @@ export const COMPAT = {
|
|
|
34
34
|
parse: out => plain(out.trim()),
|
|
35
35
|
trustNote: "The model-free extension load, RPC session identity and managed tool receipt path were checked on 1.4.0, 1.5.0 and 1.5.2. Permissions remain host-owned; account-backed inference and another version's extension contract are unverified.",
|
|
36
36
|
receipt: "docs/verification/2026-11-14-pi-152-compat.md" },
|
|
37
|
-
// Transport receipts: docs/verification/2026-10-23-headless-claude-permissions.md; 2.1.310: docs/verification/2026-10-26-claude-implementer-2.1.310.md; 2.1.314 (transport and wrapper): docs/verification/2026-10-31-claude-implementer-2.1.314.md; 2.1.316: docs/verification/2026-10-31-claude-implementer-2.1.316.md; 2.1.318: docs/verification/2026-11-05-claude-implementer-2.1.318.md; 2.1.319: docs/verification/2026-11-06-claude-implementer-2.1.319.md; 2.1.322: docs/verification/2026-11-10-claude-implementer-2.1.322.md; 2.1.323: docs/verification/2026-11-13-claude-implementer-2.1.323.md; host-wrapper receipt below repeats with them.
|
|
38
|
-
"claude-implementer": { label: "Claude headless implementer", verified: ["2.1.309", "2.1.310", "2.1.314", "2.1.316", "2.1.318", "2.1.319", "2.1.322", "2.1.323"], gate: "contract", probe: ["claude", "--version"],
|
|
37
|
+
// Transport receipts: docs/verification/2026-10-23-headless-claude-permissions.md; 2.1.310: docs/verification/2026-10-26-claude-implementer-2.1.310.md; 2.1.314 (transport and wrapper): docs/verification/2026-10-31-claude-implementer-2.1.314.md; 2.1.316: docs/verification/2026-10-31-claude-implementer-2.1.316.md; 2.1.318: docs/verification/2026-11-05-claude-implementer-2.1.318.md; 2.1.319: docs/verification/2026-11-06-claude-implementer-2.1.319.md; 2.1.322: docs/verification/2026-11-10-claude-implementer-2.1.322.md; 2.1.323: docs/verification/2026-11-13-claude-implementer-2.1.323.md; 2.1.328: docs/verification/2026-11-19-claude-implementer-2.1.328.md; 2.1.329: docs/verification/2026-11-20-claude-implementer-2.1.329.md; host-wrapper receipt below repeats with them.
|
|
38
|
+
"claude-implementer": { label: "Claude headless implementer", verified: ["2.1.309", "2.1.310", "2.1.314", "2.1.316", "2.1.318", "2.1.319", "2.1.322", "2.1.323", "2.1.328", "2.1.329"], gate: "contract", probe: ["claude", "--version"],
|
|
39
39
|
parse: out => plain(out.trim().replace(/ \(Claude Code\)$/, "")),
|
|
40
40
|
trustNote: "The native prompt-tool transport and host-wrapper rewrite, environment isolation and replay contract have isolated receipts. No dontAsk/bypass fallback exists; another version's permission or rewrite behavior is unverified.",
|
|
41
|
-
receipt: "docs/verification/2026-11-
|
|
41
|
+
receipt: "docs/verification/2026-11-20-claude-implementer-2.1.329.md" },
|
|
42
42
|
// 0.163.0 receipt: docs/verification/2026-10-22-codex-reviewer-isolation.md; 0.164.0 receipt: docs/verification/2026-10-24-codex-0164-reviewer-isolation.md; 0.166.0: docs/verification/2026-10-31-codex-0166-reviewer-isolation.md; 0.167.0 model-free only, not verified until its model-backed run: docs/verification/2026-11-06-codex-0167-reviewer-isolation.md; 0.167.2 model-free only, not verified until its model-backed run: docs/verification/2026-11-13-codex-01672-reviewer-isolation.md; 0.169.0 (model-free and one model-backed review): docs/verification/2026-11-14-codex-0169-reviewer-isolation.md and docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md
|
|
43
43
|
"codex-review": { label: "Codex reviewer (codex-cli)", verified: ["0.146.0", "0.163.0", "0.164.0", "0.166.0", "0.169.0"], gate: "isolation", probe: ["codex", "--version"], config: "codex_bin",
|
|
44
44
|
parse: out => plain(out.trim().replace(/^codex-cli /, "")),
|
|
@@ -22,7 +22,7 @@ import { createCodex, createKimi, createJcode, createPi, createLocal, createClau
|
|
|
22
22
|
import { CLAUDE_DISPLAY, CODEX_DISPLAY, KIMI_DISPLAY, PI_DISPLAY, LOCAL_DISPLAY, JCODE_DISPLAY } from "./native-display.ts";
|
|
23
23
|
import { CLAUDE_RECOVERY_SESSION, CODEX_RECOVERY_SESSION, KIMI_RECOVERY_SESSION, PI_RECOVERY_SESSION, LOCAL_RECOVERY_SESSION, JCODE_RECOVERY_SESSION } from "./native-recovery.ts";
|
|
24
24
|
import { claudeWindows, codexWindows } from "./native-quota.ts";
|
|
25
|
-
import { claudeContext, codexContext, acpContextValue, jcodeContextValue } from "./native-context.ts";
|
|
25
|
+
import { claudeContext, codexContext, acpContextValue, jcodeContextValue, piContext } from "./native-context.ts";
|
|
26
26
|
import { KIMI_TUI_FACTS_HOOK } from "../kimi-tui-facts.ts";
|
|
27
27
|
import type { AdapterDefinition } from "../registry-types.ts";
|
|
28
28
|
import type { PeerAdapter } from "../../hub/peers.ts";
|
|
@@ -132,7 +132,7 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
|
|
|
132
132
|
// Approval enforcement belongs to the verified native transport and host permission gate.
|
|
133
133
|
permission: { grants: { ...hubGrants } },
|
|
134
134
|
session: { idField: "sessionId", currentId: sessionId("sessionId"), restoreOnStart: true, launchKind: "pi", launchRecord: true, ...PI_RECOVERY_SESSION, crashPlan: piCrashPlan, unrecordedTerminal: "tui", continuityBookmark: piRecoveryContinuity, continuity: { key: "pi", parse: parsePiContinuity } },
|
|
135
|
-
turnEnd: "adapter", settle: { signal: "agent-settled" }, budget: { account: "pi", instrumented: true, noQuotaReason: "on-prem backends have no provider quota" }, reporting: { tokensNotReported: true }, configuration: { schema: piConfigSchema, routingSchema: piRoutingSchema, settings: PI_SETTINGS, restartReasons: PI_RESTART_REASONS, validateEffective: piEffectiveConfig },
|
|
135
|
+
turnEnd: "adapter", settle: { signal: "agent-settled" }, budget: { account: "pi", instrumented: true, noQuotaReason: "on-prem backends have no provider quota", context: { source: "pi_usage", read: piContext } }, reporting: { tokensNotReported: true }, configuration: { schema: piConfigSchema, routingSchema: piRoutingSchema, settings: PI_SETTINGS, restartReasons: PI_RESTART_REASONS, validateEffective: piEffectiveConfig },
|
|
136
136
|
routing: { localAllowedRefusal: "local_allowed = false also excludes pi for this class", longContext: "backend-limit", preferredTier: true, handoffPriority: 0, trace: "backend", backendLabel: "pi" },
|
|
137
137
|
cli: { command: "pi", entry: { lifecycleAdmission: false, execute: runPiEntry }, preview: previewPi, usage: [["ahub pi [--print-command] [--mode headless|tui | --headless] [--backend auto|dgx|mlx] [--model <alias>] [--session-id <id>] [--session-file <path>] [--replace-session]", "start Pi: its TUI in this terminal unless --headless or the start mode setting (peers.pi.start_mode) says headless; without a terminal the hub opens one or says how", "start Pi in a terminal, or headless"]], launchConfigKeys: ["pi.cmd", "pi.backend", "pi.dgx_coding", "pi.dgx_fast", "pi.max_steps", "routing.pi", "peers.pi.start_mode"], previewArgs: ["--mode", "tui"], retainedTerminalNotice: piRetainedTerminalNotice, personOnlyFlags: ["--replace-session"], startWords: form => ["pi", "--mode", form] }, display: PI_DISPLAY,
|
|
138
138
|
},
|
|
@@ -45,3 +45,13 @@ export function jcodeContextValue(value: unknown, sessionId: string, measuredAt:
|
|
|
45
45
|
const tokens = okay ? raw.used as number : null, window = okay ? raw.size as number : null;
|
|
46
46
|
return { source: "jcode_usage_update", sessionId, measuredAt, tokens, window, used: tokens !== null && window !== null ? Math.min(1, tokens / window) : null };
|
|
47
47
|
}
|
|
48
|
+
|
|
49
|
+
/** Pi reports the last assistant prompt's input and cache counters, not cumulative consumption. */
|
|
50
|
+
export function piContext(value: unknown, sessionId: string, measuredAt: number): ContextReading {
|
|
51
|
+
const raw = object(value), parts = [raw.input, raw.cacheRead, raw.cacheWrite];
|
|
52
|
+
const valid = parts.every(n => Number.isSafeInteger(n) && (n as number) >= 0);
|
|
53
|
+
const sum = valid ? parts.reduce<number>((a, n) => a + (n as number), 0) : null;
|
|
54
|
+
const tokens = Number.isSafeInteger(sum) ? sum : null;
|
|
55
|
+
const window = Number.isSafeInteger(raw.contextWindow) && (raw.contextWindow as number) > 0 ? raw.contextWindow as number : null;
|
|
56
|
+
return { source: "pi_usage", sessionId, measuredAt, tokens, window, used: tokens !== null && window !== null ? Math.min(1, tokens / window) : null };
|
|
57
|
+
}
|
package/src/adapters/jcode.ts
CHANGED
|
@@ -27,6 +27,16 @@ export function jcodeCommand(command: string[], kind: "serve" | "acp", socket: s
|
|
|
27
27
|
return [...command, kind, "--socket", socket, "--cwd", cwd, "--no-update", "--no-selfdev", ...(provider ? ["-p", provider] : []), ...(model ? ["--model", model] : []), ...(profile ? ["--provider-profile", profile] : []),
|
|
28
28
|
...(kind === "serve" ? ["--temporary-server", "--owner-pid", String(process.pid), "--server-name", `agent-hub-${peer}`] : ["--mcp-tools", "eager"])];
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* #1601: the one host sentence a configured Jcode may write to hub.log, because the daemon replaces every line this adapter's
|
|
32
|
+
* own `log` port would carry with "Jcode native diagnostic: details withheld". It names the cause class, the ceiling's minutes,
|
|
33
|
+
* the launch that restarts this peer and the row the person settles, and it takes only the ceiling and the host's own peer id,
|
|
34
|
+
* so no tool title or native text can reach the log through it. `peer` is `jcode` for the base peer, an instance id otherwise (#685).
|
|
35
|
+
*/
|
|
36
|
+
export function jcodeToolCeilingCause(ceilingMs: number, peer: string): string {
|
|
37
|
+
const launch = peer === "jcode" ? "ahub jcode" : `ahub jcode --as ${peer}`;
|
|
38
|
+
return `Jcode turn cancelled by the open-tool ceiling (${Math.round(ceilingMs / 60_000)} min, adapter_timing.acp_tool_ceiling_min) after a tool call stayed silent; the delivery is held for review and the peer is offline with queued work retained - restart it with '${launch}', then settle the held row ('ahub queue list --peer ${peer}' names it; 'ahub queue show <id>' prints the resolve command)`;
|
|
39
|
+
}
|
|
30
40
|
/** The session preamble of a Jcode peer: the deferred-tools guidance (#912), then the hub's role contract when there is one. Sent once, with the session's first prompt. */
|
|
31
41
|
export function jcodePreamble(roleContract?: string): string {
|
|
32
42
|
return roleContract ? `${JCODE_DEFERRED_TOOLS_INSTRUCTION}\n\n${roleContract}` : JCODE_DEFERRED_TOOLS_INSTRUCTION;
|
|
@@ -70,7 +70,7 @@ export interface LocalOptions {
|
|
|
70
70
|
turnId?: () => string | undefined;
|
|
71
71
|
onApprovalStop?: (reason: string) => void;
|
|
72
72
|
onTool?: (observation: ToolObservation, task?: string) => void;
|
|
73
|
-
tools: { docRead?: DocReadPort; webFetch?: WebFetchPort; deny: string[]; permit: ToolContext["permit"]; shellExecutionCheck?: ToolContext["shellExecutionCheck"]; bashNetwork?: SandboxNetwork; readAllow?: string[]; readOnly?: string[] };
|
|
73
|
+
tools: { docRead?: DocReadPort; webFetch?: WebFetchPort; deny: string[]; permit: ToolContext["permit"]; shellExecutionCheck?: ToolContext["shellExecutionCheck"]; editGuard?: (task: string | undefined, current: () => boolean) => ToolContext["editGuard"]; bashNetwork?: SandboxNetwork; readAllow?: string[]; readOnly?: string[] };
|
|
74
74
|
capture?: Capture;
|
|
75
75
|
/** Runs a hub task tool (hub_task_*, hub_review, hub_remember) as this peer. Absent = the tools are not offered. */
|
|
76
76
|
taskTool?: (name: string, args: Record<string, unknown>, turn: { pii: boolean; signal?: AbortSignal }) => Promise<string>;
|
|
@@ -523,7 +523,7 @@ export class LocalPeer extends BasePeer {
|
|
|
523
523
|
? Promise.resolve("error: anchored review in this batch; save notes in a later turn")
|
|
524
524
|
: (TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name)) && this.opts.taskTool
|
|
525
525
|
? this.opts.taskTool(name, safeParse(call.function.arguments), { pii: !!policy?.pii, signal: turnSignal }).catch((e: Error) => `error: ${e.message}`)
|
|
526
|
-
: runTool(name, call.function.arguments, ctx);
|
|
526
|
+
: runTool(name, call.function.arguments, this.probeConfinement ? ctx : this.toolContext(envs, turnSignal, !!policy?.pii, reply, policy?.task));
|
|
527
527
|
const probe = this.probeSession;
|
|
528
528
|
const running = probe ? (async () => {
|
|
529
529
|
try {
|
|
@@ -566,6 +566,7 @@ export class LocalPeer extends BasePeer {
|
|
|
566
566
|
...(this.opts.tools.docRead ? { docRead: { ...this.opts.tools.docRead, pii } } : {}),
|
|
567
567
|
...(this.opts.tools.webFetch ? { webFetch: { ...this.opts.tools.webFetch, pii } } : {}),
|
|
568
568
|
cwd: this.opts.cwd,
|
|
569
|
+
...(this.opts.tools.editGuard && !probe ? { editGuard: this.opts.tools.editGuard(task, () => !turnSignal.aborted && executionGeneration === this.turn) } : {}),
|
|
569
570
|
deny: this.opts.tools.deny,
|
|
570
571
|
readOnly: this.opts.tools.readOnly,
|
|
571
572
|
...(probe ? { probe: { root: probe.workspace.root, writableRoots: probe.workspace.allowedWrites,
|
package/src/adapters/pi.ts
CHANGED
|
@@ -56,6 +56,8 @@ export interface PiOptions {
|
|
|
56
56
|
admitBudget?: (envs: Envelope[], unit: ExecutionUnit) => Promise<ExecutionBudgetDecision[]>;
|
|
57
57
|
/** Reported message usage as increments, before agent_settled releases the turn. */
|
|
58
58
|
onTokens?: (added: number) => void;
|
|
59
|
+
/** Current-session prompt occupancy; unknown observations invalidate stale readings. */
|
|
60
|
+
onContext?: (value: unknown, sessionId: string) => void;
|
|
59
61
|
/** `ceiling` is the validated, session/turn-bound tool-step ceiling signal (#179), present only when the trusted extension emitted one for this turn. */
|
|
60
62
|
onTurnFailure?: (envs: Envelope[], reason: string, ceiling?: PiToolStepCeiling, settledCeiling?: boolean) => Promise<void>;
|
|
61
63
|
/** Observation only: cancelled/stopped logical turns never request failure handoff. */
|
|
@@ -113,6 +115,7 @@ function ownerStillAlive(pid: number, signature: string | undefined): boolean {
|
|
|
113
115
|
|
|
114
116
|
|
|
115
117
|
export class PiPeer extends BasePeer {
|
|
118
|
+
private sessionModel: string | undefined;
|
|
116
119
|
readonly hubNative = true;
|
|
117
120
|
readonly hubOwned: boolean = true;
|
|
118
121
|
private proc?: ChildProcessWithoutNullStreams;
|
|
@@ -295,6 +298,7 @@ export class PiPeer extends BasePeer {
|
|
|
295
298
|
const session = this.recoveryMetadata().sessionId;
|
|
296
299
|
return typeof session === "string" ? session : undefined;
|
|
297
300
|
}
|
|
301
|
+
get verifiedRecordSession(): string | undefined { return this.verifiedOwner() ? this.nativeSession : undefined; }
|
|
298
302
|
|
|
299
303
|
/** Verify the live source before choosing ID-only restoration. Never infer emptiness from a missing file. */
|
|
300
304
|
async captureResume(): Promise<Record<string, unknown>> {
|
|
@@ -311,6 +315,7 @@ export class PiPeer extends BasePeer {
|
|
|
311
315
|
? (await this.waitRpc("get_state", 15_000)).data
|
|
312
316
|
: await this.sendTui({ type: "get_session_state" });
|
|
313
317
|
if (this.state !== "idle" || this.activeTools || snapshot?.sessionId !== this.sessionId || snapshot?.sessionFile !== this.sessionFile) throw new Error("Pi source session changed during capture");
|
|
318
|
+
if (this.opts.mode === "tui" && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(snapshot); this.opts.onContext?.(snapshot.context, this.sessionId); }
|
|
314
319
|
if (!this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore)) throw new Error("Pi source session title changed during capture; retry with a fresh native session snapshot");
|
|
315
320
|
const empty = this.opts.mode === "headless"
|
|
316
321
|
? snapshot.messageCount === 0 && snapshot.pendingMessageCount === 0 && snapshot.isStreaming === false && snapshot.isCompacting !== true && !snapshot.sessionName
|
|
@@ -690,6 +695,7 @@ export class PiPeer extends BasePeer {
|
|
|
690
695
|
const snapshot = await this.sendTui({ type: "get_session_state" });
|
|
691
696
|
if (epoch !== this.rosterEpoch || this.stopping || !this.verifiedOwner() || this.activeTools || snapshot?.sessionId !== session || snapshot?.sessionFile !== file || typeof snapshot?.idle !== "boolean") throw new Error("Pi roster return could not verify the current native session");
|
|
692
697
|
if (lifecycle !== this.rosterLifecycleRevision) throw new Error("Pi native activity changed during roster return; retry with a fresh session snapshot");
|
|
698
|
+
if (session) { this.sessionModel = stateModelId(snapshot); this.opts.onContext?.(snapshot.context, session); }
|
|
693
699
|
this.observeSnapshotTitle(snapshot, titleRevisionBefore, titleEpochBefore);
|
|
694
700
|
this.rosterDetached = false;
|
|
695
701
|
this.hubPromptId = undefined; this.hubPromptGeneration = undefined;
|
|
@@ -811,7 +817,7 @@ export class PiPeer extends BasePeer {
|
|
|
811
817
|
this.noteActivity();
|
|
812
818
|
attempted = true;
|
|
813
819
|
if (deliveryId) this.activeDeliveryIds.add(deliveryId);
|
|
814
|
-
const recordPrompt = this.
|
|
820
|
+
const recordPrompt = this.turnRecordPrompt("");
|
|
815
821
|
const message = [recordPrompt, envs.some(env => env.private || remoteEnvelope(env)) ? undefined : this.opts.titlePreface?.(), renderDigest(envs, true)].filter(Boolean).join("\n");
|
|
816
822
|
if (this.opts.mode === "tui") { const pending = this.sendTui({ type: "prompt", message }); promptId = this.pendingPromptId; await pending; }
|
|
817
823
|
else await this.sendRpc({ type: "prompt", message });
|
|
@@ -884,8 +890,7 @@ export class PiPeer extends BasePeer {
|
|
|
884
890
|
}
|
|
885
891
|
|
|
886
892
|
/**
|
|
887
|
-
*
|
|
888
|
-
* itself set through `set_model` (Pi acknowledged it), which is only `configured`. A read that fails never fails the delivery.
|
|
893
|
+
* Pi's current native session model is session evidence; a failed or placeholder read leaves the acknowledged configured model.
|
|
889
894
|
*/
|
|
890
895
|
private async captureTurnModel(requested: string | undefined): Promise<void> {
|
|
891
896
|
this.turnModel = undefined;
|
|
@@ -895,6 +900,8 @@ export class PiPeer extends BasePeer {
|
|
|
895
900
|
const id = state.success === true ? stateModelId(state.data) : undefined;
|
|
896
901
|
if (id) { this.turnModel = { model: id, evidence: "session" }; return; }
|
|
897
902
|
} catch { /* optional metadata: the turn goes on without it */ }
|
|
903
|
+
} else {
|
|
904
|
+
if (this.verifiedOwner() && this.sessionModel) { this.turnModel = { model: this.sessionModel, evidence: "session" }; return; }
|
|
898
905
|
}
|
|
899
906
|
if (requested) this.turnModel = { model: requested, evidence: "configured" };
|
|
900
907
|
}
|
|
@@ -910,7 +917,7 @@ export class PiPeer extends BasePeer {
|
|
|
910
917
|
const slash = model.indexOf("/");
|
|
911
918
|
const provider = "agent-hub-local";
|
|
912
919
|
const modelId = model;
|
|
913
|
-
if (this.opts.mode === "tui") await this.sendTui({ type: "set_model", provider, modelId }); else await this.sendRpc({ type: "set_model", provider, modelId });
|
|
920
|
+
if (this.opts.mode === "tui") { if (this.sessionModel !== modelId) this.sessionModel = undefined; await this.sendTui({ type: "set_model", provider, modelId }); } else await this.sendRpc({ type: "set_model", provider, modelId });
|
|
914
921
|
this.requestedModel = model;
|
|
915
922
|
}
|
|
916
923
|
|
|
@@ -969,6 +976,7 @@ export class PiPeer extends BasePeer {
|
|
|
969
976
|
this.sessionId = String(event.sessionId ?? ""); this.sessionFile = String(event.sessionFile ?? "");
|
|
970
977
|
this.ownerPid = Number.isInteger(event.pid) ? event.pid : undefined; this.ownerSignature = typeof event.signature === "string" ? event.signature : undefined;
|
|
971
978
|
if ((this.opts.sessionId && this.sessionId !== this.opts.sessionId) || (this.opts.sessionFile && this.sessionFile !== this.opts.sessionFile)) { this.opts.log?.(`[${this.id}] Pi session identity mismatch`); return; }
|
|
979
|
+
this.sessionModel = stateModelId(event);
|
|
972
980
|
this.titleRevision = -1; this.titleEpoch++;
|
|
973
981
|
this.nativeTitleEpoch = typeof event.titleEpoch === "string" && event.titleEpoch ? event.titleEpoch : undefined;
|
|
974
982
|
this.observeTitle(event.sessionName, event.titleRevision, event.titleEpoch);
|
|
@@ -1000,6 +1008,7 @@ export class PiPeer extends BasePeer {
|
|
|
1000
1008
|
if (event.type === "agent_start") {
|
|
1001
1009
|
const generation = Number.isSafeInteger(event.generation) ? event.generation : this.budgetGeneration + 1;
|
|
1002
1010
|
if (generation <= this.budgetGeneration) return;
|
|
1011
|
+
if (this.opts.mode === "tui" && this.sessionModel && this.verifiedOwner() && (event.sessionId === undefined || event.sessionId === this.sessionId)) this.turnModel = { model: this.sessionModel, evidence: "session" };
|
|
1003
1012
|
this.modelStep = 0;
|
|
1004
1013
|
this.ceilingUnsafe = false; this.turnObserved = false;
|
|
1005
1014
|
this.approvalExpiries = 0; this.approvalAnswerEpoch = undefined; this.approvalStopReason = ""; this.approvalAbortSent = false; this.abortedToolIds.clear(); this.abortIdsOverflow = false;
|
|
@@ -1018,6 +1027,8 @@ export class PiPeer extends BasePeer {
|
|
|
1018
1027
|
}
|
|
1019
1028
|
}
|
|
1020
1029
|
if (event.type === "activity" && this.state === "busy") this.touch();
|
|
1030
|
+
if (event.type === "pi_model" && event.sessionId === this.sessionId && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(event); this.opts.onContext?.(undefined, this.sessionId); }
|
|
1031
|
+
if (event.type === "pi_usage" && this.agentRunning && this.state === "busy" && event.sessionId === this.sessionId && event.generation === this.budgetGeneration && this.verifiedOwner() && this.sessionId) { this.sessionModel = stateModelId(event); this.opts.onContext?.(event.context, this.sessionId); }
|
|
1021
1032
|
if (event.type === "tokens" && this.state === "busy" && typeof event.id === "string" && event.id.length <= 100 && Number.isSafeInteger(event.tokens) && event.tokens >= 0 && !this.usageSeen.has(event.id)) {
|
|
1022
1033
|
this.usageSeen.add(event.id);
|
|
1023
1034
|
if (this.usageSeen.size > 1000) this.usageSeen.delete(this.usageSeen.values().next().value!);
|
package/src/cli/console-state.ts
CHANGED
|
@@ -1390,7 +1390,6 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
|
|
|
1390
1390
|
const selectedTask = s.panel === 3 ? data[at] : undefined;
|
|
1391
1391
|
const holders = selectedTask && (selectedTask.planner !== undefined || selectedTask.plannerReason !== undefined)
|
|
1392
1392
|
? fieldLines((["planner", "owner", "reviewer"] as const).map((role): [string, unknown] => [role, taskHolderText(selectedTask, role)]), columns, now).flat() : [];
|
|
1393
|
-
const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : s.panel === 7 ? height - 2 - taskLines.length : height - (s.panel === 3 ? 2 + holders.length : s.panel === 1 && s.versions ? 2 : 1)); const start = Math.max(0, at - capacity + 1);
|
|
1394
1393
|
const stages = new Map(progress.stages.map(stage => [stage.id, stage]));
|
|
1395
1394
|
const cellRows = head ? data.map((row, i) => cells(s, row, i === at, now, stages)) : [];
|
|
1396
1395
|
const rowsOf = head ? s.panel === 7 ? optionalTable(head, cellRows, columns, USAGE_DROP) : s.panel === 1 ? optionalTable(head, cellRows, columns) : s.panel === 3 && s.backlogView ? optionalTable(head, cellRows, columns, ["AGE", "CLASS", "DEPS", "PRI"]) : table(head, cellRows, columns) : undefined;
|
|
@@ -1425,6 +1424,9 @@ export function renderConsoleLines(s: ConsoleState, columns: number, rows = 24,
|
|
|
1425
1424
|
}
|
|
1426
1425
|
lines.push(fitLine(parts, columns));
|
|
1427
1426
|
}
|
|
1427
|
+
// #1607: the row window is what is left after the lines already above the table (panel notes), its header and what
|
|
1428
|
+
// follows it, so the selected row is never cut off by the body height.
|
|
1429
|
+
const capacity = Math.max(1, s.panel === 2 ? Math.min(Math.floor(height / 2) - 1, height - 3 - tail.length) : height - lines.length - 1 - (s.panel === 3 ? holders.length : s.panel === 7 ? taskLines.length : 0)); const start = Math.max(0, at - capacity + 1);
|
|
1428
1430
|
lines.push(fitLine([span(" "), ...(rowsOf?.[0] ?? [span(`peer ${s.peerFilter ?? "all"} kind ${s.kindFilter ?? "all"}`, "info")])], columns));
|
|
1429
1431
|
for (let i = start; i < Math.min(data.length, start + capacity); i++) {
|
|
1430
1432
|
const selected = i === at;
|
package/src/cli/help.ts
CHANGED
|
@@ -127,7 +127,9 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
127
127
|
[`ahub roadmap ${ROADMAP_FORMS.link} | ${ROADMAP_FORMS.unlink} | ${ROADMAP_FORMS.order} | ${ROADMAP_FORMS.state}`, "planner or conductor: link and order; done and dropped require the person"],
|
|
128
128
|
[`ahub roadmap ${ROADMAP_FORMS.unplaced}`, "read open issues, tasks and active or draft specs no milestone places, each with why; private tasks are a count; partial means a lower bound"],
|
|
129
129
|
[`ahub roadmap ${ROADMAP_FORMS.triage} | ${ROADMAP_FORMS.accept} | ${ROADMAP_FORMS.reject}`, "planner or conductor: the hub model suggests a milestone for unplaced work, citing ids and words; nothing is linked until accept"],
|
|
130
|
+
[`ahub roadmap ${ROADMAP_FORMS.decompose}`, "planner or conductor: the hub model proposes parts for one milestone from its outcome, the specs it links and the issues it links; each part cites a linked id and says whether it needs its own spec issue or goes straight to a task. Saved as a pending model answer; nothing is intaken, linked or published. --accept <part> instead holds that part as an intake draft linked to the milestone, offered to nobody until the person releases it with ahub intake approve"],
|
|
130
131
|
[`ahub roadmap ${ROADMAP_FORMS.importGithub}`, "person only: create proposed milestones from open GitHub milestones and link their issues; a dry run unless --apply, idempotent, never writes GitHub"],
|
|
132
|
+
[`ahub roadmap ${ROADMAP_FORMS.check} | ${ROADMAP_FORMS.sync} | ${ROADMAP_FORMS.export}`, "check drift, preview an opt-in GitHub mirror or export a screened roadmap; GitHub apply requires a confirmed preview"],
|
|
131
133
|
["ahub release new <name> <goal> <order> | list | show <name> | plan <name> <revision> <dates-json> | activate|freeze|ship|drop <name> <revision> [--json] [--color=auto|always|never]", "person only, except show (any agent, public metadata): planned UTC millisecond dates and phased scope; ship records a time after approval, never tags or publishes"],
|
|
132
134
|
["ahub backlog split <id> <revision> <parts-json> <reason...> [--json] [--color=auto|always|never]", "person only: stage2..8 child prerequisites; original task retains integration, undo refuses used or changed children"],
|
|
133
135
|
["ahub backlog pull-ready <id> <revision> <reason...> [--json] [--color=auto|always|never]", "person only: reserve an eligible WIP slot before routing; pending unowned work can be undone"],
|
|
@@ -403,7 +405,7 @@ export const FLAG_DESCRIPTIONS: Readonly<Record<string, string>> = {
|
|
|
403
405
|
"--detail": "longer text of the task", "--sync": "sync handoff states from the targets", "--duplicate-ok": "file despite an open task, with a reason", "--key": "idempotency key (a UUID) for the handoff",
|
|
404
406
|
"--role": "owner, reviewer or planner", "--model-said": "what the model said about the claim", "--manifest": "synthesis manifest the verdict binds to", "--disposition": "resolved or qualified",
|
|
405
407
|
"--superseded-by": "work that replaces this task", "--created": "when the label applies (person only)", "--title": "milestone title", "--outcome": "the outcome the milestone delivers", "--horizon": "now, next or later",
|
|
406
|
-
"--order": "position among its siblings", "--target": "target date (YYYY-MM-DD) or none", "--parent": "parent milestone id, or none", "--project-id": "id of the disposable project", "--receipt": "file to write the receipt to",
|
|
408
|
+
"--order": "position among its siblings", "--target": "target date (YYYY-MM-DD) or none", "--parent": "parent milestone id, or none", "--write": "write the export to the caller's worktree", "--project-id": "id of the disposable project", "--receipt": "file to write the receipt to",
|
|
407
409
|
"--timeout-ms": "time limit, 100 to 120000 ms", "--hostname": "interface to listen on", "--port": "port to listen on", "--public-url": "public ws or wss URL", "--state-dir": "directory for the relay's state",
|
|
408
410
|
"--broker": "relay URL", "--accept": "request to accept", "--name": "name to join the room under", "--roster": "signed roster to join with", "--frame": "digest of the incoming frame", "--source": "registered src: id (repeatable)",
|
|
409
411
|
"--campaign": "campaign id", "--events-after": "continue its events after this number", "--plan": "plan hash to compare under", "--baseline": "baseline attempt id", "--approved": "only approved tasks",
|
package/src/cli/identity.ts
CHANGED
|
@@ -172,6 +172,7 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
|
|
|
172
172
|
if (sub === "state" && ["done", "dropped"].includes(args[2] ?? "")) return "console";
|
|
173
173
|
// R3 (#1481): importing GitHub milestones is the person's alone, a dry run included; triage, accept and reject are the planner's own tools.
|
|
174
174
|
if (sub === "import-github") return "console";
|
|
175
|
+
if ((sub === "sync" || sub === "export") && args.includes("--apply")) return "conductor";
|
|
175
176
|
return "allowed";
|
|
176
177
|
}
|
|
177
178
|
if (command === "answer" && args.includes("--instructed")) return "conductor";
|
|
@@ -227,7 +228,7 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
|
|
|
227
228
|
export function cliCommandLabel(command: string, args: readonly string[], catalog?: ProjectAdapterCatalog): string {
|
|
228
229
|
if (command === "roadmap") {
|
|
229
230
|
const sub = args[0] === "--json" ? args[1] : args[0];
|
|
230
|
-
return ["list", "show", "new", "edit", "link", "unlink", "order", "state", "unplaced", "triage", "accept", "reject", "import-github"].includes(sub ?? "") ? `roadmap ${sub}` : "roadmap";
|
|
231
|
+
return ["list", "show", "new", "edit", "link", "unlink", "order", "state", "unplaced", "triage", "decompose", "accept", "reject", "import-github", "check", "sync", "export"].includes(sub ?? "") ? `roadmap ${sub}` : "roadmap";
|
|
231
232
|
}
|
|
232
233
|
if (command === "sdlc" && args[0] === "configure") return "sdlc configure";
|
|
233
234
|
if (command === "sdlc" && args[0] === "survey") return ["start", "show"].includes(args[1] ?? "") ? `sdlc survey ${args[1]}` : "sdlc survey";
|
package/src/cli/main.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { conductorLocalOperation, conductorOperation, OPERATIONAL_PERSON_GUIDANC
|
|
|
5
5
|
import { sayRecipients } from "./say-input.ts";
|
|
6
6
|
import { parseAnswerArgs } from "./answer-args.ts";
|
|
7
7
|
import { parseRoadmapArgs, renderRoadmap } from "./roadmap.ts";
|
|
8
|
+
import { roadmapWorktree, writeRoadmap } from "./roadmap-write.ts";
|
|
8
9
|
import type { DeliverableRow } from "../hub/tasks.ts";
|
|
9
10
|
import { kimiSourceRow } from "../hub/budget-notes.ts";
|
|
10
11
|
import { hubGitSync, hubGitEnv } from "../hub/git.ts";
|
|
@@ -122,7 +123,7 @@ import { runSpecs, runSpecsStamp } from "./specs.ts";
|
|
|
122
123
|
import { confirmTidy, planTidy, realTidyGit, rowsFromReply, type TidyGit } from "./worktree-tidy.ts";
|
|
123
124
|
import { renderTidyPreview, renderTidyResult, renderWorktrees } from "./worktrees-output.ts";
|
|
124
125
|
import { formatMemoryStaleAnchors } from "../hub/memory-stale-anchors.ts";
|
|
125
|
-
import {
|
|
126
|
+
import { AGENT_MEM_REFUSAL, AGENT_MEM_VERSION, memoryIndexExists, selectedMemoryProfile } from "../hub/memory-profile.ts";
|
|
126
127
|
import { checkMemoryProfiles, formatMemoryProfileCheck } from "../hub/memory-profile-check.ts";
|
|
127
128
|
import { addonReport, appendRecords, closedAtOf, formatAddons, formatResearch, LABELS, labelTarget, RESEARCH_SCHEMA, projectKey, readStores, researchReport, taskRecords, toCsv, type Label, type TaskRecord } from "../hub/research.ts";
|
|
128
129
|
import { summarize, summarizeByTask } from "../hub/report.ts";
|
|
@@ -1717,7 +1718,13 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
1717
1718
|
let options;
|
|
1718
1719
|
try { options = parseRoadmapArgs(args); } catch (error) { return fail(`${error instanceof Error ? error.message : "invalid roadmap arguments"}; see ahub help roadmap`); }
|
|
1719
1720
|
// R3 (#1481): the GitHub reads and the model call each carry their own deadline, so these ops wait longer than the 30 s default.
|
|
1720
|
-
const text = await taskOp(options.op, options.args, false, undefined, ["hub_roadmap_unplaced", "hub_roadmap_triage", "roadmap_import_github"].includes(options.op) ? 60_000 : undefined);
|
|
1721
|
+
const text = await taskOp(options.op, options.args, false, undefined, ["hub_roadmap_unplaced", "hub_roadmap_triage", "hub_roadmap_decompose", "roadmap_import_github", "hub_roadmap_check", "roadmap_sync", "roadmap_sync_apply", "roadmap_export_apply"].includes(options.op) ? 60_000 : undefined);
|
|
1722
|
+
if (options.write) {
|
|
1723
|
+
let rendered: { json: string; markdown: string };
|
|
1724
|
+
try { rendered = JSON.parse(text); const root = roadmapWorktree(cwd, invokedFrom), policy = loadConfig(cwd); writeRoadmap(root, rendered, { deny: policy.local.deny, readOnly: policy.data?.readonly ?? [], pii: policy.pii?.paths ?? [] }); }
|
|
1725
|
+
catch (error) { return fail(error instanceof Error ? error.message : "roadmap export unavailable"); }
|
|
1726
|
+
if (!options.json) { console.log("Roadmap files written in the current worktree."); return; }
|
|
1727
|
+
}
|
|
1721
1728
|
if (options.json) console.log(text);
|
|
1722
1729
|
else console.log(renderRoadmap(text, outputOptions().columns));
|
|
1723
1730
|
},
|
|
@@ -3437,9 +3444,8 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
3437
3444
|
row(mlx.state === "ready" || mlx.state === "stopped", "pi mlx", `${mlx.state}${mlx.model ? ` (${mlx.model})` : ""}${mlx.lastError ? `: ${mlx.lastError}` : ""}`);
|
|
3438
3445
|
}
|
|
3439
3446
|
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
row(memoryLibraryReady, "memory library", memoryLibraryReady ? `amem ${AGENT_MEM_VERSION}; in-process, no claude-mem worker` : "installed amem does not match the exact dependency pin");
|
|
3447
|
+
const memoryLibraryReady = AGENT_MEM_REFUSAL === undefined;
|
|
3448
|
+
row(memoryLibraryReady, "memory library", memoryLibraryReady ? `amem ${AGENT_MEM_VERSION}; in-process, no claude-mem worker` : AGENT_MEM_REFUSAL!);
|
|
3443
3449
|
// #1008: memory capture is agent-mem's own setup state, read as structured data (`amem setup <tool> --json`, a preview that writes nothing), never dotfiles text. The caller's
|
|
3444
3450
|
// identity is NOT scrubbed: agent-mem screens a plan for an agent, and a refusal reads as unknown here instead of being laundered into a person's answer.
|
|
3445
3451
|
for (const tool of DOCTOR_MEMORY_CAPTURE_PEERS) {
|
|
@@ -5,6 +5,7 @@ import { basename, dirname, join, resolve } from "node:path";
|
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
6
|
import { hubHome, realPath } from "../hub/project.ts";
|
|
7
7
|
import { Registry } from "../hub/registry.ts";
|
|
8
|
+
import { AGENT_MEM_HOST_API_RANGE, agentMemHostApiOk, agentMemVersionInRange, isAgentMemFloorRange, readHostApiConstants } from "../hub/agent-mem-range.ts";
|
|
8
9
|
|
|
9
10
|
export type CommandResult = { code: number; stdout: string; stderr: string };
|
|
10
11
|
export type RunCommand = (args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; input?: string; pipeExitGraceMs?: number }) => Promise<CommandResult>;
|
|
@@ -48,8 +49,10 @@ function memoryRuntime(root: string, dependencyRoot?: string): string | undefine
|
|
|
48
49
|
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
49
50
|
const deps = pkg.dependencies ?? {};
|
|
50
51
|
if (!Object.keys(deps).length) return undefined;
|
|
51
|
-
const
|
|
52
|
-
|
|
52
|
+
const declared = deps["@staix/agent-mem"];
|
|
53
|
+
// #1611: a current package declares a floor range `>=X.Y.Z <M.0.0`; a package staged under #1605 declares `~X.Y.Z` and one before it an exact
|
|
54
|
+
// version, so a cached release still verifies (legacy forms need no host API); compound ranges, `^`, `*` and prereleases stay refused.
|
|
55
|
+
if (Object.keys(deps).length !== 1 || typeof declared !== "string" || !(/^~?\d+\.\d+\.\d+$/.test(declared) || isAgentMemFloorRange(declared))) throw new Error("unsupported runtime dependencies in recovery package");
|
|
53
56
|
let dir = dependencyRoot ? join(dependencyRoot, "node_modules/@staix/agent-mem")
|
|
54
57
|
: dirname(createRequire(join(root, "package.json")).resolve("@staix/agent-mem"));
|
|
55
58
|
if (dependencyRoot && !existsSync(dir)) throw new Error("memory runtime dependency is unavailable");
|
|
@@ -61,7 +64,17 @@ function memoryRuntime(root: string, dependencyRoot?: string): string | undefine
|
|
|
61
64
|
if (existsSync(manifest)) {
|
|
62
65
|
const memory = JSON.parse(readFileSync(manifest, "utf8"));
|
|
63
66
|
if (memory.name === "@staix/agent-mem") {
|
|
64
|
-
|
|
67
|
+
const installed = typeof memory.version === "string" ? memory.version : "";
|
|
68
|
+
const accepted = declared.startsWith("~") || declared.startsWith(">=") ? agentMemVersionInRange(installed, declared) : installed === declared;
|
|
69
|
+
if (accepted && isAgentMemFloorRange(declared)) {
|
|
70
|
+
// #1611: a floor-form package also needs a host API the hub supports, read from the staged package's own platform module.
|
|
71
|
+
let text = "";
|
|
72
|
+
try { text = readFileSync(join(dir, "src/memory/platform.ts"), "utf8"); } catch { /* missing constants refuse below */ }
|
|
73
|
+
const host = readHostApiConstants(text);
|
|
74
|
+
if (!agentMemHostApiOk(host.min, host.version))
|
|
75
|
+
throw new Error(`memory runtime host API ${host.min ?? "missing"}..${host.version ?? "missing"} does not intersect the supported ${AGENT_MEM_HOST_API_RANGE[0]}..${AGENT_MEM_HOST_API_RANGE[1]}`);
|
|
76
|
+
}
|
|
77
|
+
if (!accepted || Object.keys(memory.dependencies ?? {}).length) throw new Error("memory runtime dependency identity/version mismatch");
|
|
65
78
|
return realPath(dir);
|
|
66
79
|
}
|
|
67
80
|
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { constants, closeSync, fchmodSync, fstatSync, linkSync, lstatSync, openSync, renameSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { guardPath } from "../local/tools.ts";
|
|
5
|
+
import { matchesPolicy } from "../hub/path-policy.ts";
|
|
6
|
+
import { realPath } from "../hub/project.ts";
|
|
7
|
+
import { hubGitSync } from "../hub/git.ts";
|
|
8
|
+
|
|
9
|
+
/** Bind the caller's working tree to the selected hub repository, never to an unrelated checkout. */
|
|
10
|
+
export function roadmapWorktree(project: string, caller: string): string {
|
|
11
|
+
const rootResult = hubGitSync(["-C", caller, "rev-parse", "--show-toplevel"], { encoding: "utf8" });
|
|
12
|
+
if (rootResult.status !== 0 || typeof rootResult.stdout !== "string" || !rootResult.stdout.trim()) throw new Error("roadmap export needs a Git worktree");
|
|
13
|
+
const root = realPath(rootResult.stdout.trim());
|
|
14
|
+
const common = (dir: string) => {
|
|
15
|
+
const result = hubGitSync(["-C", dir, "rev-parse", "--git-common-dir"], { encoding: "utf8" });
|
|
16
|
+
if (result.status !== 0 || typeof result.stdout !== "string" || !result.stdout.trim()) throw new Error("roadmap export repository identity is unavailable");
|
|
17
|
+
return realPath(resolve(dir, result.stdout.trim()));
|
|
18
|
+
};
|
|
19
|
+
if (common(root) !== common(project)) throw new Error("roadmap export caller is in a different repository");
|
|
20
|
+
return root;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const same = (a: Stats | undefined, b: Stats | undefined) => a === undefined ? b === undefined : !!b && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
|
|
24
|
+
/** Only the two fixed generated files are written. A changed or linked target refuses; partial completion is reported. */
|
|
25
|
+
export function writeRoadmap(root: string, files: { json: string; markdown: string }, policy: { deny: string[]; readOnly: string[]; pii: string[] }): void {
|
|
26
|
+
if (typeof files.json !== "string" || typeof files.markdown !== "string") throw new Error("roadmap export is malformed");
|
|
27
|
+
const base = realPath(root), directory = resolve(base, "docs"), folder = lstatSync(directory);
|
|
28
|
+
if (!folder.isDirectory() || folder.isSymbolicLink()) throw new Error("roadmap docs directory is not a plain directory");
|
|
29
|
+
const items = [["docs/roadmap.md", files.markdown], ["docs/roadmap.json", files.json]] as const;
|
|
30
|
+
const targets = items.map(([name, text]) => {
|
|
31
|
+
if (matchesPolicy(base, name, policy.pii, true)) throw new Error("roadmap export path is private");
|
|
32
|
+
const path = guardPath({ cwd: base, deny: policy.deny, readOnly: policy.readOnly }, name, "write");
|
|
33
|
+
if (path !== resolve(base, name)) throw new Error("roadmap export path is linked");
|
|
34
|
+
const before = lstatSync(path, { throwIfNoEntry: false });
|
|
35
|
+
if (before && (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1)) throw new Error("roadmap export target is not a plain file");
|
|
36
|
+
return { name, text, path, before };
|
|
37
|
+
});
|
|
38
|
+
let written = 0;
|
|
39
|
+
try {
|
|
40
|
+
for (const target of targets) {
|
|
41
|
+
const temp = resolve(directory, `.roadmap-${randomUUID()}.tmp`); let fd: number | undefined;
|
|
42
|
+
try {
|
|
43
|
+
fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
44
|
+
writeFileSync(fd, target.text); fchmodSync(fd, target.before ? target.before.mode & 0o777 : 0o644); const created = fstatSync(fd);
|
|
45
|
+
if (!created.isFile() || created.nlink !== 1) throw new Error("temporary export is not a plain file");
|
|
46
|
+
closeSync(fd); fd = undefined;
|
|
47
|
+
if (guardPath({ cwd: base, deny: policy.deny, readOnly: policy.readOnly }, target.name, "write") !== target.path || !same(target.before, lstatSync(target.path, { throwIfNoEntry: false }))) throw new Error("roadmap export target changed");
|
|
48
|
+
// ponytail: no portable conditional rename for an existing inode; a tiny compare-to-rename race remains. Use a kernel conditional replacement if one becomes available.
|
|
49
|
+
if (target.before) renameSync(temp, target.path); else { linkSync(temp, target.path); unlinkSync(temp); }
|
|
50
|
+
written++;
|
|
51
|
+
} finally { if (fd !== undefined) closeSync(fd); try { unlinkSync(temp); } catch {} }
|
|
52
|
+
}
|
|
53
|
+
} catch (error) {
|
|
54
|
+
const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" && /^E[A-Z0-9]+$/.test(error.code) ? error.code : undefined;
|
|
55
|
+
const message = error instanceof Error && ["roadmap export target changed", "temporary export is not a plain file"].includes(error.message) ? error.message : undefined;
|
|
56
|
+
const cause = code ?? message ?? "unknown write failure";
|
|
57
|
+
throw new Error(written ? `roadmap export partially written (${cause}); inspect both files before retrying` : `roadmap export was not written (${cause}); inspect the paths before retrying`);
|
|
58
|
+
}
|
|
59
|
+
}
|