@staix/agent-hub 0.41.0 → 0.43.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 +28 -0
- package/README.md +2 -1
- package/docs/adding-an-ai-tool.md +2 -0
- package/docs/addons/claude-mem.md +1 -1
- package/docs/agent-notes/tasks.md +1 -1
- package/docs/agent-notes/tests.md +1 -1
- package/docs/design/adapters.md +3 -0
- package/docs/design/bus.md +2 -0
- package/docs/design/task-board.md +6 -0
- package/docs/dogfood.md +6 -2
- package/docs/memory.md +8 -6
- package/docs/operations.md +65 -5
- package/docs/quickstart.md +18 -2
- package/docs/sdlc.md +1 -1
- package/docs/security.md +3 -3
- package/docs/verification/2026-11-16-0.42.0.md +48 -0
- package/docs/verification/2026-11-18-0.43.0.md +56 -0
- package/docs/verified.json +23 -23
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +316 -107
- package/plugins/agent-hub/server.js +316 -107
- package/src/adapters/claude-implementer.ts +11 -1
- package/src/adapters/claude-print-child.ts +4 -1
- package/src/adapters/conformance/fakes/acp-server.ts +2 -1
- package/src/adapters/conformance/fakes/app-server.ts +1 -1
- package/src/adapters/local-worker.ts +7 -3
- package/src/adapters/reviewer-print.ts +3 -1
- package/src/cli/agent-attribution.ts +6 -0
- package/src/cli/help.ts +8 -8
- package/src/cli/identity.ts +10 -2
- package/src/cli/main.ts +58 -5
- package/src/cli/memory.ts +21 -6
- package/src/cli/upgrade-output.ts +43 -2
- package/src/cli/upgrade-stopped.ts +162 -0
- package/src/cli/upgrade-wait.ts +37 -0
- package/src/hub/board.ts +4 -2
- package/src/hub/config-apply.ts +1 -0
- package/src/hub/daemon.ts +75 -13
- package/src/hub/envelope.ts +1 -0
- package/src/hub/handoff.ts +14 -0
- package/src/hub/questions.ts +7 -0
- package/src/hub/recovery-store.ts +39 -0
- package/src/hub/research-record.ts +2 -1
- package/src/hub/runtime-capture-prune.ts +114 -3
- package/src/hub/runtime-prune-health.ts +6 -2
- package/src/hub/sdlc-metrics.ts +2 -2
- package/src/hub/settings.ts +2 -0
- package/src/hub/task-sweep.ts +6 -2
- package/src/hub/tasks.ts +8 -3
- package/src/hub/turn-attribution.ts +46 -0
- package/templates/AGENTS.block.md +1 -1
|
@@ -13,6 +13,7 @@ import { claudeStateFile } from "../hub/claude-state.ts";
|
|
|
13
13
|
import { sessionSettings } from "../cli/launch.ts";
|
|
14
14
|
import { assessVersion, COMPAT } from "./compat.ts";
|
|
15
15
|
import { OwnedPrintChild, PrintChildCleanupError, type OwnedInputContext, type OwnedInputObserver, type OwnedPrintChildOptions } from "./claude-print-child.ts";
|
|
16
|
+
import { turnAttribution } from "../hub/turn-attribution.ts";
|
|
16
17
|
import { ClaudeTaskSessions } from "./claude-task-sessions.ts";
|
|
17
18
|
import { formatClaudeFailure, type ClaudeFailureTrace } from "../hub/claude-failure-stage.ts";
|
|
18
19
|
import type { PermissionMode } from "../hub/permission-mode.ts";
|
|
@@ -52,6 +53,10 @@ export interface ClaudeImplementerOptions {
|
|
|
52
53
|
/** Host-owned policy and board reads, never native or model-selected authority. */
|
|
53
54
|
admit(env: Envelope): boolean;
|
|
54
55
|
chatTask(): number | undefined;
|
|
56
|
+
/** Host-only schedule provenance; unknown is not an assignment trigger. */
|
|
57
|
+
scheduledTask?(task: number): boolean | undefined;
|
|
58
|
+
/** Host-only privacy and current-owner check for the task-id hint; absent or unknown withholds it. */
|
|
59
|
+
taskHintAllowed?(task: number): boolean;
|
|
55
60
|
onUsage?(usage: ReviewerPrintUsage, task?: number): void;
|
|
56
61
|
notify?(message: string): void;
|
|
57
62
|
/** Test/embedding-only proof port; project configuration cannot select it. */
|
|
@@ -243,8 +248,13 @@ export class ClaudeImplementerPeer extends BasePeer {
|
|
|
243
248
|
AGENTHUB_INSTANCE_ID: this.options.instanceId, AGENTHUB_LAUNCH_ID: launchId, AGENTHUB_HOOK_PURPOSE: "permission", AGENTHUB_PERMISSION_TOOL: "1" };
|
|
244
249
|
const mcp = JSON.stringify({ mcpServers: { "agent-hub": { command: process.execPath, args: ["run", this.options.server], env } } });
|
|
245
250
|
let result = false, failed = false;
|
|
251
|
+
if (!current() || !this.binding?.() || group.envs.some(env => env.private || !this.options.admit(env))) throw new Error("Claude implementer admission changed before child start");
|
|
252
|
+
let taskPrivate = group.task !== undefined;
|
|
253
|
+
try { if (group.task !== undefined) taskPrivate = this.options.taskHintAllowed?.(group.task) !== true; } catch { /* Unknown is private. */ }
|
|
254
|
+
const attribution = turnAttribution(group.envs, { task: group.task, cloud: true, scheduled: this.options.scheduledTask });
|
|
255
|
+
if (taskPrivate) attribution.private = true;
|
|
246
256
|
const child = new OwnedPrintChild({ peer: this.id, command: this.command!, args: claudeImplementerArgs(turn, mcp, settings, this.options.systemPrompt, model), cwd: this.options.cwd,
|
|
247
|
-
input: group.envs.map(frame).join("\n\n"), env, current, stop: this.options.stopChild,
|
|
257
|
+
input: group.envs.map(frame).join("\n\n"), env, attribution, current, stop: this.options.stopChild,
|
|
248
258
|
onSpawn: () => {
|
|
249
259
|
try {
|
|
250
260
|
if (!this.binding?.() || group.envs.some(env => env.private || !this.options.admit(env))) throw new Error("Claude implementer admission changed before child start");
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
2
|
import { peerChildEnv, stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
|
|
3
3
|
import type { Envelope } from "../hub/envelope.ts";
|
|
4
|
+
import { applyTurnAttribution, type TurnAttribution } from "../hub/turn-attribution.ts";
|
|
4
5
|
|
|
5
6
|
export interface OwnedInputContext { readonly sessionId: string; readonly inputId: string }
|
|
6
7
|
export type OwnedInputObserver = (context: OwnedInputContext, envs: readonly Envelope[]) => void;
|
|
@@ -12,6 +13,8 @@ export interface OwnedPrintChildOptions {
|
|
|
12
13
|
args: readonly string[];
|
|
13
14
|
cwd: string;
|
|
14
15
|
env?: NodeJS.ProcessEnv;
|
|
16
|
+
/** Host-derived hints for this child; never native or project configuration authority. */
|
|
17
|
+
attribution?: TurnAttribution;
|
|
15
18
|
envMode?: "replace";
|
|
16
19
|
input: string;
|
|
17
20
|
/** Metadata only: fires after stdin has flushed successfully while the owning generation is current. */
|
|
@@ -58,7 +61,7 @@ export class OwnedPrintChild {
|
|
|
58
61
|
if (!command) throw new Error("print child command is missing");
|
|
59
62
|
const child = this.process = spawn(command, [...prefix, ...options.args], {
|
|
60
63
|
cwd: options.cwd, detached: true,
|
|
61
|
-
env: peerChildEnv(options.peer, options.envMode === "replace" ? options.env : { ...process.env, ...options.env }),
|
|
64
|
+
env: applyTurnAttribution(peerChildEnv(options.peer, options.envMode === "replace" ? options.env : { ...process.env, ...options.env }), options.attribution),
|
|
62
65
|
stdio: ["pipe", "pipe", options.captureStderr ? "pipe" : "ignore"],
|
|
63
66
|
});
|
|
64
67
|
// ponytail: 256 KiB per NDJSON frame and 4 MiB stdout by default; raise only with native receipts.
|
|
@@ -196,7 +196,8 @@ async function prompt(id: number, text: string) {
|
|
|
196
196
|
await sleep(delay);
|
|
197
197
|
const items = text.split('[agent-hub message from "').length - 1;
|
|
198
198
|
const memo = text.includes("Shared project memory") ? " +memory" : "";
|
|
199
|
-
|
|
199
|
+
const parts = text.includes("FINAL_FYI_TEST_ONLY") ? ["[FYI]"] : ["echo: ", text.split("\n").at(-1)! + verdict + (items > 1 ? ` (${items} items)` : "") + memo];
|
|
200
|
+
for (const part of parts) {
|
|
200
201
|
send({
|
|
201
202
|
jsonrpc: "2.0",
|
|
202
203
|
method: "session/update",
|
|
@@ -108,7 +108,7 @@ export function startFakeAppServer(
|
|
|
108
108
|
const item = (id: string, phase: string, t: string) =>
|
|
109
109
|
note("item/completed", { threadId, turnId: turn.id, completedAtMs: Date.now(), item: { type: "agentMessage", id, phase, text: t } });
|
|
110
110
|
item("m1", "commentary", "thinking out loud");
|
|
111
|
-
item("m2", "final_answer", `echo: ${text}${steered.map((s) => ` +steered: ${s}`).join("")}`);
|
|
111
|
+
item("m2", "final_answer", text.includes("FINAL_FYI_TEST_ONLY") ? "[FYI]" : `echo: ${text}${steered.map((s) => ` +steered: ${s}`).join("")}`);
|
|
112
112
|
// As Codex 0.156 reports it: the thread's running total and what this update added, 100 tokens per turn.
|
|
113
113
|
threadTotal += 100;
|
|
114
114
|
note("thread/tokenUsage/updated", { threadId, turnId: turn.id, tokenUsage: { total: usage(threadTotal), last: usage(100) } });
|
|
@@ -23,6 +23,7 @@ import { safeModelLabel } from "../omniroute/usage.ts";
|
|
|
23
23
|
import { effectiveLocalRoute } from "../hub/routing.ts";
|
|
24
24
|
import type { ExecutionBudgetDecision } from "../hub/execution-budget.ts";
|
|
25
25
|
import type { OwnedInputContext, OwnedInputObserver } from "./claude-print-child.ts";
|
|
26
|
+
import { applyTurnAttribution, turnAttribution } from "../hub/turn-attribution.ts";
|
|
26
27
|
import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
27
28
|
import { GUIDANCE_PROBE_MODEL, GUIDANCE_PROBE_SESSION_BYTES, guidanceProbeCanonical, probeHash, probeInteger,
|
|
28
29
|
type ProbeResourceCharges, type ProbeSlot, type ProbeStoredState } from "../hub/guidance-probes.ts";
|
|
@@ -83,6 +84,8 @@ export interface LocalOptions {
|
|
|
83
84
|
admitBudget?: (envs: Envelope[], unit: "model_calls" | "tool_calls") => Promise<ExecutionBudgetDecision[]>;
|
|
84
85
|
/** Per-turn policy from the task the delivery carries: the class's route, and whether it is a PII task. */
|
|
85
86
|
turnPolicy?: (envs: Envelope[]) => { route?: string; fixedModel?: string; pii: boolean; task?: string } | undefined;
|
|
87
|
+
/** Host-only schedule provenance for a task associated with this turn. */
|
|
88
|
+
scheduledTask?: (task: number) => boolean | undefined;
|
|
86
89
|
/** Role contract, appended to the system prompt. */
|
|
87
90
|
preamble?: string;
|
|
88
91
|
watchdogMs?: number;
|
|
@@ -483,7 +486,7 @@ export class LocalPeer extends BasePeer {
|
|
|
483
486
|
const fixedPrompt = this.probeConfinement
|
|
484
487
|
? this.probeSession?.prepared.request.messages[0]?.content ?? (() => { throw new ProbeLocalError("invalid"); })()
|
|
485
488
|
: this.turnRecordPrompt(system(this.opts.cwd, this.opts.preamble));
|
|
486
|
-
const ctx = this.toolContext(envs, turnSignal, !!policy?.pii, reply);
|
|
489
|
+
const ctx = this.toolContext(envs, turnSignal, !!policy?.pii, reply, policy?.task);
|
|
487
490
|
let usedTools = false;
|
|
488
491
|
let captureInvocation = 0;
|
|
489
492
|
for (let step = 0; step < maxSteps; step++) {
|
|
@@ -556,7 +559,7 @@ export class LocalPeer extends BasePeer {
|
|
|
556
559
|
/** The base tools, plus `doc_read` and `web_fetch` only when the project opted in (`local.doc_read`, `local.web_fetch.allow`; both off by default). */
|
|
557
560
|
private toolSchemas() { if (this.probeConfinement) return probeSchemas(); const extra = [...(this.opts.tools.docRead ? [DOC_READ_SCHEMA] : []), ...(this.opts.tools.webFetch ? [WEB_FETCH_SCHEMA] : [])]; return extra.length ? [...TOOL_SCHEMAS, ...extra] : TOOL_SCHEMAS; }
|
|
558
561
|
|
|
559
|
-
private toolContext(envs: Envelope[], turnSignal: AbortSignal, pii: boolean, reply: EnvelopeOpts): ToolContext {
|
|
562
|
+
private toolContext(envs: Envelope[], turnSignal: AbortSignal, pii: boolean, reply: EnvelopeOpts, task?: string): ToolContext {
|
|
560
563
|
const executionGeneration=this.turn;
|
|
561
564
|
const probe = this.probeSession;
|
|
562
565
|
const context: ToolContext = {
|
|
@@ -608,7 +611,8 @@ export class LocalPeer extends BasePeer {
|
|
|
608
611
|
},
|
|
609
612
|
shellExecutionCheck: input=>turnSignal.aborted||executionGeneration!==this.turn?"aborted":this.opts.tools.shellExecutionCheck?.(input)??"valid",
|
|
610
613
|
sandboxProfile: this.sandboxProfile,
|
|
611
|
-
sandboxEnv: this.probeConfinement ? { ...this.probeConfinement.env } : { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
|
|
614
|
+
sandboxEnv: applyTurnAttribution(this.probeConfinement ? { ...this.probeConfinement.env } : { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
|
|
615
|
+
this.probeConfinement ? undefined : turnAttribution(envs, { task: task === undefined ? undefined : Number(task), scheduled: this.opts.scheduledTask })) as Record<string, string>,
|
|
612
616
|
signal: turnSignal,
|
|
613
617
|
send: (text, to) => {
|
|
614
618
|
if (this.probeConfinement) return "error: messaging unavailable in guidance probe";
|
|
@@ -2,6 +2,7 @@ import type { ModelOverrideSelection } from "./registry-types.ts";
|
|
|
2
2
|
import { isNativeModelToken } from "./model-token.ts";
|
|
3
3
|
import type { ChildProcess } from "node:child_process";
|
|
4
4
|
import { OwnedPrintChild, PrintChildCleanupError, type OwnedInputContext, type OwnedInputObserver, type OwnedStderrReceipt } from "./claude-print-child.ts";
|
|
5
|
+
import { turnAttribution } from "../hub/turn-attribution.ts";
|
|
5
6
|
import { randomUUID } from "node:crypto";
|
|
6
7
|
import { HUB, frame, sanitize } from "../hub/envelope.ts";
|
|
7
8
|
import { BasePeer } from "../hub/peers.ts";
|
|
@@ -555,8 +556,9 @@ export class ReviewerPrintPeer extends BasePeer {
|
|
|
555
556
|
// The journal intent precedes spawn: the native agent-file already contains the review facts.
|
|
556
557
|
this.assertAdmission(env, task, binding);
|
|
557
558
|
}
|
|
559
|
+
this.assertAdmission(env, task, binding);
|
|
558
560
|
const child = new OwnedPrintChild({ peer: this.id, command: launch.command, args: launch.args,
|
|
559
|
-
cwd: launch.cwd ?? this.opts.cwd, env: launch.env, envMode: launch.envMode, input,
|
|
561
|
+
cwd: launch.cwd ?? this.opts.cwd, env: launch.env, envMode: launch.envMode, input, attribution: turnAttribution([env], { task, cloud: true }),
|
|
560
562
|
...(this.opts.backend.failureOnExit ? { captureStderr: true as const } : {}),
|
|
561
563
|
current: () => generation === this.generation, stop: launch.stop,
|
|
562
564
|
onInputReleased: () => { inputReleased = true; this.opts.inputReleased?.(inputContext, [env]); },
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { configuredPolicy, memoryHome, withCliAttribution } from "@staix/agent-mem";
|
|
2
|
+
|
|
3
|
+
/** Run an agent's memory commands in the public amem attribution and visibility scope. */
|
|
4
|
+
export async function withAgentAttribution<T>(peer: string, cwd: string, work: () => Promise<T>): Promise<T> {
|
|
5
|
+
return withCliAttribution({ actor: "agent", peer, policy: () => configuredPolicy(memoryHome(), cwd) }, work);
|
|
6
|
+
}
|
package/src/cli/help.ts
CHANGED
|
@@ -75,7 +75,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
75
75
|
["ahub down", "stop this project's hub, the counterpart of ahub up (same as ahub kill)"],
|
|
76
76
|
["ahub reset [--all] [--yes]", "list, then with --yes stop the hub and discard every queued and needs_review delivery, clear holds and pauses and drop session pointers; --all moves the state directory to .agenthub/archive instead"],
|
|
77
77
|
["ahub restart [--dry-run] [--yes] [--json] [--verbose] [--color=auto|always|never]", "recover this project's runtime; a configured conductor's --yes requires a same-project, source-issued continuation proof, otherwise run it as the person"],
|
|
78
|
-
["ahub upgrade [--project <path|id>] [--to <version>] [--dry-run] [--yes] [--json] [--verbose] [--color=auto|always|never]", "review and upgrade this selected project (default: current directory; --project selects another); global CLI/plugin updates are separate; --to defaults to latest for interactive review or dry-run, while --yes requires --to <exact-version
|
|
78
|
+
["ahub upgrade [--project <path|id> | --all-stopped] [--to <version>] [--dry-run] [--yes] [--json] [--verbose] [--color=auto|always|never]", "review and upgrade this selected project (default: current directory; --project selects another); a project whose hub is stopped has only its runtime selection retargeted: no hub, terminal, peer or recovery operation is started; --all-stopped does that for every registered stopped project, each independently (rows: retarget, already at <v>, skipped: running with its per-project command, refused: <cause> with its next step), exits nonzero when a planned retarget fails, and conflicts with --project; global CLI/plugin updates are separate; --to defaults to latest for interactive review or dry-run, while --yes requires --to <exact-version>, and for a running hub waits through a pipe until its recovery operation ends and exits nonzero unless it completed; conductor apply needs the same project's supported proof (a stopped-project retarget is person-only), and a newer-coordinator handoff is person-only"],
|
|
79
79
|
["ahub recovery [status|resume|abort] [<operation-id>] [--json] [--color=auto|always|never]", "inspect a preflight; without an id, resume/abort select this project's hold or a retained legacy machine hold; a bare terminal opens the person's screen; only its initiating conductor may continue its own supported restart/upgrade with fresh proof"],
|
|
80
80
|
["ahub recovery reattach <operation-id> codex|claude|pi", "person only: repair that blocked peer with its recorded session; leaves the rest for recovery resume"],
|
|
81
81
|
["ahub recovery dispose [<operation-id>] --fresh-session codex|claude --reason <text>", "end a partial operation by starting that peer as a new session, recording the lost conversation"],
|
|
@@ -106,7 +106,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
106
106
|
["ahub autonomy on [--all-projects] [--yes] | off [--all-projects] | status [--json]", "person only: apply the autonomy preset and machine default with one confirmation, optionally to every registered project; off removes fixed preset keys (manual edits included); status reports modes, floor enforcement and Claude homes; settings undo restores a live-hub project write"],
|
|
107
107
|
["ahub model set <peer> <model> | clear <peer> | list [--json]", "person only: select a runtime model at the next turn, clear its override, or inspect effective models and pending changes; unsupported peers need a restart"],
|
|
108
108
|
["ahub settings [list] [--json] | get <key> [--json]", "the settings the dashboard can change, each with its value, the file it comes from and when it applies; get sdlc.mode or sdlc.required_checks reads running and file values without adding writable keys"],
|
|
109
|
-
["ahub settings set <key> <value|inherit> [--yes] [--preview] [--now] | undo | reload", "validated settings: conductor set is limited to exact live operational keys; undo/reload and other keys are person only; --preview saves nothing; conductor writes keep the person undo record"],
|
|
109
|
+
["ahub settings set <key> <value|inherit> [--yes] [--preview] [--now] | undo | reload", "validated settings: memory.sync_interval_min applies live (0 disables sync); conductor set is limited to exact live operational keys; undo/reload and other keys are person only; --preview saves nothing; conductor writes keep the person undo record"],
|
|
110
110
|
["ahub settings edit <config.local.json|sdlc.toml> (set <path> <json> | remove <path>)... [--reason <text>] [--preview] [--yes] | backups [--json]", "human only: structural config (instances, review, snapshots, approvals, context.gate, research.runners, sdlc.toml mode and required_checks) validated by the hub's own loaders, previewed as a diff and written with a backup; a key that runs code or locates secrets needs its name typed, never --yes"],
|
|
111
111
|
["ahub pause|resume <peer>", "hold a peer's deliveries in its queue / release them"],
|
|
112
112
|
["ahub title <peer> <text...>", "person only: replace a Pi or local-worker session title; native-title peers rename in their own UI"],
|
|
@@ -198,11 +198,11 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
198
198
|
["ahub check-path <file> [--peer <id>]", "other owners' open tasks that claim or changed a file"],
|
|
199
199
|
["ahub memory [list] [--tier short|long] [--kind <kind>] [--peer <p>] [--machine <id>] [--since <iso>] [--limit N] [--json]", "the hub's own memory for this project: decisions, contracts, fails and findings, short- and long-term (docs/memory.md)"],
|
|
200
200
|
["ahub memory search <words> [--ungrouped] | show <id> | graph <id|node> [--hops 1|2] [--history | --as-of <iso>] [--json]", "find entries, read one with its provenance, or list its graph neighbourhood; search groups visible hits by task unless --ungrouped; superseded and expired entries are hidden unless a person asks for --history or --as-of"],
|
|
201
|
-
["ahub memory promote|demote|forget <id> | supersede <old> <new> | rebuild", "
|
|
202
|
-
["ahub memory sync [--remote <private git url>] | machine [--label <name>]", "sync hub memory with your other machines through a private git remote
|
|
203
|
-
["ahub memory import claude-mem [--db <path>] [--limit N] [--restart] | dedupe [--apply] | suggestions | confirm|reject <id>", "copy the hub's notes from claude-mem into hub memory
|
|
204
|
-
["ahub memory decay [--days N] [--json]", "
|
|
205
|
-
["ahub memory declined [--json]", "
|
|
201
|
+
["ahub memory promote|demote|forget <id> | supersede <old> <new> | rebuild", "change memory: move an entry between tiers, forget it, mark it superseded, or rebuild the index from the logs; an agent shell's change is recorded as that agent"],
|
|
202
|
+
["ahub memory sync [--remote <private git url>] | machine [--label <name>]", "sync hub memory with your other machines through a private git remote, or show or name this machine"],
|
|
203
|
+
["ahub memory import claude-mem [--db <path>] [--limit N] [--restart] | dedupe [--apply] | suggestions | confirm|reject <id>", "copy the hub's notes from claude-mem into hub memory; review the model's suggested edges (confirm and reject are a person's)"],
|
|
204
|
+
["ahub memory decay [--days N] [--json]", "list long-term entries older than N days (default 90) that no open goal links; review only, nothing is changed"],
|
|
205
|
+
["ahub memory declined [--json]", "list declined physical outbound row ids and safe rule labels; never shows row text; reports incomplete scans explicitly"],
|
|
206
206
|
["ahub memory profile-check [--json]", "read-only check of the running hubs' memory bindings against their memory profiles; exits 1 when one is not ready"],
|
|
207
207
|
["ahub goal [list] [--all] | show <id> [--json]", "long-term tasks: state, which machine holds each and until when, linked board tasks"],
|
|
208
208
|
["ahub goal new <title> [--milestone <text>]... [--depends <id>]... [--shared] | link <id> <task> | state <id> <state> | done <id> | take <id> [--force]", "a person's changes to long-term tasks (link also the configured conductor's); take --force voids other machines' claims"],
|
|
@@ -385,7 +385,7 @@ export const FLAG_DESCRIPTIONS: Readonly<Record<string, string>> = {
|
|
|
385
385
|
"--specs": "turn design specs on", "--no-specs": "turn design specs off", "--spec-review": "how covering specs are reviewed", "--conductor": "the peer that conducts, or none", "--planner": "peers that plan",
|
|
386
386
|
"--reviewer": "peers that review, or person", "--track-config": "share config.json through git", "--no-track-config": "keep config.json out of git", "--autonomy": "inherit the machine preset, or not",
|
|
387
387
|
"--shadow": "hub-owned snapshots for a non-git folder", "--release-guard": "install the tag pre-push hook", "--focus": "area the survey looks at", "--review": "review scope: full, delta or none",
|
|
388
|
-
"--reviewers": "number of reviewers", "--ci": "CI scope: full, focused or reuse", "--reserved": "reserve the card for this peer", "--unreserve": "clear the card's reservation", "--to": "version to upgrade to",
|
|
388
|
+
"--reviewers": "number of reviewers", "--ci": "CI scope: full, focused or reuse", "--reserved": "reserve the card for this peer", "--unreserve": "clear the card's reservation", "--to": "version to upgrade to", "--all-stopped": "retarget every stopped project's runtime",
|
|
389
389
|
"--version": "print the installed version",
|
|
390
390
|
// daemon, agents and recovery
|
|
391
391
|
"--unattended": "no permission prompts; the agent acts alone", "--no-console": "do not enter the console", "--no-agents": "do not start the default agents", "--panels": "start in panels mode",
|
package/src/cli/identity.ts
CHANGED
|
@@ -18,6 +18,8 @@ export function liveTestRefusal(command: string, args: readonly string[], contex
|
|
|
18
18
|
if (command === "roadmap" && ![undefined, "list", "show", "--json"].includes(args[0])) return true;
|
|
19
19
|
if (command === "roadmap" && args[0] === "--json" && ![undefined, "list", "show"].includes(args[1])) return true;
|
|
20
20
|
if (command === "sdlc" && args[0] === "configure") return true;
|
|
21
|
+
// #1540: retargeting a stopped project's runtime or every stopped one is the person's choice of which code runs next; an agent shell must not reach it through `--live-test`.
|
|
22
|
+
if (command === "upgrade" && args.includes("--all-stopped")) return true;
|
|
21
23
|
if (command === "lineage" && args[0] === "link") return true;
|
|
22
24
|
if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
|
|
23
25
|
if (command === "sdlc" && args[0] === "survey" && args[1] !== "show") return true;
|
|
@@ -78,6 +80,11 @@ export function detectCliIdentity(env: Readonly<Record<string, string | undefine
|
|
|
78
80
|
|
|
79
81
|
export type PeerCommandAccess = "allowed" | "conductor" | "console";
|
|
80
82
|
|
|
83
|
+
/** #1522: the `ahub memory` subcommands an agent shell runs (reads, and the changes amem records under the agent's own name). Anything else in the family stays the person's. */
|
|
84
|
+
export const AGENT_MEMORY_SUBS: readonly string[] = ["list", "search", "show", "suggestions", "machine", "sync", "import", "dedupe", "promote", "demote", "forget", "supersede", "rebuild", "decay", "declined"];
|
|
85
|
+
/** The ones that change memory and record an actor: `memoryCommand` runs these under the agent's attribution. Reads and the two review previews run unchanged. */
|
|
86
|
+
export const AGENT_MEMORY_RECORDING_SUBS: readonly string[] = ["sync", "import", "dedupe", "promote", "demote", "forget", "supersede", "rebuild"];
|
|
87
|
+
|
|
81
88
|
/** Flags the read-only forms of #812 accept: display options that change no behaviour. */
|
|
82
89
|
const peerReadFlags = (args: readonly string[]): boolean =>
|
|
83
90
|
args.every((arg) => ["--json", "--full", "--verbose", "--color=always", "--color=never", "--color=auto"].includes(arg) || arg.startsWith("--color="));
|
|
@@ -192,8 +199,9 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
|
|
|
192
199
|
if (command === "agents") return args.every(arg => arg === "--json") ? "allowed" : "console";
|
|
193
200
|
// #247: reading the research measures and records is harmless (ids and counts only); #933 made backfill a conductor operation (above).
|
|
194
201
|
if (command === "research") return args[0] === "backfill" ? "console" : "allowed";
|
|
195
|
-
// #
|
|
196
|
-
|
|
202
|
+
// #1522 (hub task 969): an agent shell runs the memory family as itself. The CLI wraps the writers in amem's agent attribution (`memoryCommand`), so the recorded and displayed actor is the agent, never the person.
|
|
203
|
+
// Left to the person: `graph` (its labels are unscreened note text), `confirm`/`reject` (judgments of suggested links), `profile-check` and every command outside `memory`; hub verdicts are not memory commands.
|
|
204
|
+
if (command === "memory") { const sub = args.find((arg) => arg !== "--json"); return sub === undefined || sub.startsWith("--") || AGENT_MEMORY_SUBS.includes(sub) ? "allowed" : "console"; }
|
|
197
205
|
if (command === "goal") { const sub = args.find((arg) => arg !== "--json"); return sub === undefined || sub.startsWith("--") || ["list", "show"].includes(sub) ? "allowed" : "console"; }
|
|
198
206
|
// #251: a run resets the bench project's tree and proposes work (#933: a conductor operation, above); reading results is harmless.
|
|
199
207
|
// The subcommand is the first argument that is not --json, which the command accepts anywhere.
|
package/src/cli/main.ts
CHANGED
|
@@ -100,11 +100,13 @@ import { childEnv, personEnv } from "../hub/child-process.ts";
|
|
|
100
100
|
import { abortRecovery, createOperation, disposeRecovery, recordRecoveryDelegation, repairedFreshSession, reattachRecovery, liveProjects, nextChoices, nextActionsText, publicOperation, recoveryCommand, registeredProjects, runRecovery, type RecoveryOperation, type Inspection } from "./upgrade.ts";
|
|
101
101
|
import { endPlannedPeer, makeRecoveryDriver, makeUpgradePlan, preserveSource, reattachPlannedTerminals } from "./upgrade-runtime.ts";
|
|
102
102
|
import { exactVersion, latestRelease, newerVersion } from "./recovery-package.ts";
|
|
103
|
+
import { applyStoppedRetargets, planStoppedRetargets } from "./upgrade-stopped.ts";
|
|
104
|
+
import { awaitOperationEnd } from "./upgrade-wait.ts";
|
|
103
105
|
import { globalUpdateAdvice, runtimeVersionWarnings } from "./runtime-version-warning.ts";
|
|
104
106
|
import { operationScreen, planScreen, type ScreenIO, type UpgradeHost } from "./upgrade-interactive.ts";
|
|
105
107
|
import { readRecoveryPresentationFlags } from "./upgrade-presentation-flags.ts";
|
|
106
108
|
import { renderOperation, renderBlocked, renderSummary, type RecoveryPresentationOptions } from "./upgrade-presentation.ts";
|
|
107
|
-
import { renderBudgetResult, renderRecoveryStatus, renderUpgradePlan } from "./upgrade-output.ts";
|
|
109
|
+
import { renderBudgetResult, renderRecoveryStatus, renderStoppedPlan, renderStoppedResults, renderUpgradePlan } from "./upgrade-output.ts";
|
|
108
110
|
import { recordTerminalLaunch, prepareTerminalLaunch, registerTerminalLaunch, type TerminalPeer } from "./terminal-recovery.ts";
|
|
109
111
|
import { effectiveStartAgents, inheritMachineStart, setupStartAgents, startProjectAgents } from "./start-agents-run.ts";
|
|
110
112
|
import { ensureMlx, inspectMlx, stopMlx } from "../models/mlx.ts";
|
|
@@ -771,11 +773,53 @@ function globalUpdateLines(target: string): string[] {
|
|
|
771
773
|
probe: () => spawnSync(DOCTOR_PLUGIN_PROBE.command, [...DOCTOR_PLUGIN_PROBE.argv], { encoding: "utf8", timeout: 10_000 }) });
|
|
772
774
|
}
|
|
773
775
|
|
|
776
|
+
/**
|
|
777
|
+
* #1540: `ahub upgrade` for a project whose hub is stopped (this one, or every registered one with `--all-stopped`): the runtime selection is rewritten and nothing else is started or recorded.
|
|
778
|
+
* True when it handled the command. A single project whose hub is running, or that is not registered, is left to the ordinary recovery plan.
|
|
779
|
+
*/
|
|
780
|
+
async function stoppedUpgrade(to: string, all: boolean, display: ReturnType<typeof recoveryDisplay>, yes: boolean, dry: boolean): Promise<boolean> {
|
|
781
|
+
let plan: Awaited<ReturnType<typeof planStoppedRetargets>>;
|
|
782
|
+
try { plan = await planStoppedRetargets(to, all ? "all" : { root: cwd }); } catch (error) { return fail((error as Error).message); }
|
|
783
|
+
// One project whose hub is not positively stopped (or missing) keeps the ordinary plan, with its own blockers; "unknown" is never read as stopped.
|
|
784
|
+
if (!all && !plan.rows.some((row) => row.inspected === "stopped" || row.inspected === "missing")) return false;
|
|
785
|
+
if (display.json) {
|
|
786
|
+
if (!yes || dry) console.log(JSON.stringify(plan, null, 2));
|
|
787
|
+
for (const blocker of plan.blockers) console.error(`ahub: blocker: ${blocker}`);
|
|
788
|
+
} else printRecovery(renderStoppedPlan(plan, VERSION, display.options, yes && !dry));
|
|
789
|
+
if (dry) return true;
|
|
790
|
+
if (plan.blockers.length) fail("plan has blockers; no runtime was changed");
|
|
791
|
+
const retargets = plan.rows.filter((row) => row.outcome === "retarget");
|
|
792
|
+
// Nothing to retarget is still an outcome: a JSON consumer of an idempotent `--yes` run gets the same results document the apply path prints, with no results.
|
|
793
|
+
if (!retargets.length) { if (display.json && yes) console.log(JSON.stringify({ version: plan.version, results: [] }, null, 2)); return true; }
|
|
794
|
+
// The runtime selection decides which code runs a project next: that is the person's choice, as the plan of a running hub is for a conductor only with its source-issued proof.
|
|
795
|
+
if (conductorPeer || delegatedPeer) fail("retargeting a stopped project's runtime is the person's: run it in ahub console or a terminal; no runtime was changed");
|
|
796
|
+
if (!yes) {
|
|
797
|
+
if (!process.stdin.isTTY) fail("review --dry-run and use --yes in non-interactive sessions");
|
|
798
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
799
|
+
try {
|
|
800
|
+
if (!/^(y|yes)$/i.test((await rl.question(`Retarget ${retargets.length} stopped project${retargets.length === 1 ? "" : "s"} without starting ${retargets.length === 1 ? "its hub" : "their hubs"}? [y/N] `)).trim())) return true;
|
|
801
|
+
} finally { rl.close(); }
|
|
802
|
+
const current = await planStoppedRetargets(to, all ? "all" : { root: cwd });
|
|
803
|
+
if (current.fingerprint !== plan.fingerprint) fail("plan changed during review; run the command again");
|
|
804
|
+
}
|
|
805
|
+
const results = await applyStoppedRetargets(plan);
|
|
806
|
+
const failed = results.filter((result) => result.outcome === "failed");
|
|
807
|
+
if (display.json) console.log(JSON.stringify({ version: plan.version, results }, null, 2));
|
|
808
|
+
else {
|
|
809
|
+
printRecovery(renderStoppedResults(results, display.options));
|
|
810
|
+
if (!failed.length) printRecovery(globalUpdateLines(plan.version));
|
|
811
|
+
}
|
|
812
|
+
if (failed.length) fail(`${failed.length} of ${results.length} planned retarget${results.length === 1 ? "" : "s"} failed (${failed.map((result) => result.id).join(", ")}); the others stay retargeted`);
|
|
813
|
+
return true;
|
|
814
|
+
}
|
|
815
|
+
|
|
774
816
|
async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
|
|
775
817
|
const display = recoveryDisplay();
|
|
776
818
|
const { one, rest } = takeFlags(display.args, ["--to"], []);
|
|
777
|
-
if (rest.some((a) => !["--dry-run", "--yes"].includes(a)) || (kind === "restart" && one["--to"])) fail("usage: ahub upgrade [--project <path|id>] [--to <version>] [--dry-run] [--yes] | ahub restart [--dry-run] [--yes]");
|
|
819
|
+
if (rest.some((a) => !["--dry-run", "--yes", ...(kind === "upgrade" ? ["--all-stopped"] : [])].includes(a)) || (kind === "restart" && one["--to"])) fail("usage: ahub upgrade [--project <path|id> | --all-stopped] [--to <version>] [--dry-run] [--yes] | ahub restart [--dry-run] [--yes]");
|
|
778
820
|
const yes = rest.includes("--yes"), dry = rest.includes("--dry-run") || (display.json && !yes);
|
|
821
|
+
const allStopped = rest.includes("--all-stopped");
|
|
822
|
+
if (allStopped && selector !== undefined) fail("--all-stopped and --project are conflicting selectors: --all-stopped covers every registered stopped project");
|
|
779
823
|
// #272: on a terminal, with neither flag, the plan is reviewed, applied and followed in one session.
|
|
780
824
|
const interactive = !dry && !yes && humanRecovery(display.json);
|
|
781
825
|
let to = one["--to"];
|
|
@@ -789,7 +833,7 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
|
|
|
789
833
|
// An older CLI must not coordinate a newer target (docs/operations.md): the target's own coordinator takes over.
|
|
790
834
|
if (conductorPeer && kind === "upgrade" && newerVersion(to!, VERSION)) fail("a supporting target coordinator is required; the person runs it in ahub console or a terminal");
|
|
791
835
|
if (kind === "upgrade" && newerVersion(to!, VERSION) && process.env.AGENTHUB_UPGRADE_HANDOVER !== "1") {
|
|
792
|
-
const argv = ["x", "--package", `@staix/agent-hub@${to}`, "ahub", "--project", cwd, ...liveTestArgs, "upgrade", "--to", to!, ...rest, ...display.flags, ...(dry && !rest.includes("--dry-run") ? ["--dry-run"] : [])];
|
|
836
|
+
const argv = ["x", "--package", `@staix/agent-hub@${to}`, "ahub", ...(allStopped ? [] : ["--project", cwd]), ...liveTestArgs, "upgrade", "--to", to!, ...rest, ...display.flags, ...(dry && !rest.includes("--dry-run") ? ["--dry-run"] : [])];
|
|
793
837
|
console.error(`ahub: ${to} is newer than this CLI (${VERSION}), so its own coordinator runs the upgrade: bun ${argv.join(" ")}`);
|
|
794
838
|
if (interactive) {
|
|
795
839
|
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
@@ -805,6 +849,7 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
|
|
|
805
849
|
});
|
|
806
850
|
process.exit(code);
|
|
807
851
|
}
|
|
852
|
+
if (kind === "upgrade" && await stoppedUpgrade(to!, allStopped, display, yes, dry)) return;
|
|
808
853
|
if (kind === "upgrade") console.error("ahub: Kimi now defaults to its own TUI (pull-only) in projects without peers.kimi.start_mode. To keep ACP: ahub settings set peers.kimi.start_mode headless");
|
|
809
854
|
if (interactive) return onTerminal((io) => planScreen(upgradeHost(kind, to ?? VERSION), io), display.options);
|
|
810
855
|
const plan = await makeUpgradePlan(kind, to ?? VERSION, cwd, undefined, conductorPeer);
|
|
@@ -816,7 +861,7 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
|
|
|
816
861
|
if (!jsonApply) console.log(JSON.stringify(plan, null, 2));
|
|
817
862
|
for (const p of plan.projects) for (const peer of p.reconnectOnly ?? []) console.error(`ahub: ${p.project.id}: ${peer} is reconnect-only (unmanaged session): its plugin reattaches to the new hub; no terminal is closed or relaunched`);
|
|
818
863
|
for (const p of plan.projects) for (const peer of p.freshStart ?? []) console.error(`ahub: ${p.project.id}: ${peer} restarts as a new session: its thread has no rollout and the hub recorded no turn on it, so nothing is lost`);
|
|
819
|
-
} else printRecovery(renderUpgradePlan(plan, VERSION, display.options));
|
|
864
|
+
} else printRecovery(renderUpgradePlan(plan, VERSION, display.options, yes && !dry));
|
|
820
865
|
const blockers = [...plan.blockers, ...plan.projects.flatMap((p) => p.blockers.map((b) => `${p.project.id}: ${b}`))];
|
|
821
866
|
if (display.json) for (const blocker of blockers) console.error(`ahub: blocker: ${blocker}`);
|
|
822
867
|
if (dry) return;
|
|
@@ -850,6 +895,13 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
|
|
|
850
895
|
// #718: the upgrade is only scheduled here, but the step is already known: the CLI and the plugin are compared with the daemon this upgrade installs. Never in --json, which stays the raw document.
|
|
851
896
|
if (kind === "upgrade") printRecovery(globalUpdateLines(plan.version));
|
|
852
897
|
}
|
|
898
|
+
if (kind === "upgrade" && yes && !process.stdout.isTTY) {
|
|
899
|
+
const ended = await awaitOperationEnd(operation, { read: (id) => readOperation<RecoveryOperation>(id), runner: (id) => recoveryRunner(id), now: Date.now, sleep: Bun.sleep });
|
|
900
|
+
if (ended.phase === "completed") { if (!display.json) console.log(`${kind} to ${plan.version} completed`); return; }
|
|
901
|
+
fail(ended.phase === "blocked" || ended.phase === "cancelled"
|
|
902
|
+
? `${kind} operation ${operation.id} is ${ended.phase}${ended.error ? `: ${ended.error.split("; next actions: ")[0]}` : ""}; ${nextActionsText(ended)}`
|
|
903
|
+
: `operation ${operation.id} did not finish (its runner stopped, or is still working after the wait limit); ${recoveryCommand(operation, "status")}`);
|
|
904
|
+
}
|
|
853
905
|
}
|
|
854
906
|
|
|
855
907
|
/** Strict person command: recorded identity only, no session or terminal overrides. */
|
|
@@ -2857,7 +2909,8 @@ const commands: Record<string, () => Promise<void> | void> = {
|
|
|
2857
2909
|
if (!result.ready) process.exitCode = 1;
|
|
2858
2910
|
return;
|
|
2859
2911
|
}
|
|
2860
|
-
|
|
2912
|
+
// #1522: an agent shell runs this as itself; its peer id, not the person, is what amem records for a change.
|
|
2913
|
+
try { console.log(await memoryCommand(args, cwd, { person: caller.role === "console", ...(caller.role === "tools" ? { agent: caller.peer } : {}) })); } catch (e) { fail((e as Error).message); }
|
|
2861
2914
|
},
|
|
2862
2915
|
goal: async () => {
|
|
2863
2916
|
// #258: long-term tasks; a link goes through the project's hub, so Tasks validates the board task.
|
package/src/cli/memory.ts
CHANGED
|
@@ -12,7 +12,8 @@ import { foldSegment } from "../hub/permission-mode.ts";
|
|
|
12
12
|
import { matchesPolicyLexically } from "../hub/path-policy.ts";
|
|
13
13
|
import { memoryAnchorTaskIdentity, memoryStaleAnchors, unavailableMemoryStaleAnchors, type MemoryStaleAnchorReport, type MemoryTaskPrivacy } from "../hub/memory-stale-anchors.ts";
|
|
14
14
|
import { MEMORY_SYMBOL_START_BUDGET_MS } from "../hub/memory-symbols.ts";
|
|
15
|
-
import { detectCliIdentity } from "./identity.ts";
|
|
15
|
+
import { AGENT_MEMORY_RECORDING_SUBS, detectCliIdentity } from "./identity.ts";
|
|
16
|
+
import { withAgentAttribution } from "./agent-attribution.ts";
|
|
16
17
|
import { createStalenessProbe } from "../hub/memory-staleness.ts";
|
|
17
18
|
import { looksSecret, memoryHome, memoryProjectKey, pathCandidates, readProfileJSON, resolveShardProfile, type MemoryStore } from "@staix/agent-mem";
|
|
18
19
|
import type { SyncOptions } from "@staix/agent-mem";
|
|
@@ -111,6 +112,9 @@ function commandStores(provided: MemoryStore | undefined, options: ProfileMemory
|
|
|
111
112
|
try { return { ...(provided ? bindProfileMemory(provided, undefined, memoryProjectKey(cwd)) : openProfileMemory(options)), owned: !provided }; }
|
|
112
113
|
catch (error) { throw new Error(error instanceof Error && error.message === MEMORY_SPLIT_INCOMPLETE ? error.message : MEMORY_PROFILE_UNAVAILABLE); }
|
|
113
114
|
}
|
|
115
|
+
/** What a JSON receipt may carry for an agent (#1522): the kind, state and generation prefix, never the home path, selector, version or skip totals the person sees. */
|
|
116
|
+
const shownReceipt = (profile: MemoryProfileReceipt | undefined, person: boolean) =>
|
|
117
|
+
person || !profile ? profile : { profile: profile.profile, state: profile.state, ...(profile.generation ? { generation: profile.generation.slice(0, 8) } : {}) };
|
|
114
118
|
function profileOutput(text: string, json: boolean, profile: MemoryProfileReceipt | undefined, person: boolean): string {
|
|
115
119
|
if (!profile) return text;
|
|
116
120
|
if (profile.state !== "ready") throw new Error(MEMORY_PROFILE_UNAVAILABLE);
|
|
@@ -119,12 +123,23 @@ function profileOutput(text: string, json: boolean, profile: MemoryProfileReceip
|
|
|
119
123
|
}
|
|
120
124
|
|
|
121
125
|
/** Hub wrapper: current project policy and TTL stay here; parsing and storage commands belong to the core. */
|
|
122
|
-
export async function memoryCommand(args: string[], cwd: string, opts: { store?: MemoryStore; sync?: Omit<SyncOptions, "remote">; now?: () => number; person?: boolean } = {}): Promise<string> {
|
|
126
|
+
export async function memoryCommand(args: string[], cwd: string, opts: { store?: MemoryStore; sync?: Omit<SyncOptions, "remote">; now?: () => number; person?: boolean; /** The agent shell's peer id (#1522): its changes are recorded under this name. */ agent?: string } = {}): Promise<string> {
|
|
123
127
|
const person = opts.person ?? detectCliIdentity(process.env).role === "console";
|
|
128
|
+
const sub = args.find(arg => arg !== "--json");
|
|
129
|
+
// #1522: an agent runs the family as itself. The recording commands run inside amem's agent attribution, so every writer stamps the agent (never "user")
|
|
130
|
+
// and amem applies its screened-visibility checks to each target; with no agent peer id, or no way to attribute, a change is refused rather than run as the person.
|
|
131
|
+
if (!person && sub !== undefined && AGENT_MEMORY_RECORDING_SUBS.includes(sub)) {
|
|
132
|
+
const peer = opts.agent ?? (() => { const identity = detectCliIdentity(process.env); return identity.role === "tools" ? identity.peer : undefined; })();
|
|
133
|
+
if (peer === undefined) fail(`memory ${sub} changes memory and needs an identified agent or the person; no agent identity was found, so nothing was run`);
|
|
134
|
+
return withAgentAttribution(peer!, cwd, () => memoryCommandBody(args, cwd, opts, person));
|
|
135
|
+
}
|
|
136
|
+
return memoryCommandBody(args, cwd, opts, person);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function memoryCommandBody(args: string[], cwd: string, opts: { store?: MemoryStore; sync?: Omit<SyncOptions, "remote">; now?: () => number }, person: boolean): Promise<string> {
|
|
124
140
|
const privatePaths = (): string[] => { try { return loadConfig(cwd).pii?.paths ?? []; } catch (e) { return fail(`the project's config does not load (${(e as Error).message}); fix it before reading hub memory`); } };
|
|
125
141
|
const rest = args.filter(arg => arg !== "--json");
|
|
126
142
|
if (rest[0] === "decay") {
|
|
127
|
-
if (!person) fail("memory decay requires person authority");
|
|
128
143
|
let days = 90;
|
|
129
144
|
if (rest.length !== 1) {
|
|
130
145
|
if (rest.length !== 3 || rest[1] !== "--days" || !/^[1-9][0-9]*$/.test(rest[2]!)) fail("usage: ahub memory decay [--days N] [--json] (N must be a positive integer)");
|
|
@@ -149,7 +164,8 @@ export async function memoryCommand(args: string[], cwd: string, opts: { store?:
|
|
|
149
164
|
&& !note.about.some(node => openGoals.has(node) || (node.startsWith("task:") && linkedTasks.has(node.slice(5))))), routing, cwd, paths);
|
|
150
165
|
});
|
|
151
166
|
const profile = context.binding.status(store);
|
|
152
|
-
|
|
167
|
+
// #1522: decay is open to an agent, so its JSON carries only the receipt an agent may see.
|
|
168
|
+
if (args.includes("--json")) return profileOutput(JSON.stringify({ days, cutoff, candidates, memoryProfile: shownReceipt(profile, person) }), true, profile, person);
|
|
153
169
|
const text = candidates.length
|
|
154
170
|
? [`${candidates.length} decay candidate${candidates.length === 1 ? "" : "s"} older than ${days} days (review only):`, ...candidates.map(note => `mem:${note.id} ${note.at} ${note.kind}: ${note.title ?? note.text}`)].join("\n")
|
|
155
171
|
: `no decay candidates older than ${days} days`;
|
|
@@ -157,7 +173,6 @@ export async function memoryCommand(args: string[], cwd: string, opts: { store?:
|
|
|
157
173
|
} finally { if (context.owned) store.close(); }
|
|
158
174
|
}
|
|
159
175
|
if (rest[0] === "declined") {
|
|
160
|
-
if (!person) fail("memory declined requires person authority");
|
|
161
176
|
if (rest.length !== 1) fail("usage: ahub memory declined [--json]");
|
|
162
177
|
const project = projectOf(cwd, opts.store);
|
|
163
178
|
const context = commandStores(opts.store, { project, deferPromotions: true, now: opts.now }, cwd);
|
|
@@ -175,7 +190,7 @@ export async function memoryCommand(args: string[], cwd: string, opts: { store?:
|
|
|
175
190
|
const profile = context.binding.status(context.store);
|
|
176
191
|
if (hostSyncPolicyInputs(cwd, context.binding.home, project, profile).version !== boundPolicy.version)
|
|
177
192
|
fail("memory declined policy changed during inspection; retry with stable privacy policy");
|
|
178
|
-
if (args.includes("--json")) return JSON.stringify({ rows: result.rows, complete: result.complete, ...(result.reason ? { reason: result.reason } : {}), memoryProfile: profile });
|
|
193
|
+
if (args.includes("--json")) return JSON.stringify({ rows: result.rows, complete: result.complete, ...(result.reason ? { reason: result.reason } : {}), memoryProfile: shownReceipt(profile, person) });
|
|
179
194
|
const text = result.complete
|
|
180
195
|
? result.rows.length
|
|
181
196
|
? [`${result.rows.length} declined physical outbound row${result.rows.length === 1 ? "" : "s"}:`, ...result.rows.map(row => `mem:${row.id} ${row.rule}`), "Review the source or approved policy, then run `ahub memory sync`. `forget` does not remove append-only physical rows."].join("\n")
|
|
@@ -9,6 +9,7 @@ import { choiceInstruction, renderBlocked, renderOperation, renderPlan, type Rec
|
|
|
9
9
|
import { paint, terminalText, wrap, type Span, type Tone } from "./console-state.ts";
|
|
10
10
|
import { renderExecutionBudgetStatus } from "./output.ts";
|
|
11
11
|
import type { NextChoice, RecoveryOperation, UpgradePlan } from "./upgrade.ts";
|
|
12
|
+
import type { StoppedPlan, StoppedResult, StoppedRow } from "./upgrade-stopped.ts";
|
|
12
13
|
|
|
13
14
|
const columnsOf = (options: RecoveryPresentationOptions) => Number.isFinite(options.columns) ? Math.max(2, Math.floor(options.columns)) : 80;
|
|
14
15
|
const text = (value: string, tone: Tone, options: RecoveryPresentationOptions): string[] =>
|
|
@@ -18,19 +19,59 @@ const text = (value: string, tone: Tone, options: RecoveryPresentationOptions):
|
|
|
18
19
|
* The plan `restart` or `upgrade` would apply, for a person reading a pipe or a `--dry-run`: the same rows the plan
|
|
19
20
|
* screen shows (a peer per line with how it runs and what happens to it), every blocker, and what the plan will not do.
|
|
20
21
|
* Blockers, reconnect-only sessions and fresh starts are part of the rows, so none of them is stderr-only any more.
|
|
22
|
+
* `applying` (#1540 AC9): under `--yes` the plan is the first part of an apply, so the closing line that says nothing was changed and offers `--yes` is left out.
|
|
21
23
|
*/
|
|
22
|
-
export function renderUpgradePlan(plan: UpgradePlan, current: string, options: RecoveryPresentationOptions): string[] {
|
|
24
|
+
export function renderUpgradePlan(plan: UpgradePlan, current: string, options: RecoveryPresentationOptions, applying = false): string[] {
|
|
23
25
|
const out = renderPlan(plan, current, options, planLines(plan, current));
|
|
24
26
|
const blocked = plan.blockers.length > 0 || plan.projects.some(project => project.blockers.length > 0);
|
|
25
27
|
if (!plan.projects.length) out.push(...text(plan.kind === "upgrade"
|
|
26
28
|
? `No hub is running, so nothing is carried over: ${globalCliUpdateStep(plan.version)}, then \`ahub setup\`.`
|
|
27
29
|
: "This project's hub is not running: `ahub up` starts it.", "muted", options));
|
|
28
|
-
out.push(...text(blocked
|
|
30
|
+
if (blocked || !applying) out.push(...text(blocked
|
|
29
31
|
? "Blocked: take the next action each blocker names, then run this again. Nothing was changed."
|
|
30
32
|
: "Nothing was changed. Apply with `--yes`.", blocked ? "failure" : "muted", options));
|
|
31
33
|
return out;
|
|
32
34
|
}
|
|
33
35
|
|
|
36
|
+
const stoppedRowText = (plan: StoppedPlan, row: StoppedRow): { text: string; tone: Tone; next?: string } => {
|
|
37
|
+
const single = plan.scope === "project";
|
|
38
|
+
switch (row.outcome) {
|
|
39
|
+
case "retarget": return { text: `${single ? "stopped" : "retarget"}: runtime selection only (${row.from ? `${row.from} to ` : ""}${plan.version})`, tone: "info" };
|
|
40
|
+
case "current": return { text: `already at ${row.from ?? plan.version}`, tone: "muted" };
|
|
41
|
+
case "running": return { text: `skipped: running; its own plan is \`${row.command}\``, tone: "attention" };
|
|
42
|
+
case "refused": return { text: `refused: ${row.cause}`, tone: "failure", ...(row.next ? { next: row.next } : {}) };
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* #1540: the plan of `ahub upgrade` for stopped projects (one, or `--all-stopped`): a row per project with its outcome, never a peer. It changes nothing and says what applying does:
|
|
48
|
+
* a runtime selection is written, and no hub, terminal or recovery operation is started.
|
|
49
|
+
*/
|
|
50
|
+
export function renderStoppedPlan(plan: StoppedPlan, current: string, options: RecoveryPresentationOptions, applying = false): string[] {
|
|
51
|
+
const out = [...text(`upgrade to ${plan.version}: runtime selection of ${plan.scope === "all-stopped" ? "stopped projects" : "a stopped project"}`, "strong", options), ...text(`Coordinator version ${current}`, "muted", options)];
|
|
52
|
+
if (!plan.rows.length) out.push(...text(plan.scope === "all-stopped" ? "No project is registered." : "This project is not registered.", "muted", options));
|
|
53
|
+
for (const row of plan.rows) {
|
|
54
|
+
const view = stoppedRowText(plan, row);
|
|
55
|
+
out.push(...text(`${row.project.id} ${row.project.root}`, "info", options), ...text(` ${view.text}`, view.tone, options));
|
|
56
|
+
if (view.next) out.push(...text(` next: ${view.next}`, "attention", options));
|
|
57
|
+
}
|
|
58
|
+
const retargets = plan.rows.filter(row => row.outcome === "retarget").length;
|
|
59
|
+
if (retargets) out.push(...text(`Applying writes ${retargets === 1 ? "one runtime selection" : `${retargets} runtime selections`}: no hub is started, no terminal or peer is touched and no recovery operation is recorded.`, "muted", options));
|
|
60
|
+
else if (plan.scope === "all-stopped") out.push(...text("Nothing to retarget.", "muted", options));
|
|
61
|
+
const blocked = plan.blockers.length > 0;
|
|
62
|
+
if (blocked || !applying) out.push(...text(blocked ? "Blocked: take the next action it names, then run this again. Nothing was changed." : retargets ? "Nothing was changed. Apply with `--yes`." : "Nothing was changed.", blocked ? "failure" : "muted", options));
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** #1540: one line per project of an applied stopped retarget, with the cause of each failure. */
|
|
67
|
+
export function renderStoppedResults(results: readonly StoppedResult[], options: RecoveryPresentationOptions): string[] {
|
|
68
|
+
const out: string[] = [];
|
|
69
|
+
for (const result of results) out.push(...text(result.outcome === "retargeted"
|
|
70
|
+
? `${result.id}: runtime selection set to ${result.to}${result.from ? ` (was ${result.from})` : ""}; it stays stopped`
|
|
71
|
+
: `${result.id}: not retargeted (${result.cause})`, result.outcome === "retargeted" ? "success" : "failure", options));
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
34
75
|
/**
|
|
35
76
|
* `ahub recovery status [<id>]`: the receipt's step and projects, then what the person can do about it. A blocked
|
|
36
77
|
* operation also says what happened, why and what to do, exactly as the coordinator's screen does; the wait and
|