@astrofoundry/pi-astro 0.40.82 → 0.40.84

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.82",
3
+ "version": "0.40.84",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -7,7 +7,7 @@ description: How the Arcane specialist operates the Arcane container platform an
7
7
 
8
8
  Arcane manages the Docker host on VM 100 (`10.0.40.30`). Every app is a Compose project synced from the GitOps repository `astronaute77/arcane`, branch `main`, into `/opt/docker`. The `arcane` tool wraps `arcane-cli` with a fresh short-lived token on every call and adds `git` subcommands for the repository checkout. `arcane-cli gitops ...` (server-side syncs) passes through untouched.
9
9
 
10
- Since 2026-11-09 a second environment, `mira`, runs the `media-mira` project on media-mira (`10.1.40.30`, VM 111 on SPACE-X at Mira) through an Edge agent. `stack-update`, `stack-rollback`, `deployment`, and `release-notes` find a stack's environment themselves; `update-report`, `container-watch`, and `project-status` cover every environment and name the remote one in `environment`. A raw arcane-cli call on Mira needs `--env f1968df8-bce3-4a65-966f-72934727ae86` (the wrapper turns `--env` into `--agent` for arcane-cli 3, and a call without either goes to the manager's own host). The `host` commands reach VM 100 only.
10
+ Since 2026-11-09 a second environment, `mira`, runs the `media-mira` project on media-mira (`10.1.40.30`, VM 111 on SPACE-X at Mira) through an Arcane agent (v3.0.1, a gRPC tunnel to the manager). `stack-update`, `stack-rollback`, `deployment`, and `release-notes` find a stack's environment themselves; `update-report`, `container-watch`, and `project-status` cover every environment and name the remote one in `environment`. A raw arcane-cli call on Mira needs `--agent f1968df8-bce3-4a65-966f-72934727ae86`; a call without `--agent` goes to the manager's own host (agent `0`). arcane-cli 3 calls them agents (`agents list`, `agents version <id>`), not environments. The `host` commands reach VM 100 only; for a container on Mira, read its log with `["container-logs", "<name>", "<since>", "<until>"]` (below).
11
11
 
12
12
  ## Calling the tool
13
13
 
@@ -106,6 +106,8 @@ When the bridge's Upgrade carefully thread gives you a plan task, read the notes
106
106
 
107
107
  `["change-origin", "<path>", "<sha256|->", "<utc>"]` answers whether a deployment-file change Wazuh saw on the Arcane VM (`/opt/docker/<project>/compose.yaml`, `docker-compose.yml`, or `pre-deploy.sh`; rule 100020) is ours. `known` when the new content (its SHA-256 from the alert's `syscheck.sha256_after`), or `-` for a deletion, equals a commit of `<project>/<file>` at origin, any author, CI included; or when our `stack-update`, `manager-upgrade`, `manager-rollback`, or `host db-restore` on that stack ran then (the specialists' audit log). Otherwise `unknown`, with the newest commit touching the file. Arcane syncs the files verbatim, so a GitOps deploy always matches. The Discord bridge calls it for every such alert; an `unknown` change pages the owner.
108
108
 
109
+ `["container-logs", "<name>", "<since>", "<until>"]` (UTC `YYYY-MM-DDTHH:MM:SSZ`) reads the newest 300 lines of that window for a container on any agent, Mira's included, through Arcane's log download, with credentials masked like `host container-logs ... text`; call them redacted log lines. Use it for Mira's containers (such as `radarr-mira`), where `host container-logs` cannot reach.
110
+
109
111
  `["container-watch"]` lists every container with its state, health, exit code, and uptime; containers started or created in the last 30 minutes also carry the start time, the Compose project, and the `operation` (our stack-update, manager-upgrade, manager-rollback, or host db-restore on that stack) whose run covers the start. The Discord bridge polls it every five minutes to detect restarts and redeploys; when it asks you to investigate a container that keeps restarting, read only and propose the fix.
110
112
 
111
113
  `["project-status"]` (or with a project name) lists projects with their GitOps sync: commit, state, hook state, without error text. `["deployment", "check"|"wait", "<project>", "--commit", "<sha>", "--container", "NAME=sha256:ID", ...]` compares the sync and each container's project, image ID, state, and health; `wait` polls every 10 s up to `--timeout` (default 600 s). Read `status` in the answer.
@@ -53,8 +53,9 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
53
53
  - `inference` reaches Nexus through one forced-command key. The Europa check is HTTP only until Windows OpenSSH forced commands are verified.
54
54
  - `REFUSED_PREFIXES` protects only the wrapper itself (`config`, `auth`, `self-update`, `completion`). The GitOps-first rule for managed projects lives in the skill and the agent prompt, not in code, because unmanaged projects and emergencies need the direct CLI.
55
55
  - The wrapper's repository commands are the `git` group; `gitops` must stay free because it is an `arcane-cli` command group (server-side syncs).
56
- - arcane-cli 3 (Arcane 3.0) renamed `--env` to `--agent` and `environments` to `agents`, and without `--agent` runs a command on every agent and wraps each answer in `{success, agents}`. Since 0.40.82 the wrapper writes every call in the 2.x form and `cliArgs` translates it for the installed major (`arcane-cli --version`, read once per invocation): a 3.x call always names its agent (`--agent 0`, the manager's own host, by default), which keeps the 2.x output shapes (`RunScoped` in the CLI's `cmdutil/scope.go` runs a call with an agent like 2.x did, checked at v3.0.1). The same wrapper therefore runs before and after the manager upgrade. `envContent` (v3's Git sync environment values) is in `ARCANE_DENIED_KEYS`.
57
- - Every passthrough call writes a private per-call copy of `arcanecli.yml` with `jwt_token` set, because some `arcane-cli` commands validate the config file before reading `ARCANE_TOKEN`. The copy is removed after the call. arcane-cli prints a warning on stderr that `jwt_token` and `refresh_token` in the config stop working in v3 (in the bridge log since 2026-10-23); `cliFailure` therefore names the exit code and the filtered stdout as well, because a failure can carry nothing else on stderr (the media update on 2026-11-02).
56
+ - Arcane and arcane-cli run 3.x since 2026-11-16. Without `--agent`, arcane-cli 3 runs a command on every agent and wraps each answer in `{success, agents}`, and asks before a change on all of them; `withAgent` therefore names the agent on every call (`--agent 0`, the manager's own host, unless the call names another), which keeps the plain output shape (`RunScoped` in the CLI's `cmdutil/scope.go`, read at v3.0.1). `environments` is `agents` and `--env` is `--agent` in 3.x. `envContent` (Git sync environment values) is in `ARCANE_DENIED_KEYS`.
57
+ - `arcane container-logs <name> <since> <until>` (0.40.84, `lib/arcane-logs.ts`) finds the container on any agent through `containers list --all` and streams `GET /api/agents/<id>/containers/<containerId>/logs/download` (Arcane 3: the whole log with timestamps, `containers:logs`) with the federated token, keeping the newest 300 stamped lines inside `[since, until)` and stopping at the first line past `until`. `redactText` mirrors `redact_text` of the arcane repository's `host/spc-arcane-probes/incident_probe.py`; change both together. It exists because the `host` commands reach only VM 100, so Radarr's v7 migration log on Mira was out of reach on 2026-11-16.
58
+ - Every call runs with the federated token in `ARCANE_TOKEN`, which arcane-cli 3 uses ahead of any credential in `arcanecli.yml` (`client.New`); the per-call config copy with `jwt_token` that 2.x needed is gone (0.40.83). `cliFailure` names the exit code and the filtered stdout as well as stderr, because a failure can carry nothing else on stderr (the media update on 2026-11-02).
58
59
  - Every wrapper answers `--help` without reading config, so agents can discover subcommands before anything else is set up.
59
60
  - `entry/specialist-install.sh` runs as root, so it runs only `/usr/bin`, `/bin`, `/usr/sbin`, `/sbin` and the Node it installed, never Homebrew or anything else the main user can write; it checks that `/usr/local/libexec/specialist-node` (and each `specialist-<tool>` folder) and its parents belong to root and are writable by nobody else. Arguments are checked before the root test (tests exercise that part). Downloads go to a root-only temporary directory and are verified before use: Node against `SHASUMS256.txt` and the LTS flag in `index.json`, npm tarballs against the registry's `sha512` integrity, arcane-cli against the release's checksums file. Inside `/Users/specialist` it works only as `specialist` (`sudo -u specialist -H`), from a staging directory root hands over, so a link the specialist plants cannot redirect a root write. Each component switches by rename after a check (every installed wrapper's `--help`, `--version` of the new binary) and restores the previous copy when the check fails. Older versions are refused; `rollback` swaps current and previous. `python`, `gcloud`, `bw`, and `jq` follow the same rules: version folders under `/usr/local/libexec/specialist-<tool>/` behind the links `current` and `previous`, sealed `root:wheel` and not writable by others, smoke-tested as `specialist` before `current` moves; `python` refuses a switch that breaks the current gcloud. Consumers use the `current` paths: `provision.sh` for `bw` and `jq`, `edge.json` for `gcloud` and `gcloudPython`. Nothing a wrapper runs with secrets may come from Homebrew.
60
61
  - `main()` waits for stdout and stderr to flush before `process.exit`: on a pipe, exiting right after a write drops everything past the 64 KiB buffer, which cut large answers such as `projects list --all` until 2026-09-25 (`lib/flush.test.ts`).
@@ -1,12 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { dirname, join } from "node:path";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
5
4
  import { buildHostRemote, compareAudit, HOST_COMMANDS, type AuditFile } from "../lib/arcane-host.ts";
6
5
  import { type CommitVersion, coveringOperation, judgeChange, parseChangeQuery, readTail } from "../lib/change-origin.ts";
7
6
  import { failedChecks, MANAGER_COMPOSE, MANAGER_IMAGE, normalizeVersion, olderThan, pinCompose, projectSync, syncId, syncReady, utcStamp, type VerifyCheck } from "../lib/arcane-manager.ts";
8
7
  import { readConfig } from "../lib/config.ts";
9
8
  import { isRecent, listContainer, type WatchedContainer, withDetail } from "../lib/container-watch.ts";
9
+ import { LogWindow } from "../lib/arcane-logs.ts";
10
10
  import { containerFacts, deploymentChecks, listRows, parseDeploymentArgs, syncFacts, type DeploymentExpectation } from "../lib/deployment.ts";
11
11
  import { ServiceError, UsageError } from "../lib/errors.ts";
12
12
  import { withLock } from "../lib/lock.ts";
@@ -58,59 +58,18 @@ const HOST_SHAPE = { hostAddress: "string", hostUser: "string" } as const;
58
58
  export const REFUSED_PREFIXES: readonly string[] = ["config", "auth", "self-update", "completion"];
59
59
 
60
60
  /** Global arcane-cli flags that take a separate value. */
61
- const VALUE_FLAGS = ["--env", "--agent", "--output", "--config", "-c", "--request-timeout", "--log-level", "--limit"];
61
+ const VALUE_FLAGS = ["--agent", "--output", "--config", "-c", "--request-timeout", "--log-level", "--limit"];
62
62
 
63
- /** The manager's own Docker host, which arcane-cli 2 reaches without --env and 3 names `--agent 0`. */
63
+ /** The manager's own Docker host, agent `0`. */
64
64
  const LOCAL_ENV = "0";
65
65
 
66
66
  /**
67
- * arcane-cli 3 renamed `--env` to `--agent` and `environments` to `agents`, and
68
- * without `--agent` it runs a command on every agent and wraps each answer.
69
- * Calls are written in the 2.x form; for a 3.x CLI this names the agent on every
70
- * call (the manager's own host when none is given), which keeps 2.x output.
67
+ * arcane-cli 3 runs a command on every agent and wraps each answer when no
68
+ * `--agent` is given, so every call names its agent: the manager's own host
69
+ * unless the call names another. With one agent the output keeps the plain shape.
71
70
  */
72
- export function cliArgs(args: readonly string[], major: number): string[] {
73
- if (major < 3) return [...args];
74
- const out: string[] = [];
75
- let positional = false;
76
- let scoped = false;
77
- for (let i = 0; i < args.length; i++) {
78
- const a = args[i];
79
- if (a === "--env" || a === "--agent") {
80
- out.push("--agent", args[i + 1] ?? "");
81
- scoped = true;
82
- i++;
83
- } else if (a.startsWith("--env=") || a.startsWith("--agent=")) {
84
- out.push(`--agent=${a.slice(a.indexOf("=") + 1)}`);
85
- scoped = true;
86
- } else if (VALUE_FLAGS.includes(a)) {
87
- out.push(a, args[i + 1] ?? "");
88
- i++;
89
- } else if (!positional && !a.startsWith("-")) {
90
- positional = true;
91
- out.push(a === "environments" ? "agents" : a);
92
- } else {
93
- out.push(a);
94
- }
95
- }
96
- return scoped ? out : ["--agent", LOCAL_ENV, ...out];
97
- }
98
-
99
- /** The major version of the installed arcane-cli, from its `--version` line. */
100
- export function cliMajorOf(versionOutput: string): number {
101
- const m = /(\d+)\.\d+\.\d+/.exec(versionOutput);
102
- if (!m) throw new ServiceError(`arcane-cli --version printed no version: ${versionOutput.trim().slice(0, 200)}`);
103
- return Number(m[1]);
104
- }
105
-
106
- let cliMajorCache: number | undefined;
107
-
108
- async function cliMajor(config: ArcaneConfig): Promise<number> {
109
- if (cliMajorCache !== undefined) return cliMajorCache;
110
- const result = await run(config.arcaneCli, ["--version"], { timeoutMs: 30_000 });
111
- if (result.code !== 0) throw new ServiceError(`arcane-cli --version failed: ${result.stderr.trim()}`);
112
- cliMajorCache = cliMajorOf(result.stdout);
113
- return cliMajorCache;
71
+ export function withAgent(args: readonly string[], agent: string = LOCAL_ENV): string[] {
72
+ return args.some((a) => a === "--agent" || a.startsWith("--agent=")) ? [...args] : ["--agent", agent, ...args];
114
73
  }
115
74
 
116
75
  /** Positional words of an arcane-cli invocation, with global flags and their values removed. */
@@ -176,6 +135,9 @@ ${Object.entries(HOST_COMMANDS)
176
135
  docker-compose.yml, pre-deploy.sh) is ours: known when the new content, or the deletion,
177
136
  is a commit of <project>/<file> in the GitOps repository, or when our stack-update,
178
137
  manager-upgrade, manager-rollback, or host db-restore on that stack ran then (audit log)
138
+ container-logs <name> <since> <until>
139
+ the newest 300 log lines of a UTC window (YYYY-MM-DDTHH:MM:SSZ) of a container on any agent,
140
+ Mira's included, through Arcane's log download; credentials masked (redacted log lines)
179
141
  container-watch every container's state in every environment, health, exit code, and uptime; for those started or created in
180
142
  the last 30 minutes also the start time, the Compose project, and our stack-update,
181
143
  manager-upgrade, manager-rollback, or host db-restore whose run covers the start (JSON)
@@ -225,38 +187,16 @@ async function federatedToken(config: ArcaneConfig): Promise<string> {
225
187
  return match[1];
226
188
  }
227
189
 
228
- /**
229
- * Some arcane-cli commands validate credentials in the config file before they
230
- * look at ARCANE_TOKEN, so the token goes into a private per-call copy of the
231
- * config as well. The copy lives for one command and is removed afterwards.
232
- */
233
- function writeCallConfig(config: ArcaneConfig, token: string): string {
234
- const base = readFileSync(config.arcaneCliConfig, "utf-8").replace(/^(jwt_token|api_key|refresh_token):.*$/gm, "");
235
- const dir = mkdtempSync(join(tmpdir(), "arcane-run-"));
236
- const file = join(dir, "arcanecli.yml");
237
- writeFileSync(file, `${base.trimEnd()}\njwt_token: ${JSON.stringify(token)}\n`, { mode: 0o600 });
238
- return file;
239
- }
240
-
241
190
  type Cli = (args: string[], timeoutMs?: number) => Promise<{ stdout: string; stderr: string; code: number }>;
242
191
 
243
192
  /** The Arcane environment the calls of this invocation target; unset is the manager's own Docker host. Stack commands set it to their stack's environment. */
244
193
  let targetEnv: string | undefined;
245
194
 
246
- /** One federated token and one private config copy for every arcane-cli call of this invocation. */
195
+ /** One federated token for every arcane-cli call of this invocation. */
247
196
  async function withCli<T>(config: ArcaneConfig, fn: (cli: Cli) => Promise<T>, env: string | undefined = targetEnv): Promise<T> {
248
- const major = await cliMajor(config);
249
197
  const token = await federatedToken(config);
250
- const callConfig = writeCallConfig(config, token);
251
- const at = env === undefined ? [] : ["--env", env];
252
- try {
253
- return await fn((args, timeoutMs = TIMEOUT_MS) => {
254
- const scoped = args.some((a) => a === "--env" || a === "--agent" || a.startsWith("--env=") || a.startsWith("--agent=")) ? args : [...at, ...args];
255
- return run(config.arcaneCli, ["--config", callConfig, "--no-color", ...cliArgs(scoped, major)], { env: { ARCANE_TOKEN: token }, timeoutMs });
256
- });
257
- } finally {
258
- rmSync(dirname(callConfig), { recursive: true, force: true });
259
- }
198
+ // ARCANE_TOKEN takes precedence over any credential in the config file (arcane-cli 3 client.New).
199
+ return fn((args, timeoutMs = TIMEOUT_MS) => run(config.arcaneCli, ["--config", config.arcaneCliConfig, "--no-color", ...withAgent(args, env)], { env: { ARCANE_TOKEN: token }, timeoutMs }));
260
200
  }
261
201
 
262
202
  async function passthrough(config: ArcaneConfig, args: string[]): Promise<number> {
@@ -297,7 +237,7 @@ interface ArcaneEnv {
297
237
 
298
238
  /** Every enabled environment, the manager's own first. */
299
239
  async function arcaneEnvs(cli: Cli): Promise<ArcaneEnv[]> {
300
- const envs = listRows(await cliJson(cli, ["environments", "list"]))
240
+ const envs = listRows(await cliJson(cli, ["agents", "list"]))
301
241
  .filter((e) => e.enabled !== false && typeof e.id === "string" && typeof e.name === "string")
302
242
  .map((e) => ({ id: e.id as string, name: e.name as string }));
303
243
  return envs.sort((a, b) => Number(b.id === LOCAL_ENV) - Number(a.id === LOCAL_ENV) || a.name.localeCompare(b.name));
@@ -305,7 +245,7 @@ async function arcaneEnvs(cli: Cli): Promise<ArcaneEnv[]> {
305
245
 
306
246
  /** arcane-cli arguments that point one call at an environment. */
307
247
  function envArgs(env: ArcaneEnv): string[] {
308
- return env.id === LOCAL_ENV ? [] : ["--env", env.id];
248
+ return ["--agent", env.id];
309
249
  }
310
250
 
311
251
  /** The remote environment that runs this stack, or undefined for the manager's own host; stack names are unique across environments. */
@@ -358,7 +298,7 @@ async function updateReport(config: ArcaneConfig, args: string[]): Promise<numbe
358
298
  // Each remote agent should run the manager's version; manager-upgrade moves only the manager.
359
299
  const agentsBehind: { environment: string; agent: string; manager: string }[] = [];
360
300
  const versionOf = async (env: ArcaneEnv): Promise<string> => {
361
- const answer = await cliJson(cli, ["environments", "version", env.id]);
301
+ const answer = await cliJson(cli, ["agents", "version", env.id]);
362
302
  const current = typeof answer === "object" && answer !== null ? (answer as { currentVersion?: unknown }).currentVersion : undefined;
363
303
  return typeof current === "string" ? current : "?";
364
304
  };
@@ -465,6 +405,61 @@ async function changeOrigin(config: ArcaneConfig, args: string[]): Promise<numbe
465
405
  }
466
406
 
467
407
  /** Container state for the Discord bridge's restart and redeploy checks: one list, plus details only for recent starts. */
408
+ const LOG_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
409
+ const LOG_DOWNLOAD_TIMEOUT_MS = 5 * 60_000;
410
+
411
+ /** A container's log window on any agent, through Arcane's log download, with credentials masked like `host container-logs ... text`. */
412
+ async function containerLogs(config: ArcaneConfig, args: string[]): Promise<number> {
413
+ const usage = "container-logs <name> <since> <until> (UTC YYYY-MM-DDTHH:MM:SSZ, until after since)";
414
+ if (args.length !== 3 || !NAME.test(args[0]) || !LOG_UTC.test(args[1]) || !LOG_UTC.test(args[2])) throw new UsageError(usage);
415
+ const sinceMs = Date.parse(args[1]);
416
+ const untilMs = Date.parse(args[2]);
417
+ if (!(untilMs > sinceMs)) throw new UsageError(usage);
418
+ const found = await withCli(
419
+ config,
420
+ async (cli) => {
421
+ const hits: { env: ArcaneEnv; id: string }[] = [];
422
+ for (const env of await arcaneEnvs(cli)) {
423
+ for (const row of listRows(await cliJson(cli, [...envArgs(env), "containers", "list", "--all"]))) {
424
+ const c = listContainer(row);
425
+ if (c?.name === args[0]) hits.push({ env, id: c.id });
426
+ }
427
+ }
428
+ return hits;
429
+ },
430
+ undefined,
431
+ );
432
+ if (found.length !== 1) throw new UsageError(found.length === 0 ? `no container named ${args[0]}` : `${args[0]} exists on several agents: ${found.map((f) => f.env.name).join(", ")}`);
433
+ const { env, id } = found[0];
434
+ const token = await federatedToken(config);
435
+ const res = await fetch(`${config.serverUrl}/api/agents/${encodeURIComponent(env.id)}/containers/${encodeURIComponent(id)}/logs/download`, {
436
+ headers: { authorization: `Bearer ${token}` },
437
+ signal: AbortSignal.timeout(LOG_DOWNLOAD_TIMEOUT_MS),
438
+ });
439
+ if (!res.ok || res.body === null) throw new ServiceError(`log download for ${args[0]} answered ${res.status}`);
440
+ const window = new LogWindow(sinceMs, untilMs);
441
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
442
+ let rest = "";
443
+ let open = true;
444
+ while (open) {
445
+ const { value, done } = await reader.read();
446
+ if (done) break;
447
+ const parts = (rest + value).split("\n");
448
+ rest = parts.pop() ?? "";
449
+ for (const line of parts) {
450
+ if (!window.push(line.replace(/\r$/, ""))) {
451
+ open = false;
452
+ break;
453
+ }
454
+ }
455
+ }
456
+ if (open && rest.length > 0) window.push(rest);
457
+ await reader.cancel().catch(() => undefined);
458
+ const { lines, omittedOlderLines } = window.result();
459
+ printJson({ name: args[0], agent: env.name, container_id: id, since: args[1], until: args[2], source: "text", redacted: true, omitted_older_lines: omittedOlderLines, lines });
460
+ return 0;
461
+ }
462
+
468
463
  async function containerWatch(config: ArcaneConfig, args: string[]): Promise<number> {
469
464
  if (args.length > 0) throw new UsageError("container-watch takes no arguments");
470
465
  let audit: string;
@@ -1036,6 +1031,7 @@ export async function command(args: string[]): Promise<number> {
1036
1031
  if (args[0] === "release-notes") return releaseNotes(config, args.slice(1));
1037
1032
  if (args[0] === "change-origin") return changeOrigin(config, args.slice(1));
1038
1033
  if (args[0] === "container-watch") return containerWatch(config, args.slice(1));
1034
+ if (args[0] === "container-logs") return containerLogs(config, args.slice(1));
1039
1035
  if (args[0] === "host") return hostCommand(config, args.slice(1));
1040
1036
  if (args[0] === "project-status") return projectStatus(config, args.slice(1));
1041
1037
  if (args[0] === "deployment") return deployment(config, args.slice(1));
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { LogWindow, redactText, stampMs, TEXT_CHARS, TEXT_LINES } from "./arcane-logs.ts";
3
+
4
+ const SECRET = "SYNTHETIC_SECRET_MUST_NOT_APPEAR";
5
+
6
+ describe("redactText", () => {
7
+ it("keeps the message and masks credentials", () => {
8
+ const out = redactText(`Startup failed: password=${SECRET} for https://user:${SECRET}@db.example/x, Authorization: Bearer ${SECRET}`);
9
+ expect(out).toContain("Startup failed");
10
+ expect(out).not.toContain(SECRET);
11
+ expect(out).toContain("https://[redacted]@db.example/x");
12
+ });
13
+ it("masks JWTs and long random tokens", () => {
14
+ const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlc2lnbmF0dXJl";
15
+ expect(redactText(`token ${jwt}`)).not.toContain("eyJhbGci");
16
+ expect(redactText("id a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8")).toBe("id [redacted]");
17
+ });
18
+ it("strips ANSI colors and control characters", () => {
19
+ expect(redactText(`${String.fromCharCode(27)}[92mINF${String.fromCharCode(27)}[0m started\tok`)).toBe("INF started ok");
20
+ });
21
+ it("cuts long messages without keeping a split word", () => {
22
+ const out = redactText(`${"word ".repeat(2000)}tail`);
23
+ expect(out.endsWith(" [cut]")).toBe(true);
24
+ expect(out.length).toBe(TEXT_CHARS + " [cut]".length);
25
+ });
26
+ });
27
+
28
+ describe("stampMs", () => {
29
+ it("reads Docker's nanosecond timestamps", () => {
30
+ expect(stampMs("2026-11-16T05:55:28.150475752Z")).toBe(Date.parse("2026-11-16T05:55:28.150Z"));
31
+ expect(stampMs("2026-11-16T05:55:28Z")).toBe(Date.parse("2026-11-16T05:55:28Z"));
32
+ expect(stampMs("not-a-time")).toBeNull();
33
+ });
34
+ });
35
+
36
+ describe("LogWindow", () => {
37
+ const since = Date.parse("2026-11-16T05:00:00Z");
38
+ const until = Date.parse("2026-11-16T06:00:00Z");
39
+
40
+ it("keeps lines inside the window and stops past its end", () => {
41
+ const w = new LogWindow(since, until);
42
+ expect(w.push("2026-11-16T04:59:59.9Z before")).toBe(true);
43
+ expect(w.push("2026-11-16T05:30:00.123456789Z inside")).toBe(true);
44
+ expect(w.push("unstamped continuation")).toBe(true);
45
+ expect(w.push("2026-11-16T06:00:00Z after")).toBe(false);
46
+ expect(w.result()).toEqual({ lines: [{ timestamp: "2026-11-16T05:30:00.123456789Z", text: "inside" }], omittedOlderLines: 0 });
47
+ });
48
+ it("keeps the newest lines and counts the older ones", () => {
49
+ const w = new LogWindow(since, until);
50
+ for (let i = 0; i < TEXT_LINES + 5; i++) w.push(`2026-11-16T05:${String(Math.floor(i / 60)).padStart(2, "0")}:${String(i % 60).padStart(2, "0")}Z line ${i}`);
51
+ const { lines, omittedOlderLines } = w.result();
52
+ expect(lines).toHaveLength(TEXT_LINES);
53
+ expect(omittedOlderLines).toBe(5);
54
+ expect(lines[0].text).toBe("line 5");
55
+ });
56
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Container log lines read through Arcane's API, so a container on any agent
3
+ * (Mira's included) can be read like `host container-logs ... text` reads one
4
+ * on the manager's own host: the newest lines of a UTC window, credentials
5
+ * masked. The masking mirrors `redact_text` in the arcane repository's
6
+ * `host/spc-arcane-probes/incident_probe.py`; keep the two in step.
7
+ */
8
+
9
+ export const TEXT_LINES = 300;
10
+ export const TEXT_CHARS = 500;
11
+ const REDACTED = "[redacted]";
12
+ const SECRET_WORD = String.raw`(?:secret|token|passw(?:or)?d|pwd|pass|api[_-]?key|key|auth\w*|credential|cookie|session|signature|sig|salt|hash)`;
13
+
14
+ const TEXT_REDACTIONS: readonly [RegExp, string][] = [
15
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----.*/gi, REDACTED],
16
+ [/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]*@/gi, `$1${REDACTED}@`],
17
+ [/\b(bearer|basic|digest|token)(\s+)[A-Za-z0-9._~+/=-]{8,}/gi, `$1$2${REDACTED}`],
18
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g, REDACTED],
19
+ [new RegExp(String.raw`([A-Za-z0-9_.-]*${SECRET_WORD}[A-Za-z0-9_.-]*["']?\s*[:=]\s*["']?)[^\s"',;&)}\]]+`, "gi"), `$1${REDACTED}`],
20
+ [/(?<![A-Za-z0-9+/_-])(?=[A-Za-z0-9+/_-]*[0-9])(?=[A-Za-z0-9+/_-]*[A-Za-z])[A-Za-z0-9+/_-]{32,}={0,2}/g, REDACTED],
21
+ ];
22
+
23
+ /** ANSI escape sequences, built from the escape character so the pattern holds no control character. */
24
+ const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
25
+
26
+ /** Masks credentials in one log message; it over-masks rather than let a secret through. */
27
+ export function redactText(message: string): string {
28
+ const cut = message.length > 8 * TEXT_CHARS;
29
+ let text = message;
30
+ if (cut) {
31
+ // Drop the word split by the cut: a partial secret would be too short to match a pattern.
32
+ const head = text.slice(0, 8 * TEXT_CHARS);
33
+ const space = head.lastIndexOf(" ");
34
+ text = space >= 0 ? head.slice(0, space) : head;
35
+ }
36
+ text = text.replace(ANSI, "").replace(/[\p{C}\p{Z}]/gu, " ");
37
+ for (const [pattern, replacement] of TEXT_REDACTIONS) text = text.replace(pattern, replacement);
38
+ return cut || text.length > TEXT_CHARS ? `${text.slice(0, TEXT_CHARS)} [cut]` : text;
39
+ }
40
+
41
+ const STAMP = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?Z$/;
42
+
43
+ /** Milliseconds of a Docker timestamp (nanosecond fraction allowed), or null. */
44
+ export function stampMs(stamp: string): number | null {
45
+ const m = STAMP.exec(stamp);
46
+ if (!m) return null;
47
+ const ms = Date.parse(`${m[1]}.${(m[2] ?? "").padEnd(3, "0").slice(0, 3)}Z`);
48
+ return Number.isNaN(ms) ? null : ms;
49
+ }
50
+
51
+ export interface LogRow {
52
+ timestamp: string;
53
+ text: string;
54
+ }
55
+
56
+ /**
57
+ * Collects the newest TEXT_LINES stamped lines inside [since, until) from a
58
+ * chronological stream. `push` returns false once a line is past `until`, so
59
+ * the caller can stop reading.
60
+ */
61
+ export class LogWindow {
62
+ private readonly rows: [string, string][] = [];
63
+ private omitted = 0;
64
+ private readonly sinceMs: number;
65
+ private readonly untilMs: number;
66
+
67
+ constructor(sinceMs: number, untilMs: number) {
68
+ this.sinceMs = sinceMs;
69
+ this.untilMs = untilMs;
70
+ }
71
+
72
+ push(line: string): boolean {
73
+ const space = line.indexOf(" ");
74
+ if (space <= 0) return true;
75
+ const stamp = line.slice(0, space);
76
+ const ms = stampMs(stamp);
77
+ if (ms === null || ms < this.sinceMs) return true;
78
+ if (ms >= this.untilMs) return false;
79
+ this.rows.push([stamp, line.slice(space + 1)]);
80
+ if (this.rows.length > TEXT_LINES) {
81
+ this.rows.shift();
82
+ this.omitted++;
83
+ }
84
+ return true;
85
+ }
86
+
87
+ result(): { lines: LogRow[]; omittedOlderLines: number } {
88
+ return { lines: this.rows.map(([timestamp, message]) => ({ timestamp, text: redactText(message) })), omittedOlderLines: this.omitted };
89
+ }
90
+ }
@@ -5,7 +5,7 @@ import type { AddressInfo } from "node:net";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
8
- import { cliArgs, cliFailure, cliMajorOf, refusedPrefix, command as arcaneCommand } from "./arcane/run.ts";
8
+ import { cliFailure, refusedPrefix, withAgent, command as arcaneCommand } from "./arcane/run.ts";
9
9
  import { buildBackupRemote, command as backupCommand } from "./backup/run.ts";
10
10
  import { buildNodeRemote, parseJoinArgs, parseParams, parseRecordFilters, technitiumRequest, technitiumTarget, command as dnsCommand } from "./dns/run.ts";
11
11
  import { buildVpsRemote, command as edgeCommand, isTransientSshFailure, PUBLIC_ROUTES, routeProbe } from "./edge/run.ts";
@@ -24,7 +24,7 @@ describe("arcane wrapper", () => {
24
24
  it("refuses only the wrapper's own setup paths", () => {
25
25
  expect(refusedPrefix(["projects", "create", "x"])).toBeNull();
26
26
  expect(refusedPrefix(["projects", "update", "arcane", "--flag"])).toBeNull();
27
- expect(refusedPrefix(["--env", "0", "auth", "login"])).toBe("auth");
27
+ expect(refusedPrefix(["--agent", "0", "auth", "login"])).toBe("auth");
28
28
  expect(refusedPrefix(["self-update"])).toBe("self-update");
29
29
  expect(refusedPrefix(["config", "set", "api-key", "x"])).toBe("config");
30
30
  expect(refusedPrefix(["projects", "list"])).toBeNull();
@@ -1314,24 +1314,14 @@ describe("research wrapper", () => {
1314
1314
  });
1315
1315
  });
1316
1316
 
1317
- describe("arcane-cli 3 arguments", () => {
1318
- it("keeps 2.x arguments unchanged", () => {
1319
- expect(cliArgs(["--env", "2", "projects", "list", "--all"], 2)).toEqual(["--env", "2", "projects", "list", "--all"]);
1320
- expect(cliArgs(["environments", "list"], 2)).toEqual(["environments", "list"]);
1317
+ describe("arcane-cli agent scope", () => {
1318
+ it("names the manager's own host when a call names no agent", () => {
1319
+ expect(withAgent(["--output", "json", "projects", "list", "--all"])).toEqual(["--agent", "0", "--output", "json", "projects", "list", "--all"]);
1320
+ expect(withAgent(["gitops", "list", "--all"], "f1968df8")).toEqual(["--agent", "f1968df8", "gitops", "list", "--all"]);
1321
1321
  });
1322
- it("names the agent on every 3.x call, the manager's own host by default", () => {
1323
- expect(cliArgs(["--output", "json", "projects", "list", "--all"], 3)).toEqual(["--agent", "0", "--output", "json", "projects", "list", "--all"]);
1324
- expect(cliArgs(["--env", "2", "--output", "json", "gitops", "list", "--all"], 3)).toEqual(["--agent", "2", "--output", "json", "gitops", "list", "--all"]);
1325
- expect(cliArgs(["--env=2", "containers", "list"], 3)).toEqual(["--agent=2", "containers", "list"]);
1326
- });
1327
- it("renames the environments command to agents only as the command word", () => {
1328
- expect(cliArgs(["--output", "json", "environments", "version", "2"], 3)).toEqual(["--agent", "0", "--output", "json", "agents", "version", "2"]);
1329
- expect(cliArgs(["projects", "get", "environments"], 3)).toEqual(["--agent", "0", "projects", "get", "environments"]);
1330
- });
1331
- it("reads the major version from arcane-cli --version", () => {
1332
- expect(cliMajorOf("Arcane CLI version: 3.0.1\nGo version: go1.25.4\n")).toBe(3);
1333
- expect(cliMajorOf("arcane-cli version v2.17.3\n")).toBe(2);
1334
- expect(() => cliMajorOf("unknown")).toThrow(/printed no version/);
1322
+ it("keeps the agent a call names", () => {
1323
+ expect(withAgent(["--agent", "2", "containers", "list"])).toEqual(["--agent", "2", "containers", "list"]);
1324
+ expect(withAgent(["--agent=2", "containers", "list"], "0")).toEqual(["--agent=2", "containers", "list"]);
1335
1325
  });
1336
1326
  it("treats --agent as a global flag with a value", () => {
1337
1327
  expect(refusedPrefix(["--agent", "2", "auth", "login"])).toBe("auth");