@staix/agent-hub 0.35.0 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +21 -4
- package/docs/agent-notes/README.md +60 -0
- package/docs/agent-notes/adapters.md +5 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +5 -4
- package/docs/agent-notes/models.md +4 -3
- package/docs/agent-notes/tasks.md +8 -1
- package/docs/agent-notes/tests.md +1 -0
- package/docs/design/adapters.md +72 -0
- package/docs/design/agent-hub-architecture.md +1 -1
- package/docs/design/bus.md +8 -0
- package/docs/design/execution-reference.md +171 -11
- package/docs/design/guidance-experiments.md +438 -0
- package/docs/design/model-routes.md +628 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +111 -0
- package/docs/dogfood.md +15 -4
- package/docs/operations.md +291 -22
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +106 -1
- package/docs/research.md +4 -2
- package/docs/sdlc.md +108 -4
- package/docs/security.md +67 -5
- package/docs/specs/2026-09-19-agent-hub-design.md +5 -4
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
- package/docs/verification/2026-11-10-0.36.0.md +59 -0
- package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
- package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
- package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
- package/docs/verification/claude-shell-wrapper-native.py +1 -1
- package/docs/verified.json +27 -27
- package/package.json +1 -1
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +1201 -368
- package/plugins/agent-hub/server.js +1682 -431
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/compat.ts +10 -10
- package/src/adapters/local-worker.ts +1 -1
- package/src/adapters/qwen-dual.ts +324 -44
- package/src/cli/guidance.ts +67 -0
- package/src/cli/help.ts +10 -3
- package/src/cli/identity.ts +10 -3
- package/src/cli/init-prompt.ts +15 -2
- package/src/cli/init-required-checks.ts +122 -0
- package/src/cli/init-settings.ts +10 -4
- package/src/cli/init.ts +39 -3
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +111 -10
- package/src/cli/setup-research.ts +10 -0
- package/src/hub/autonomy-defaults.ts +20 -9
- package/src/hub/board.ts +346 -4
- package/src/hub/build-entry.ts +11 -0
- package/src/hub/bus.ts +12 -0
- package/src/hub/ci-watch.ts +4 -4
- package/src/hub/config-apply.ts +2 -1
- package/src/hub/config-trust.ts +1 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +342 -20
- package/src/hub/delivery-hints.ts +4 -2
- package/src/hub/delivery-journal.ts +50 -2
- package/src/hub/delivery-public.ts +51 -0
- package/src/hub/dogfood-profile.ts +8 -4
- package/src/hub/execution-lineage-owner.ts +272 -0
- package/src/hub/execution-lineage.ts +52 -8
- package/src/hub/execution-links.ts +85 -0
- package/src/hub/guidance-variants.ts +398 -0
- package/src/hub/handoff.ts +1 -0
- package/src/hub/hub-tools.ts +43 -2
- package/src/hub/manager.ts +44 -2
- package/src/hub/memory-policy.ts +2 -2
- package/src/hub/peers.ts +1 -1
- package/src/hub/planning.ts +1 -1
- package/src/hub/progress.ts +24 -7
- package/src/hub/restart.ts +13 -0
- package/src/hub/roles.ts +26 -0
- package/src/hub/routing.ts +4 -1
- package/src/hub/sdlc-merge.ts +39 -1
- package/src/hub/sdlc-release.ts +1 -1
- package/src/hub/sdlc.ts +62 -11
- package/src/hub/settings.ts +2 -0
- package/src/hub/supervision-proposals.ts +405 -0
- package/src/hub/supervision-rules.ts +388 -0
- package/src/hub/supervision.ts +2 -0
- package/src/hub/task-approval.ts +2 -2
- package/src/hub/task-repository.ts +5 -0
- package/src/hub/tasks.ts +603 -50
- package/src/memory/capture.ts +2 -2
- package/src/models/relay.ts +9 -2
- package/src/models/route/config.ts +27 -0
- package/src/models/route/decision.ts +87 -15
- package/src/models/route/relay-selector.ts +8 -7
- package/src/models/route/runtime.ts +22 -16
- package/src/models/route/stage-diagnostics.ts +22 -0
- package/src/models/route/stage-evidence.ts +55 -0
- package/src/models/route/stage-fallback.ts +58 -0
- package/src/models/route/stage-input.ts +155 -0
- package/src/models/route/stage.ts +5 -147
- package/src/ui/guidance-panel.ts +156 -0
- package/src/ui/guidance-view.ts +43 -0
- package/src/ui/lineage-view.ts +34 -0
- package/src/ui/plugin.ts +71 -7
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { executionText } from "../hub/execution-reference.ts";
|
|
2
|
+
import { GUIDANCE_HASH_HEX_LENGTH, GUIDANCE_CURSOR_MAX_BYTES, parseGuidanceWriteReceipt, type GuidanceDiffResult, type GuidancePageResult, type GuidanceWriteReceipt } from "../hub/guidance-variants.ts";
|
|
3
|
+
import { guidanceLines, guidanceReceiptLines } from "../ui/guidance-view.ts";
|
|
4
|
+
import { terminalText } from "./console-state.ts";
|
|
5
|
+
|
|
6
|
+
export const GUIDANCE_USAGE = "usage: ahub guidance create --file FILE [--json] | list --task N --task-created MS [--cursor TOKEN] [--json] | show --task N --task-created MS --id HASH [--json] | withdraw --task N --task-created MS --revision R --id HASH [--json]";
|
|
7
|
+
type Create = { op: "create"; json: boolean; file: string };
|
|
8
|
+
type List = { op: "list"; json: boolean; taskId: number; taskCreated: number; cursor?: string };
|
|
9
|
+
type Show = { op: "show"; json: boolean; taskId: number; taskCreated: number; id: string };
|
|
10
|
+
type Withdraw = { op: "withdraw"; json: boolean; taskId: number; taskCreated: number; flowRevision: number; id: string };
|
|
11
|
+
export type GuidanceCommand = Create | List | Show | Withdraw;
|
|
12
|
+
const invalid = (): never => { throw new Error(`invalid guidance arguments; ${GUIDANCE_USAGE}`); };
|
|
13
|
+
const integer = (raw: string | undefined, minimum: number): number => {
|
|
14
|
+
if (raw === undefined || !/^(0|[1-9][0-9]*)$/.test(raw)) return invalid();
|
|
15
|
+
const value = Number(raw);
|
|
16
|
+
return Number.isSafeInteger(value) && value >= minimum ? value : invalid();
|
|
17
|
+
};
|
|
18
|
+
const contentId = (raw: string | undefined): string =>
|
|
19
|
+
typeof raw === "string" && raw.length === GUIDANCE_HASH_HEX_LENGTH && /^[a-f0-9]+$/.test(raw) ? raw : invalid();
|
|
20
|
+
/** The explicit filename remains a selector; main owns its bounded read and the complete V1 parse. */
|
|
21
|
+
export function parseGuidanceCommand(args: readonly string[]): GuidanceCommand {
|
|
22
|
+
const [op, ...rest] = args;
|
|
23
|
+
if (op !== "create" && op !== "list" && op !== "show" && op !== "withdraw") return invalid();
|
|
24
|
+
const allowed = op === "create" ? ["--file"] : op === "list" ? ["--task", "--task-created", "--cursor"]
|
|
25
|
+
: op === "show" ? ["--task", "--task-created", "--id"] : ["--task", "--task-created", "--revision", "--id"];
|
|
26
|
+
const values = new Map<string, string>(); let json = false;
|
|
27
|
+
for (let index = 0; index < rest.length; index++) {
|
|
28
|
+
const flag = rest[index]!;
|
|
29
|
+
if (flag === "--json") { if (json) return invalid(); json = true; continue; }
|
|
30
|
+
if (!allowed.includes(flag) || values.has(flag)) return invalid();
|
|
31
|
+
const value = rest[++index];
|
|
32
|
+
if (typeof value !== "string" || value.length === 0 || value.startsWith("--") || /[\p{Cc}\p{Cf}\p{Cs}]/u.test(value)) return invalid();
|
|
33
|
+
values.set(flag, value);
|
|
34
|
+
}
|
|
35
|
+
if (op === "create") {
|
|
36
|
+
const file = values.get("--file");
|
|
37
|
+
if (!file) return invalid();
|
|
38
|
+
return { op, json, file };
|
|
39
|
+
}
|
|
40
|
+
const taskId = integer(values.get("--task"), 1), taskCreated = integer(values.get("--task-created"), 0);
|
|
41
|
+
if (op === "list") {
|
|
42
|
+
if (!values.has("--cursor")) return { op, json, taskId, taskCreated };
|
|
43
|
+
const cursor = values.get("--cursor")!;
|
|
44
|
+
// V1 wire bound: authentication and task/actor binding belong to the source host.
|
|
45
|
+
if (!executionText(cursor, GUIDANCE_CURSOR_MAX_BYTES) || !/^[A-Za-z0-9_-]+$/.test(cursor)) return invalid();
|
|
46
|
+
return { op, json, taskId, taskCreated, cursor };
|
|
47
|
+
}
|
|
48
|
+
const id = contentId(values.get("--id"));
|
|
49
|
+
return op === "show" ? { op, json, taskId, taskCreated, id }
|
|
50
|
+
: { op, json, taskId, taskCreated, flowRevision: integer(values.get("--revision"), 0), id };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export { parseGuidancePageResult as validateGuidancePageReply, parseGuidanceDiffResult as validateGuidanceDiffReply } from "../hub/guidance-variants.ts";
|
|
54
|
+
/** An unconfirmed write never authorizes an automatic retry or reinterprets a displayed experiment label as a selector. */
|
|
55
|
+
export function validateGuidanceReceipt(value: unknown, expected: { id?: string; taskId?: number; status?: "withdrawn" }): GuidanceWriteReceipt {
|
|
56
|
+
const unconfirmed = (): never => { throw new Error("guidance write reply is unconfirmed; inspect ahub guidance list for the task before retrying the write"); };
|
|
57
|
+
try {
|
|
58
|
+
const receipt = parseGuidanceWriteReceipt(value);
|
|
59
|
+
if (expected.id !== undefined && receipt.id !== expected.id || expected.taskId !== undefined && receipt.taskId !== expected.taskId
|
|
60
|
+
|| expected.status !== undefined && receipt.status !== expected.status) return unconfirmed();
|
|
61
|
+
return receipt;
|
|
62
|
+
} catch { return unconfirmed(); }
|
|
63
|
+
}
|
|
64
|
+
/** The shared view contains public data only; terminal controls are stripped at this surface. */
|
|
65
|
+
const terminalLines = (lines: readonly string[]): string[] => lines.map(line => terminalText(line).replace(/[\r\n]+/g, " "));
|
|
66
|
+
export const renderGuidance = (result: GuidancePageResult | GuidanceDiffResult): string[] => terminalLines(guidanceLines(result));
|
|
67
|
+
export const renderGuidanceReceipt = (receipt: GuidanceWriteReceipt): string[] => terminalLines(guidanceReceiptLines(receipt));
|
package/src/cli/help.ts
CHANGED
|
@@ -12,8 +12,8 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
12
12
|
["ahub --project <path|id> <command>", "select a repository or worktree explicitly"],
|
|
13
13
|
["ahub projects [--json] [--full] [--color=auto|always|never]", "list registered projects and live status"],
|
|
14
14
|
["ahub projects remove <id>", "forget a stopped registration (keeps project files)"],
|
|
15
|
-
["ahub setup [--yes] [--agents <a,b>]", "install or update the channel plugin and project-neutral hook in Claude configuration homes in use, preserving unrelated profile settings, ask once which agents ahub up starts (--agents answers it, --yes keeps the current choice or claude,codex, no terminal keeps the default), register the acon console plugin (console/plugins/ahub.json in the hub home, read at acon's next start), then run doctor"],
|
|
16
|
-
["ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--coordination advisory|turn-free] [--memory|--no-memory] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]", "preview or write .agenthub/config.json and the AGENTS.md marker block (drops a legacy CLAUDE.md block); a pack is a shipped one (writing-pack, analysis, ops) or a project file .agenthub/roles/<name>.pack.json; a new project inherits a trusted machine autonomy default and the agent set chosen at ahub setup (start.agents) into config.local.json. Settings flags (#1065): --agents sets start.agents (none starts no agent) and --autonomy off skips the autonomy inheritance,
|
|
15
|
+
["ahub setup [--yes] [--agents <a,b>] [--research|--no-research]", "install or update the channel plugin and project-neutral hook in Claude configuration homes in use, preserving unrelated profile settings, ask once which agents ahub up starts (--agents answers it, --yes keeps the current choice or claude,codex, no terminal keeps the default), save the research default only with explicit --research/--no-research (ordinary setup leaves it unchanged), register the acon console plugin (console/plugins/ahub.json in the hub home, read at acon's next start), then run doctor"],
|
|
16
|
+
["ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--required-checks <a,b,...>] [--coordination advisory|turn-free] [--memory|--no-memory] [--research|--no-research] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]", "preview or write .agenthub/config.json and the AGENTS.md marker block (drops a legacy CLAUDE.md block); a pack is a shipped one (writing-pack, analysis, ops) or a project file .agenthub/roles/<name>.pack.json; a new project inherits a trusted machine autonomy default and the agent set chosen at ahub setup (start.agents) into config.local.json. Settings flags (#1065): --agents sets start.agents (none starts no agent), --research/--no-research sets research.enabled (new project default: the trusted setup choice, else off) and --autonomy off skips the autonomy inheritance, all in config.local.json; --sdlc sets sdlc.toml mode (off writes no file on a new project); advise/enforce discovers required checks from CI or literal workflow job names; --required-checks overrides discovery, and enforce without names refuses before writes; --coordination, --memory, --snapshots and --pi set their keys in config.json. On an existing project only a flag you give changes anything, and --dry-run shows each change as old -> new (--dry-run --json adds a settings array); a value equal to the current one is a no-op, an invalid value is refused with the allowed ones and nothing is written. --specs/--no-specs and --spec-review set the design-specs keys (and the AGENTS.md specs block). A person at a terminal who runs ahub init on a new project with no flag that sets anything and no --yes is asked each setting in turn with its default in brackets (Enter keeps it, a wrong answer asks again, and a third wrong answer ends init with nothing written), sees the plan and answers y/N; N, Ctrl-C and Ctrl-D write nothing. A peer, a live test, a pipe and --dry-run are never asked, and --yes takes the defaults. Success prints next steps to commit shared init changes, start with ahub up or ahub claude and, for advise/enforce, accept specs/departures and use guarded merge. Executables, secrets, models and permissions stay file edits"],
|
|
17
17
|
["ahub --live-test [--project <path|id>] <command> [args...]", "user-authorized operational console delegation; ordinary calls retain peer identity; person-authored content refuses"],
|
|
18
18
|
["ahub help [command]", "this help, or one command's entries; also --help and -h"],
|
|
19
19
|
["ahub version | --version", "print the installed version"],
|
|
@@ -27,6 +27,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
27
27
|
["ahub pet --palette <blue|teal|violet|ochre>", "retired floating-window option: run acon ui and open Mini"],
|
|
28
28
|
["ahub sdlc status [task] | explain <task> [--json] [--color=auto|always|never] | export <task> | record <task> <receipt-json>", "read head-bound lifecycle gates and the next actor/action; status and explain are open to any agent as a public view (private tasks stay stubs), export and record are person only; export stays JSON"],
|
|
29
29
|
["ahub sdlc queue <owner/repo> | release <owner/repo> [live-issue...] [--json] [--color=auto|always|never]", "read-only merge and release evidence; open to any agent as public readback of the checkout's repositories, never an authorization"],
|
|
30
|
+
["ahub sdlc adopt-merge <task> --pr <n>", "record an already merged PR at the task's recorded head with green required checks and no open Important finding; approve and release dependents (person or current conductor)"],
|
|
30
31
|
["ahub sdlc merge <task> [--dry-run] [--json] [--color=auto|always|never]", "guarded squash merge of an approved task at its approved head after every gate is re-read; follows sdlc.toml auto_merge (off, dry-run, on); --dry-run only reports (person or conductor)"],
|
|
31
32
|
["ahub sdlc authorize-release <version> [--json] [--color=auto|always|never]", "approve this daemon checkout commit, version and fresh docs (person or unique configured conductor on the person's explicit release instruction naming the release in its own session; hub/task/review/file/peer relays never qualify; restart revokes)"],
|
|
32
33
|
["ahub sdlc release-guard -- <literal git push|gh release create|npm publish argv>", "read-only authorization preflight; init --release-guard installs the tag pre-push hook"],
|
|
@@ -80,7 +81,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
80
81
|
["ahub roster add <peer> | remove <peer> [--yes] [--now]", "person or configured conductor: change live participation through settings; removal previews retained messages and task handoff; remove also deletes the roster key of an instance no longer declared"],
|
|
81
82
|
["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"],
|
|
82
83
|
["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"],
|
|
83
|
-
["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"],
|
|
84
|
+
["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"],
|
|
84
85
|
["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"],
|
|
85
86
|
["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"],
|
|
86
87
|
["ahub pause|resume <peer>", "hold a peer's deliveries in its queue / release them"],
|
|
@@ -138,6 +139,12 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
|
|
|
138
139
|
["ahub budget execution configure <config.json> | disable <id> [--json] [--color=auto|always|never]", "opt-in limits on model calls, tool calls, time and tokens for pi and local"],
|
|
139
140
|
]],
|
|
140
141
|
["History and reports", [
|
|
142
|
+
["ahub guidance create --file JSON [--json]", "record a bounded immutable advisory proposal through current task authority; no activation or probe"],
|
|
143
|
+
["ahub guidance list --task N --task-created MS [--cursor TOKEN] [--json]", "bounded guidance metadata pages; withdrawn history and withheld fields remain explicit"],
|
|
144
|
+
["ahub guidance show --task N --task-created MS --id HASH [--json]", "screened editable-section diff selected by existing variant id, never a displayed experiment label"],
|
|
145
|
+
["ahub guidance withdraw --task N --task-created MS --revision R --id HASH [--json]", "one-way withdrawal using current task flow; retained history never becomes active guidance"],
|
|
146
|
+
["ahub lineage show (--task N | --attempt ra-id | --root JSON [--task-scope N --task-created MS]) [--cursor TOKEN] [--nodes N --edges N --bytes N] [--json]", "bounded execution metadata and explicit evidence strengths; unavailable stays unknown, with no probes or replay"],
|
|
147
|
+
["ahub lineage link --task N --task-created MS --revision N --ref JSON [--from JSON] [--json]", "register a declared metadata link through the task's current authority and revision; no producer attestation"],
|
|
141
148
|
["ahub turns [peer] [--limit N] [--json] [--color=auto|always|never]", "recent turns and the files each changed (a git work tree only)"],
|
|
142
149
|
["ahub undo <turn> [--yes] [--context]", "put back the files a turn changed; refuses files changed since. Without --yes it only lists them; --context also drops a Codex turn from its conversation"],
|
|
143
150
|
["ahub report [--since 7d|<iso>] [--by task] [--json] [--color=auto|always|never]", "turns, tokens, messages, overlaps and task events per period"],
|
package/src/cli/identity.ts
CHANGED
|
@@ -15,6 +15,8 @@ export const LIVE_TEST_PERSON_REFUSAL = "live-test cannot write person-attribute
|
|
|
15
15
|
|
|
16
16
|
/** Person verdicts and user-authored workflow content are never delegated. */
|
|
17
17
|
export function liveTestRefusal(command: string, args: readonly string[], context: { repairedFresh?: boolean } = {}): boolean {
|
|
18
|
+
if (command === "lineage" && args[0] === "link") return true;
|
|
19
|
+
if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
|
|
18
20
|
if (command === "model") return true; // #1317: even listing runtime overrides is person-only, never live-test delegated.
|
|
19
21
|
if (command === "sdlc" && (args[0] === "authorize-release" || args[0] === "plan-review" || args[0] === "release-assign" || args[0] === "merge" || args[0] === "train" && args[1] !== "report")) return true;
|
|
20
22
|
if (args.some(arg => arg === "--as-user" || arg.startsWith("--as-user="))) return true;
|
|
@@ -27,7 +29,7 @@ export function liveTestRefusal(command: string, args: readonly string[], contex
|
|
|
27
29
|
// #601: a campaign's draft, revise, approve and close are the person's verdicts; only `show` is a read. Without this an agent shell could run them as the person through `--live-test`.
|
|
28
30
|
|| (command === "study" && sub !== "show" && sub !== "experiments")
|
|
29
31
|
|| (command === "recovery" && (sub === "reattach" || sub === "dispose" && context.repairedFresh === true))
|
|
30
|
-
|| (command === "board" && args[0] === "import") || (command === "sdlc" && (args[0] === "record" || args[0] === "accept" || args[0] === "accept-departure"))
|
|
32
|
+
|| (command === "board" && args[0] === "import") || (command === "sdlc" && (args[0] === "record" || args[0] === "accept" || args[0] === "accept-departure" || args[0] === "adopt-merge"))
|
|
31
33
|
|| (command === "bench" && args.find(arg => arg !== "--json") === "run") || command === "pet"
|
|
32
34
|
// #691: trusting an untested agent CLI version is the person's consent, never a delegated live-test operation.
|
|
33
35
|
|| command === "autonomy" || command === "title"
|
|
@@ -154,9 +156,12 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
|
|
|
154
156
|
if (conductorOperation(command,args)) return "conductor";
|
|
155
157
|
if (command === "stop") return "console";
|
|
156
158
|
if (command === "sdlc" && ["release-guard", "release-guard-hook"].includes(args[0] ?? "")) return "allowed";
|
|
157
|
-
// #786, #1063: guarded merge and
|
|
158
|
-
if (command === "sdlc" && ["merge", "authorize-release"].includes(args[0] ?? "")) return "conductor";
|
|
159
|
+
// #786, #1063, #1328: guarded merge, merge adoption and explicitly instructed release consent admit the person or unique configured conductor; the daemon checks the role.
|
|
160
|
+
if (command === "sdlc" && ["merge", "authorize-release", "adopt-merge"].includes(args[0] ?? "")) return "conductor";
|
|
159
161
|
if (command === "role") return ["list", "show"].includes(args[0] ?? "") ? "allowed" : "console";
|
|
162
|
+
// The original tools identity reaches Tasks for read visibility or task-scoped link admission.
|
|
163
|
+
if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? "allowed" : "console";
|
|
164
|
+
if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? "allowed" : "console";
|
|
160
165
|
if (command === "task") {
|
|
161
166
|
// #933: cancel, label and role act on the caller's own task only; the daemon refuses another peer's task by role (Tasks.cancel, task_catalog_role, task_label_check).
|
|
162
167
|
if (["propose", "show", "cancel", "label", "role"].includes(args[0] ?? "")) return "allowed";
|
|
@@ -196,6 +201,8 @@ export function classifyPeerCommand(command: string, args: readonly string[], ca
|
|
|
196
201
|
|
|
197
202
|
/** No argument text is included: notices and refusal logs must not copy task text or credentials. */
|
|
198
203
|
export function cliCommandLabel(command: string, args: readonly string[], catalog?: ProjectAdapterCatalog): string {
|
|
204
|
+
if (command === "lineage") return ["show", "link"].includes(args[0] ?? "") ? `lineage ${args[0]}` : "lineage";
|
|
205
|
+
if (command === "guidance") return ["create", "list", "show", "withdraw"].includes(args[0] ?? "") ? `guidance ${args[0]}` : "guidance";
|
|
199
206
|
if (command === "model") return ["list", "set", "clear"].includes(args[0] ?? "") ? `model ${args[0]}` : "model";
|
|
200
207
|
if (command === "peer") return args[0] === "takeover" ? "peer takeover" : "peer";
|
|
201
208
|
if (command === "backlog") return ["list", "add", "pull", "pull-ready", "split", "return", "plan", "pin", "undo"].includes(args[0] ?? "") ? `backlog ${args[0]}` : "backlog";
|
package/src/cli/init-prompt.ts
CHANGED
|
@@ -64,6 +64,7 @@ export function shownDefault(id: string): string {
|
|
|
64
64
|
: id === "coordination" ? DEFAULT_CONFIG.coordination
|
|
65
65
|
: id === "specs.enabled" ? DEFAULT_SPECS_CONFIG.enabled
|
|
66
66
|
: id === "specs.review" ? DEFAULT_SPECS_CONFIG.review
|
|
67
|
+
: id === "sdlc.required_checks" ? "none"
|
|
67
68
|
: id === "sdlc.mode" ? "off" // no file is written for it: the loader's own default (src/hub/sdlc.ts)
|
|
68
69
|
: row.id.endsWith(".enabled") ? false // a legacy `<kind>.enabled` switch that the template does not carry reads as off
|
|
69
70
|
: undefined;
|
|
@@ -84,8 +85,11 @@ const oneOf = (id: string, label: string, values: readonly string[], shown: stri
|
|
|
84
85
|
export interface InitQuestionContext {
|
|
85
86
|
/** The agent set `ahub setup` chose on this machine (the default shown for the agents question), or `undefined` for the shipped default. */
|
|
86
87
|
machineAgents?: readonly string[];
|
|
88
|
+
/** Effective research default for this new project, read from the trusted setup choice (else off). */
|
|
89
|
+
machineResearch?: boolean;
|
|
87
90
|
/** Project packs a profile answer may name besides the shipped profiles. */
|
|
88
91
|
packs?: readonly string[];
|
|
92
|
+
discoverChecks?: () => Promise<readonly string[]>;
|
|
89
93
|
/** Shadow history is offered only for a folder with no Git work tree. */
|
|
90
94
|
shadowAvailable?: boolean;
|
|
91
95
|
}
|
|
@@ -105,15 +109,17 @@ export function initQuestions(context: InitQuestionContext = {}): InitQuestion[]
|
|
|
105
109
|
id: "start.agents", label: "Agents ahub up starts", choices: `${START_AGENTS_ALLOWED.join(",")} as a comma list, or none`, shown: (context.machineAgents ?? START_AGENTS_DEFAULT).join(", ") || "none",
|
|
106
110
|
read: text => INIT_SETTINGS.find(row => row.id === "start.agents")!.parse(text.trim().toLowerCase()),
|
|
107
111
|
};
|
|
108
|
-
const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "snapshots.enabled"].includes(row.id));
|
|
112
|
+
const switches = INIT_SETTINGS.filter(row => row.id.endsWith(".enabled") && !["specs.enabled", "memory.enabled", "research.enabled", "snapshots.enabled"].includes(row.id));
|
|
109
113
|
const all: InitQuestion[] = [
|
|
110
114
|
profile,
|
|
111
115
|
agents,
|
|
112
116
|
onOff("specs.enabled", "Design specs and their freshness checks", shownDefault("specs.enabled") as "on" | "off"),
|
|
113
117
|
oneOf("specs.review", "Spec review mode", SPEC_REVIEW_MODES, shownDefault("specs.review")),
|
|
114
118
|
oneOf("sdlc.mode", "SDLC mode", SDLC_MODES, shownDefault("sdlc.mode")),
|
|
119
|
+
{ id: "sdlc.required_checks", label: "Required CI checks", choices: "comma-separated names", shown: "none", read: text => INIT_SETTINGS.find(row => row.id === "sdlc.required_checks")!.parse(text) },
|
|
115
120
|
oneOf("coordination", "Coordination", COORDINATION_MODES, shownDefault("coordination")),
|
|
116
121
|
onOff("memory.enabled", "Shared memory", shownDefault("memory.enabled") as "on" | "off"),
|
|
122
|
+
onOff("research.enabled", "Research records", context.machineResearch === true ? "on" : "off"),
|
|
117
123
|
onOff("snapshots.enabled", "Per-turn snapshots", shownDefault("snapshots.enabled") as "on" | "off"),
|
|
118
124
|
...switches.map(row => onOff(row.id, row.describe.charAt(0).toUpperCase() + row.describe.slice(1), shownDefault(row.id) as "on" | "off")),
|
|
119
125
|
oneOf("autonomy", "Machine autonomy preset", AUTONOMY_CHOICES, "inherit"),
|
|
@@ -133,7 +139,14 @@ export const questionLine = (question: InitQuestion): string => `${question.labe
|
|
|
133
139
|
export async function runInitPrompt(ports: InitPromptPorts, context: InitQuestionContext, preview: (answers: InitAnswers) => string[]): Promise<InitPromptResult> {
|
|
134
140
|
const answers: InitAnswers = { request: { values: {} }, shadow: false, releaseGuard: false };
|
|
135
141
|
ports.print("ahub init: press Enter to keep the default in brackets. N at the end, Ctrl-C or Ctrl-D writes nothing.");
|
|
136
|
-
for (const
|
|
142
|
+
for (const original of initQuestions(context)) {
|
|
143
|
+
let question = original;
|
|
144
|
+
if (question.id === "sdlc.required_checks") {
|
|
145
|
+
if (!["advise", "enforce"].includes(String(answers.request.values["sdlc.mode"]))) continue;
|
|
146
|
+
const names = await context.discoverChecks?.() ?? [];
|
|
147
|
+
answers.request.values["sdlc.required_checks"] = [...names];
|
|
148
|
+
question = { ...question, shown: names.join(", ") || "none; supply check names" };
|
|
149
|
+
}
|
|
137
150
|
let settled = false;
|
|
138
151
|
for (let attempt = 0; attempt < MAX_TRIES && !settled; attempt++) {
|
|
139
152
|
const answer = await ports.ask(questionLine(question));
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { constants, openSync, fstatSync, readSync, closeSync, readdirSync, lstatSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { githubOriginRepository } from "../hub/task-repository.ts";
|
|
4
|
+
import { requiredChecksFor } from "../hub/sdlc-merge.ts";
|
|
5
|
+
import { hubGitSync } from "../hub/git.ts";
|
|
6
|
+
import { loadSdlc, sdlcGh, type SdlcGh } from "../hub/sdlc.ts";
|
|
7
|
+
import type { InitSettingsRequest } from "./init-settings.ts";
|
|
8
|
+
|
|
9
|
+
const DISCOVERY_DEADLINE_MS = 20_000;
|
|
10
|
+
const DISCOVERY_READ_MS = 5_000;
|
|
11
|
+
const DISCOVERY_BYTES = 512 * 1024;
|
|
12
|
+
const DISCOVERY_JOBS = 100;
|
|
13
|
+
const WORKFLOW_FILES = 32;
|
|
14
|
+
const WORKFLOW_BYTES = 256 * 1024;
|
|
15
|
+
|
|
16
|
+
export interface InitCheckDiscovery { names: string[]; source: "CI" | "workflows" | "unknown"; reason?: string }
|
|
17
|
+
const validNames = (names: unknown[]): names is string[] => names.length > 0 && names.length <= 32 && names.every(name => typeof name === "string" && name.trim() === name && name.length > 0 && name.length <= 120 && !/[\p{Cc}]/u.test(name));
|
|
18
|
+
|
|
19
|
+
/** Literal block-style jobs only. ponytail: expressions, matrices and YAML aliases need an explicit override until a bounded YAML resolver is specified. */
|
|
20
|
+
export function workflowCheckNames(text: string): string[] | undefined {
|
|
21
|
+
const lines = text.split(/\r?\n/), start = lines.findIndex(line => /^jobs:\s*(?:#.*)?$/.test(line));
|
|
22
|
+
if (start < 0) return undefined;
|
|
23
|
+
const names: string[] = [];
|
|
24
|
+
let id: string | undefined, name: string | undefined, dynamic = false;
|
|
25
|
+
const finish = () => { if (id) names.push(name ?? id); };
|
|
26
|
+
for (const line of lines.slice(start + 1)) {
|
|
27
|
+
if (/^[^\s#]/.test(line)) break;
|
|
28
|
+
const job = /^ ([A-Za-z_][A-Za-z0-9_-]*):\s*(?:#.*)?$/.exec(line);
|
|
29
|
+
if (job) { finish(); id = job[1]!; name = undefined; continue; }
|
|
30
|
+
if (!line.trim() || /^\s*#/.test(line)) continue;
|
|
31
|
+
if (/^ \S/.test(line)) { dynamic = true; continue; }
|
|
32
|
+
if (!id) continue;
|
|
33
|
+
if (/^ (?:strategy|uses):/.test(line) || /^ <<:/.test(line)) dynamic = true;
|
|
34
|
+
const named = /^ name:\s*(.*?)\s*$/.exec(line);
|
|
35
|
+
if (named) {
|
|
36
|
+
const raw = named[1]!;
|
|
37
|
+
if (/\$\{|^[>|*&!{\[]/.test(raw)) { dynamic = true; continue; }
|
|
38
|
+
try {
|
|
39
|
+
if (raw.startsWith("'")) {
|
|
40
|
+
const quoted = /^'((?:[^']|'')*)'\s*(?:#.*)?$/.exec(raw);
|
|
41
|
+
if (!quoted) { dynamic = true; continue; }
|
|
42
|
+
name = quoted[1]!.replaceAll("''", "'");
|
|
43
|
+
} else if (raw.startsWith('"')) {
|
|
44
|
+
const quoted = /^("(?:[^"\\]|\\.)*")\s*(?:#.*)?$/.exec(raw);
|
|
45
|
+
if (!quoted) { dynamic = true; continue; }
|
|
46
|
+
name = JSON.parse(quoted[1]!);
|
|
47
|
+
} else name = raw.replace(/\s+#.*$/, "");
|
|
48
|
+
} catch { dynamic = true; }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
finish();
|
|
52
|
+
const unique = [...new Set(names)];
|
|
53
|
+
return !dynamic && validNames(unique) ? unique : undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function workflowChecks(cwd: string): InitCheckDiscovery {
|
|
57
|
+
const unknown: InitCheckDiscovery = { names: [], source: "unknown", reason: "CI unavailable or workflows have no complete literal job names; pass --required-checks <a,b,...>" };
|
|
58
|
+
const folder = join(cwd, ".github", "workflows");
|
|
59
|
+
try {
|
|
60
|
+
if (lstatSync(join(cwd, ".github")).isSymbolicLink() || lstatSync(folder).isSymbolicLink()) return unknown;
|
|
61
|
+
const files = readdirSync(folder).filter(file => file.endsWith(".yml")).sort();
|
|
62
|
+
if (!files.length || files.length > WORKFLOW_FILES) return unknown;
|
|
63
|
+
const names: string[] = [];
|
|
64
|
+
for (const file of files) {
|
|
65
|
+
const fd = openSync(join(folder, file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
66
|
+
try {
|
|
67
|
+
const stat = fstatSync(fd);
|
|
68
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.size > WORKFLOW_BYTES) return unknown;
|
|
69
|
+
const bytes = Buffer.alloc(WORKFLOW_BYTES + 1);
|
|
70
|
+
let length = 0, count = 0;
|
|
71
|
+
while ((count = readSync(fd, bytes, length, bytes.length - length, null)) > 0) { length += count; if (length > WORKFLOW_BYTES) return unknown; }
|
|
72
|
+
const after = fstatSync(fd);
|
|
73
|
+
if (stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || length !== after.size) return unknown;
|
|
74
|
+
const text = bytes.subarray(0, length).toString("utf8");
|
|
75
|
+
const found = workflowCheckNames(text);
|
|
76
|
+
if (!found) return unknown;
|
|
77
|
+
names.push(...found);
|
|
78
|
+
} finally { closeSync(fd); }
|
|
79
|
+
}
|
|
80
|
+
const unique = [...new Set(names)];
|
|
81
|
+
return validNames(unique) ? { names: unique, source: "workflows" } : unknown;
|
|
82
|
+
} catch { return unknown; }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** At most three capped reads under one deadline; any incomplete evidence falls back to bounded local workflow data. No shell or YAML execution. */
|
|
86
|
+
export async function discoverInitChecks(cwd: string, run: SdlcGh = sdlcGh): Promise<InitCheckDiscovery> {
|
|
87
|
+
const deadline = performance.now() + DISCOVERY_DEADLINE_MS;
|
|
88
|
+
try {
|
|
89
|
+
const repo = githubOriginRepository(cwd);
|
|
90
|
+
if (!repo) return workflowChecks(cwd);
|
|
91
|
+
const read = async (args: string[]) => {
|
|
92
|
+
const remaining = deadline - performance.now();
|
|
93
|
+
if (remaining <= 0) throw new Error("discovery deadline");
|
|
94
|
+
const reply = await run(args, Math.min(DISCOVERY_READ_MS, remaining), cwd, DISCOVERY_BYTES);
|
|
95
|
+
if (reply.code !== 0 || Buffer.byteLength(reply.stdout) >= DISCOVERY_BYTES || performance.now() >= deadline) throw new Error("discovery unavailable");
|
|
96
|
+
return JSON.parse(reply.stdout);
|
|
97
|
+
};
|
|
98
|
+
const local = hubGitSync(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], { cwd, encoding: "utf8", timeout: DISCOVERY_READ_MS });
|
|
99
|
+
const remaining = deadline - performance.now();
|
|
100
|
+
const target = local.status === 0 && remaining > 0 ? hubGitSync(["rev-parse", "--verify", "refs/remotes/origin/HEAD^{commit}"], { cwd, encoding: "utf8", timeout: Math.min(DISCOVERY_READ_MS, remaining) }) : undefined;
|
|
101
|
+
let branch = local.status === 0 && target?.status === 0 ? local.stdout.trim().replace(/^refs\/remotes\/origin\//, "") : undefined;
|
|
102
|
+
if (!branch) branch = (await read(["api", `repos/${repo}`])).default_branch;
|
|
103
|
+
if (typeof branch !== "string" || !branch || /[\r\n]/.test(branch)) return workflowChecks(cwd);
|
|
104
|
+
const runs = await read(["api", "--method", "GET", `repos/${repo}/actions/runs`, "-f", `branch=${branch}`, "-f", "status=completed", "-f", "per_page=1"]);
|
|
105
|
+
const latest = runs.workflow_runs?.[0];
|
|
106
|
+
if (!Number.isSafeInteger(latest?.id) || latest.id <= 0 || latest.status !== "completed" || latest.head_branch !== branch) return workflowChecks(cwd);
|
|
107
|
+
const body = await read(["api", "--method", "GET", `repos/${repo}/actions/runs/${latest.id}/jobs`, "-f", `per_page=${DISCOVERY_JOBS}`]);
|
|
108
|
+
const jobs = body.jobs;
|
|
109
|
+
if (!Array.isArray(jobs) || body.total_count !== jobs.length || jobs.length >= DISCOVERY_JOBS) return workflowChecks(cwd);
|
|
110
|
+
const names: unknown[] = [...new Set(jobs.map(job => job?.name))];
|
|
111
|
+
return validNames(names) ? { names, source: "CI" } : workflowChecks(cwd);
|
|
112
|
+
} catch { return workflowChecks(cwd); }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The CLI resolves discovery before preview or write; an override never contacts GitHub. */
|
|
116
|
+
export async function withInitChecks(cwd: string, request: InitSettingsRequest, discover = discoverInitChecks): Promise<InitSettingsRequest> {
|
|
117
|
+
if (!["advise", "enforce"].includes(String(request.values["sdlc.mode"])) || Object.hasOwn(request.values, "sdlc.required_checks")) return request;
|
|
118
|
+
if (requiredChecksFor(loadSdlc(cwd), githubOriginRepository(cwd)).length) return request;
|
|
119
|
+
const result = await discover(cwd);
|
|
120
|
+
if (!result.names.length && request.values["sdlc.mode"] === "enforce") throw new Error(`enforce needs required CI checks: ${result.reason}; nothing was written`);
|
|
121
|
+
return { ...request, values: { ...request.values, "sdlc.required_checks": result.names } };
|
|
122
|
+
}
|
package/src/cli/init-settings.ts
CHANGED
|
@@ -48,8 +48,14 @@ export const INIT_SETTINGS: readonly InitSettingDef[] = [
|
|
|
48
48
|
catch (error) { throw new Error(`${(error as Error).message}; allowed: ${START_AGENTS_ALLOWED.join(", ")} or none; nothing was written`); }
|
|
49
49
|
} },
|
|
50
50
|
{ id: "sdlc.mode", flags: [{ flag: "--sdlc" }], file: "sdlc.toml", path: ["mode"], allowed: SDLC_MODES.join("|"), describe: "SDLC mode", parse: choice("sdlc.mode", "--sdlc", SDLC_MODES) },
|
|
51
|
+
{ id: "sdlc.required_checks", flags: [{ flag: "--required-checks" }], file: "sdlc.toml", path: ["required_checks"], allowed: "comma-separated check names", describe: "required CI checks", parse: text => {
|
|
52
|
+
const names = text.split(",").map(name => name.trim());
|
|
53
|
+
if (!names.length || names.some(name => !name || name.length > 120 || /[\p{Cc}]/u.test(name)) || new Set(names).size !== names.length || names.length > 32) throw new Error("--required-checks needs 1 to 32 distinct check names, each at most 120 characters; nothing was written");
|
|
54
|
+
return names;
|
|
55
|
+
} },
|
|
51
56
|
{ id: "coordination", flags: [{ flag: "--coordination" }], file: "config.json", path: ["coordination"], allowed: COORDINATION_MODES.join("|"), describe: "coordination mode", parse: choice("coordination", "--coordination", COORDINATION_MODES) },
|
|
52
57
|
{ id: "memory.enabled", flags: [{ flag: "--memory", value: true }, { flag: "--no-memory", value: false }], file: "config.json", path: ["memory", "enabled"], allowed: "on|off", describe: "shared memory", parse: () => { throw new Error("unreachable"); } },
|
|
58
|
+
{ id: "research.enabled", flags: [{ flag: "--research", value: true }, { flag: "--no-research", value: false }], file: "config.local.json", path: ["research", "enabled"], allowed: "on|off", describe: "research records", parse: () => { throw new Error("unreachable"); } },
|
|
53
59
|
{ id: "snapshots.enabled", flags: [{ flag: "--snapshots", value: true }, { flag: "--no-snapshots", value: false }], file: "config.json", path: ["snapshots", "enabled"], allowed: "on|off", describe: "per-turn snapshots", parse: () => { throw new Error("unreachable"); } },
|
|
54
60
|
// #1064 T3: the design-specs feature. `--no-specs` also removes the AGENT_HUB_SPECS block from AGENTS.md and `--specs` restores it (init.ts reads the planned `specs.enabled`); the key is shared, so a team commits the choice.
|
|
55
61
|
{ id: "specs.enabled", flags: [{ flag: "--specs", value: true }, { flag: "--no-specs", value: false }], file: "config.json", path: ["specs", "enabled"], allowed: "on|off", describe: "design specs and their freshness checks", parse: () => { throw new Error("unreachable"); } },
|
|
@@ -70,7 +76,7 @@ export interface InitSettingsRequest {
|
|
|
70
76
|
}
|
|
71
77
|
|
|
72
78
|
/** The usage line `ahub init` prints for a bad argument; help.ts shows the same flags. */
|
|
73
|
-
export const INIT_USAGE = "usage: ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--coordination advisory|turn-free] [--memory|--no-memory] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]";
|
|
79
|
+
export const INIT_USAGE = "usage: ahub init [--profile dev|research|writing|general|<pack>] [--agents <a,b,...|none>] [--sdlc off|advise|enforce] [--required-checks <a,b,...>] [--coordination advisory|turn-free] [--memory|--no-memory] [--research|--no-research] [--snapshots|--no-snapshots] [--pi|--no-pi] [--specs|--no-specs] [--spec-review off|report|require] [--autonomy inherit|off] [--shadow] [--release-guard] [--yes] [--dry-run --json]";
|
|
74
80
|
|
|
75
81
|
/** Every flag the table and the two non-key choices own, for the caller's own argument loop and for help. */
|
|
76
82
|
export const INIT_SETTING_FLAGS: readonly string[] = [...INIT_SETTINGS.flatMap(row => row.flags.map(flag => flag.flag)), "--autonomy"];
|
|
@@ -207,13 +213,13 @@ export function planInitSettings(request: InitSettingsRequest, texts: InitSettin
|
|
|
207
213
|
if (!Object.hasOwn(request.values, row.id)) continue;
|
|
208
214
|
const to = request.values[row.id];
|
|
209
215
|
if (row.file === "sdlc.toml") {
|
|
210
|
-
let from: unknown = "off";
|
|
216
|
+
let from: unknown = row.id === "sdlc.mode" ? "off" : [];
|
|
211
217
|
if (texts["sdlc.toml"] !== null) {
|
|
212
|
-
try { const
|
|
218
|
+
try { const held = (Bun.TOML.parse(texts["sdlc.toml"]) as Record<string, unknown>)[row.path[0]!]; if (held !== undefined) from = held; }
|
|
213
219
|
catch { throw new Error(".agenthub/sdlc.toml is not valid TOML; fix it in your editor, then run ahub init again; nothing was written"); }
|
|
214
220
|
}
|
|
215
221
|
if (same(from, to)) continue; // off with no file is the shipped state: no file is written for it
|
|
216
|
-
const text = editSdlcText(next["sdlc.toml"] ?? texts["sdlc.toml"], [{ path: [
|
|
222
|
+
const text = editSdlcText(next["sdlc.toml"] ?? texts["sdlc.toml"], [{ path: [...row.path], value: to }]);
|
|
217
223
|
if (text !== null) next["sdlc.toml"] = text;
|
|
218
224
|
rows.push({ key: row.id, file: "sdlc.toml", from, to });
|
|
219
225
|
continue;
|
package/src/cli/init.ts
CHANGED
|
@@ -12,7 +12,9 @@ import { hubGitArgv, hubGitEnv, hubGitSync } from "../hub/git.ts";
|
|
|
12
12
|
import { KIMI_MCP_FILE } from "./kimi-mcp.ts";
|
|
13
13
|
import { AGY_PLUGIN_FILES } from "./agy-mcp.ts";
|
|
14
14
|
import { loadConfig } from "../hub/daemon.ts";
|
|
15
|
-
import {
|
|
15
|
+
import { requiredChecksFor } from "../hub/sdlc-merge.ts";
|
|
16
|
+
import { githubOriginRepository } from "../hub/task-repository.ts";
|
|
17
|
+
import { loadSdlc, sdlcConfig } from "../hub/sdlc.ts";
|
|
16
18
|
import { VERSION } from "../version.ts";
|
|
17
19
|
import { planInitSettings, type InitSettingFile, type InitSettingRow, type InitSettingsRequest } from "./init-settings.ts";
|
|
18
20
|
|
|
@@ -249,7 +251,7 @@ function changes(cwd: string, requestedName?: string, shadow = false, releaseGua
|
|
|
249
251
|
for (const name of Object.keys(result.next) as InitSettingFile[]) {
|
|
250
252
|
const path = files[name], text = result.next[name]!;
|
|
251
253
|
const row = changed.find(entry => entry.path === path);
|
|
252
|
-
const reason = `set ${result.rows.filter(entry => entry.file === name).map(entry => entry.key).join(", ")} from the init
|
|
254
|
+
const reason = `set ${result.rows.filter(entry => entry.file === name).map(entry => entry.key).join(", ")} from the init settings`;
|
|
253
255
|
if (row) { row.next = text; row.reason = `${row.reason}; ${reason}`; }
|
|
254
256
|
else changed.push({ action: existsSync(path) ? "modify" : "create", path, next: text, reason, ...(name === "config.local.json" ? { privateFile: true as const } : {}) });
|
|
255
257
|
}
|
|
@@ -273,7 +275,10 @@ function checkCandidate(cwd: string, plan: readonly PlannedWrite[]): void {
|
|
|
273
275
|
catch (error) { throw new Error(`the resulting .agenthub config does not pass the hub's config check: ${(error as Error).message}; fix that key in your editor, then run ahub init again; nothing was written`); }
|
|
274
276
|
}
|
|
275
277
|
if (sdlc !== undefined) {
|
|
276
|
-
try {
|
|
278
|
+
try {
|
|
279
|
+
const lifecycle = sdlcConfig(Bun.TOML.parse(sdlc), VERSION);
|
|
280
|
+
if (lifecycle.mode === "enforce" && !requiredChecksFor(lifecycle, githubOriginRepository(cwd)).length) throw new Error("enforce needs required CI checks; pass --required-checks <a,b,...>");
|
|
281
|
+
}
|
|
277
282
|
catch (error) { throw new Error(`the resulting .agenthub/sdlc.toml does not pass the hub's check: ${(error as Error).message}; fix it in your editor, then run ahub init again; nothing was written`); }
|
|
278
283
|
}
|
|
279
284
|
}
|
|
@@ -296,6 +301,37 @@ export function planInit(cwd: string, profile?: string, shadow = false, releaseG
|
|
|
296
301
|
export function initSettingRows(cwd: string, profile?: string, shadow = false, releaseGuard = false, settings?: InitSettingsRequest): InitSettingRow[] {
|
|
297
302
|
return changes(cwd, profile, shadow, releaseGuard, settings).settingRows;
|
|
298
303
|
}
|
|
304
|
+
/** A pre-existing local project choice wins; missing or unreadable machine defaults are off. Validation still runs before any write. */
|
|
305
|
+
export function initResearchDefault(cwd: string, machineValue: boolean | undefined): boolean {
|
|
306
|
+
const local = join(cwd, ".agenthub", "config.local.json");
|
|
307
|
+
try {
|
|
308
|
+
if (existsSync(local)) {
|
|
309
|
+
const value = JSON.parse(readFileSync(local, "utf8"))?.research?.enabled;
|
|
310
|
+
if (typeof value === "boolean") return value;
|
|
311
|
+
}
|
|
312
|
+
} catch { /* the init candidate validation reports malformed local files before writes */ }
|
|
313
|
+
return machineValue === true;
|
|
314
|
+
}
|
|
315
|
+
/** Add only a new project's effective on default to the normal plan. Off is the shipped default; explicit flags always win. Never writes machine defaults. */
|
|
316
|
+
export function withInitResearch(cwd: string, request: InitSettingsRequest, machineValue: boolean | undefined): InitSettingsRequest {
|
|
317
|
+
if (existsSync(join(cwd, ".agenthub", "config.json")) || Object.hasOwn(request.values, "research.enabled") || !initResearchDefault(cwd, machineValue)) return request;
|
|
318
|
+
return { ...request, values: { ...request.values, "research.enabled": true } };
|
|
319
|
+
}
|
|
320
|
+
/** Prepare person guidance before writes; the CLI prints it only after successful apply. Creates no lifecycle evidence or acceptance. */
|
|
321
|
+
export function initNextSteps(cwd: string, settings?: InitSettingsRequest): string[] {
|
|
322
|
+
const lines = [
|
|
323
|
+
"Next steps:",
|
|
324
|
+
"- Review and commit AGENTS.md, .agenthub/config.json and other shared init changes; keep config.local.json untracked.",
|
|
325
|
+
"- Start with ahub up or ahub claude; sessions started otherwise miss hub pushes.",
|
|
326
|
+
];
|
|
327
|
+
const mode = settings?.values["sdlc.mode"] ?? loadSdlc(cwd, VERSION).mode;
|
|
328
|
+
if (mode !== "off") lines.push(
|
|
329
|
+
`- SDLC ${mode}: accept the planner-recorded spec with ahub sdlc accept <task> --issue <n>.`,
|
|
330
|
+
"- When a plan departure needs your consent: ahub sdlc accept-departure <task> <head> <reason...>.",
|
|
331
|
+
"- After hub_task_done on the open PR, reviewer approval and green exact-head CI, use guarded merge: ahub sdlc merge <task>.",
|
|
332
|
+
);
|
|
333
|
+
return lines;
|
|
334
|
+
}
|
|
299
335
|
/** Returns the paths it changed, applying the same plan as the preview. */
|
|
300
336
|
export function init(cwd: string, profile?: string, shadow = false, releaseGuard = false, settings?: InitSettingsRequest): string[] {
|
|
301
337
|
const plan = changes(cwd, profile, shadow, releaseGuard, settings).writes;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { executionReferenceKey, executionText, parseExecutionReference, type ExecutionReferenceV1 } from "../hub/execution-reference.ts";
|
|
2
|
+
import { LINEAGE_LIMITS, type LineageResult } from "../hub/execution-lineage.ts";
|
|
3
|
+
import { executionLineageLines } from "../ui/lineage-view.ts";
|
|
4
|
+
import { terminalText } from "./console-state.ts";
|
|
5
|
+
|
|
6
|
+
export const LINEAGE_USAGE = "usage: ahub lineage show (--task N | --attempt ra-id | --root JSON [--task-scope N --task-created MS]) [--cursor TOKEN] [--nodes N --edges N --bytes N] [--json] | link --task N --task-created MS --revision N --ref JSON [--from JSON] [--json]";
|
|
7
|
+
type Show = { op: "show"; json: boolean; taskId?: number; attemptId?: string; root?: ExecutionReferenceV1; task?: { id: number; created: number }; cursor?: string; nodes?: number; edges?: number; bytes?: number };
|
|
8
|
+
type Link = { op: "link"; json: boolean; taskId: number; taskCreated: number; flowRevision: number; reference: ExecutionReferenceV1; from?: ExecutionReferenceV1 };
|
|
9
|
+
const invalid = (): never => { throw new Error(`invalid lineage arguments; ${LINEAGE_USAGE}`); };
|
|
10
|
+
const integer = (raw: string | undefined, minimum: number, maximum = Number.MAX_SAFE_INTEGER): number => {
|
|
11
|
+
if (raw === undefined || !/^(0|[1-9][0-9]*)$/.test(raw)) return invalid();
|
|
12
|
+
const value = Number(raw);
|
|
13
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) return invalid();
|
|
14
|
+
return value;
|
|
15
|
+
};
|
|
16
|
+
function reference(raw: string | undefined): ExecutionReferenceV1 {
|
|
17
|
+
if (raw === undefined || Buffer.byteLength(raw) > 8192) return invalid();
|
|
18
|
+
try { return parseExecutionReference(JSON.parse(raw)); } catch { return invalid(); }
|
|
19
|
+
}
|
|
20
|
+
/** Shortcuts remain selectors: only the source host can supply their project identity. */
|
|
21
|
+
export function parseLineageCommand(args: readonly string[]): Show | Link {
|
|
22
|
+
const [op, ...rest] = args;
|
|
23
|
+
if (op !== "show" && op !== "link") return invalid();
|
|
24
|
+
const values = new Map<string, string>(); let json = false;
|
|
25
|
+
const allowed = op === "show"
|
|
26
|
+
? ["--task", "--attempt", "--root", "--task-scope", "--task-created", "--cursor", "--nodes", "--edges", "--bytes"]
|
|
27
|
+
: ["--task", "--task-created", "--revision", "--ref", "--from"];
|
|
28
|
+
for (let i = 0; i < rest.length; i++) {
|
|
29
|
+
const flag = rest[i]!;
|
|
30
|
+
if (flag === "--json") { if (json) return invalid(); json = true; continue; }
|
|
31
|
+
if (!allowed.includes(flag) || values.has(flag)) return invalid();
|
|
32
|
+
const value = rest[++i]; if (value === undefined || value.startsWith("--")) return invalid();
|
|
33
|
+
values.set(flag, value);
|
|
34
|
+
}
|
|
35
|
+
if (op === "link") return { op, json, taskId: integer(values.get("--task"), 1), taskCreated: integer(values.get("--task-created"), 0),
|
|
36
|
+
flowRevision: integer(values.get("--revision"), 0), reference: reference(values.get("--ref")),
|
|
37
|
+
...(values.has("--from") ? { from: reference(values.get("--from")) } : {}) };
|
|
38
|
+
if (["--task", "--attempt", "--root"].filter(key => values.has(key)).length !== 1) return invalid();
|
|
39
|
+
const result: Show = { op, json };
|
|
40
|
+
if (values.has("--task")) result.taskId = integer(values.get("--task"), 1);
|
|
41
|
+
if (values.has("--attempt")) {
|
|
42
|
+
const attemptId = values.get("--attempt")!;
|
|
43
|
+
if (!/^ra-[0-9a-f]{12}$/.test(attemptId)) return invalid();
|
|
44
|
+
result.attemptId = attemptId;
|
|
45
|
+
}
|
|
46
|
+
if (values.has("--root")) result.root = reference(values.get("--root"));
|
|
47
|
+
if (values.has("--task-scope") || values.has("--task-created")) {
|
|
48
|
+
if (!result.root) return invalid();
|
|
49
|
+
result.task = { id: integer(values.get("--task-scope"), 1), created: integer(values.get("--task-created"), 0) };
|
|
50
|
+
}
|
|
51
|
+
if (values.has("--cursor")) {
|
|
52
|
+
const cursor = values.get("--cursor")!;
|
|
53
|
+
if (cursor.length > LINEAGE_LIMITS.cursor || !/^[A-Za-z0-9_-]+$/.test(cursor)) return invalid();
|
|
54
|
+
result.cursor = cursor;
|
|
55
|
+
}
|
|
56
|
+
if (values.has("--nodes")) result.nodes = integer(values.get("--nodes"), 1, LINEAGE_LIMITS.nodes);
|
|
57
|
+
if (values.has("--edges")) result.edges = integer(values.get("--edges"), 1, LINEAGE_LIMITS.edges);
|
|
58
|
+
if (values.has("--bytes")) result.bytes = integer(values.get("--bytes"), LINEAGE_LIMITS.minimumBytes, LINEAGE_LIMITS.bytes);
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The closed shape check lives in the hub module, beside the reader that produces it, so the console reads it identically (#1220 T3). */
|
|
63
|
+
export { parseLineageResult as validateLineageReply } from "../hub/execution-lineage.ts";
|
|
64
|
+
export interface LineageLinkReceipt { id: string; taskId: number; reference: ExecutionReferenceV1; strength: "declared"; already: boolean }
|
|
65
|
+
export function validateLineageLink(value: unknown, command: { taskId: number; reference: ExecutionReferenceV1 }): LineageLinkReceipt {
|
|
66
|
+
const bad = (): never => { throw new Error("lineage link reply is unconfirmed; inspect ahub lineage show before retrying the link"); };
|
|
67
|
+
try {
|
|
68
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Buffer.byteLength(JSON.stringify(value)) > 8192) return bad();
|
|
69
|
+
const row = value as Record<string, unknown>, keys = ["id", "taskId", "reference", "strength", "already"];
|
|
70
|
+
if (Object.keys(row).length !== keys.length || !keys.every(key => Object.hasOwn(row, key)) || !executionText(row.id, 256) ||
|
|
71
|
+
row.taskId !== command.taskId || row.strength !== "declared" || typeof row.already !== "boolean" ||
|
|
72
|
+
executionReferenceKey(parseExecutionReference(row.reference)) !== executionReferenceKey(command.reference)) return bad();
|
|
73
|
+
return value as LineageLinkReceipt;
|
|
74
|
+
} catch { return bad(); }
|
|
75
|
+
}
|
|
76
|
+
/** The CLI is a terminal: the shared view crosses `terminalText` here, at this surface's own boundary. */
|
|
77
|
+
export const renderExecutionLineage = (result: LineageResult): string[] =>
|
|
78
|
+
executionLineageLines(result).map(line => terminalText(line).replace(/[\r\n]+/g, " "));
|