shadok-ai 0.17.65 → 0.17.66

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/dist/server.js CHANGED
@@ -44,7 +44,8 @@ import { openBrowser } from "./open-browser.js";
44
44
  import { parseSkillMeta, prepromptParts, prepromptFingerprint, stalenessReasons, LEGACY_FINGERPRINT, } from "./preprompt.js";
45
45
  import { ensureSpawnHelperExecutable } from "./node-pty-fix.js";
46
46
  import { TmuxPilot, tmuxAvailable, tmuxHasSession, tmuxKillSession, tmuxPaneCwd } from "./tmux.js";
47
- import { scanUsage, sessionFilePath, tailSession, clearTailPos, seedTailPos, isNothingToShow } from "./tail.js";
47
+ import { scanUsage, sessionFilePath, tailSession, clearTailPos, seedTailPos, isNothingToShow, newestTranscriptById } from "./tail.js";
48
+ import { strandedWorktreePlan } from "./worktree-relocate.js";
48
49
  import { detectFork, rootIdOfFile } from "./forktrace.js";
49
50
  import { computePace, paceBlock, WINDOW_SEC } from "./pace.js";
50
51
  import { getUsage } from "./usage.js";
@@ -3161,6 +3162,17 @@ function osUserExistsSync(u) {
3161
3162
  return false;
3162
3163
  }
3163
3164
  }
3165
+ /** Synchronous uid of an OS user, or null if it does not exist. */
3166
+ function uidOf(user) {
3167
+ try {
3168
+ const out = execFileSync("id", ["-u", user], { encoding: "utf8", timeout: 5000 }).trim();
3169
+ const n = Number(out);
3170
+ return Number.isInteger(n) ? n : null;
3171
+ }
3172
+ catch {
3173
+ return null;
3174
+ }
3175
+ }
3164
3176
  /** Already migrated iff the marker is present AND `main` exists (the latter is
3165
3177
  * what a docker recreate loses, re-triggering the idempotent provisioning). */
3166
3178
  function alreadyMigratedNow() {
@@ -3265,6 +3277,14 @@ async function ensureGroupsProvisioned() {
3265
3277
  // Then take back the ownership of the server's OWN credentials, which the
3266
3278
  // commons chown swept (see below) — the SSH identity first of all.
3267
3279
  await healServerOwnedState();
3280
+ // Finally finish an INTERRUPTED migration. First complete the commons-repo
3281
+ // chown if it was left half-done (so a relocated worktree's agent can actually
3282
+ // commit), then relocate any worktree still stranded under the server tree
3283
+ // (unreachable by its drop user → "stuck on root") — the one-time migration
3284
+ // would have done both, but the marker now blocks it from re-running.
3285
+ // Idempotent and fail-safe.
3286
+ await reassertCommonsRepoOwnership();
3287
+ await healStrandedWorktrees();
3268
3288
  }
3269
3289
  /**
3270
3290
  * Boot self-heal for the commons agent's OWN helper scripts and cron guards after
@@ -3426,6 +3446,157 @@ async function healServerOwnedState() {
3426
3446
  }
3427
3447
  }
3428
3448
  }
3449
+ /**
3450
+ * Boot self-heal: complete the migration's `chown` of the commons repo (the
3451
+ * launch dir) when it was left half-done. The migration chowns `process.cwd()`
3452
+ * to `main` as a CORE step; an INTERRUPTED run (or a marker written by an older
3453
+ * build before this was a step) can leave the launch repo `root:root`, so a
3454
+ * commons (`main`) agent hits git's "dubious ownership" and cannot write `.git`
3455
+ * — in particular the shared object store, so it can read but never COMMIT. One
3456
+ * cheap `stat` gates the fix (already `main`-owned → no-op); best-effort.
3457
+ */
3458
+ async function reassertCommonsRepoOwnership() {
3459
+ if (DEPLOYMENT_MODE !== "multi-tenant" || !groupsMigrated)
3460
+ return;
3461
+ const user = commonsOsUser({ migrated: groupsMigrated, mode: DEPLOYMENT_MODE });
3462
+ if (!user)
3463
+ return;
3464
+ const repo = path.resolve(process.cwd());
3465
+ try {
3466
+ const uid = uidOf(user);
3467
+ if (uid != null && fs.statSync(repo).uid === uid)
3468
+ return; // already owned → no-op
3469
+ await runPrivileged("chown", ["-R", `${user}:${user}`, repo], { timeoutMs: TREE_OP_TIMEOUT_MS });
3470
+ console.log(`heal: launch repo ${repo} re-owned to ${user} — completed a partial migration chown`);
3471
+ }
3472
+ catch (e) {
3473
+ console.error(`heal: re-owning the launch repo failed (best-effort): ${e?.message ?? e}`);
3474
+ }
3475
+ }
3476
+ /**
3477
+ * Boot self-heal, twin of `healCommonsStrandedScripts`, for the gap it leaves:
3478
+ * a WORKTREE stranded under the server tree after an INTERRUPTED migration. The
3479
+ * root→non-root migration relocates each agent's worktree into the drop user's
3480
+ * own home and respawns it there; interrupted (a container restart mid-run), it
3481
+ * leaves some worktrees under `/root/.shadok-ai/worktrees/…`, which the drop
3482
+ * user cannot even traverse (`/root` is 0700). That agent is then "stuck on
3483
+ * root", and the marker is already written so the one-time migration will not
3484
+ * re-run to finish it. This finishes it, idempotently, on every capable boot.
3485
+ *
3486
+ * Fail-safe by construction: the checkout is COPIED first and the source removed
3487
+ * only once the canonical copy is wired up, so a failure at any step leaves the
3488
+ * agent exactly as it was (working, as root) — never half-moved, never lost. Each
3489
+ * agent is independent and best-effort; a throw is logged, never fatal.
3490
+ */
3491
+ async function healStrandedWorktrees() {
3492
+ if (DEPLOYMENT_MODE !== "multi-tenant" || !groupsMigrated)
3493
+ return;
3494
+ const groups = loadGroups();
3495
+ const commons = commonsOsUser({ migrated: groupsMigrated, mode: DEPLOYMENT_MODE });
3496
+ const launchDir = path.resolve(process.cwd());
3497
+ const plan = strandedWorktreePlan(loadChannels(), {
3498
+ dropUserFor: (gid) => {
3499
+ const g = gid ? groups.find((x) => x.id === gid) : undefined;
3500
+ return (g ? osUserFor(g) : null) ?? commons;
3501
+ },
3502
+ stateHomeFor: (u) => agentStateHome(u),
3503
+ // Reachable := the drop user can enter the checkout AND write it. A working,
3504
+ // already-migrated agent answers true and is left untouched; only a truly
3505
+ // unreachable (stranded) worktree is relocated. The cwd is passed as an
3506
+ // argv parameter (`$1`), never interpolated into the script.
3507
+ canReach: (user, cwd) => spawnAsUserSync(user, "bash", ["-c", 'cd "$1" && test -w .', "_", cwd]).ok,
3508
+ // A worktree, not the launch dir (which has no worktree to move): a checkout
3509
+ // carrying a `.git` FILE, or sitting under a `.shadok-ai/worktrees` base.
3510
+ isWorktreeCwd: (cwd) => path.resolve(cwd) !== launchDir &&
3511
+ (fs.existsSync(path.join(cwd, ".git")) ||
3512
+ cwd.includes(`${path.sep}.shadok-ai${path.sep}worktrees${path.sep}`)),
3513
+ });
3514
+ if (!plan.length)
3515
+ return;
3516
+ console.log(`heal: ${plan.length} stranded worktree(s) to relocate off the server tree`);
3517
+ for (const r of plan) {
3518
+ try {
3519
+ await relocateStrandedWorktree(r);
3520
+ }
3521
+ catch (e) {
3522
+ console.error(`heal: relocating worktree ${r.sessionId.slice(0, 8)} failed (best-effort, agent left as-is): ${e?.message ?? e}`);
3523
+ }
3524
+ }
3525
+ }
3526
+ /** Relocate ONE stranded worktree to its canonical home under the drop user, then
3527
+ * carry the transcript, repoint the channel and drop the stale source. Order is
3528
+ * load-bearing: COPY before any delete, so a failure never loses work. */
3529
+ async function relocateStrandedWorktree(r) {
3530
+ const name = "sk-" + r.sessionId;
3531
+ const owner = `${r.user}:${r.user}`;
3532
+ // 1. Stop the stale pane and drop the live entry, so nothing holds the old
3533
+ // checkout while we move it and a resume rebuilds the session at the NEW cwd.
3534
+ if (tmuxHasSession(name)) {
3535
+ tmuxKillSession(name);
3536
+ for (let i = 0; i < 30 && tmuxHasSession(name); i++)
3537
+ await sleep(100);
3538
+ }
3539
+ const live = sessions.get(r.sessionId);
3540
+ if (live) {
3541
+ try {
3542
+ live.pilot.kill();
3543
+ }
3544
+ catch {
3545
+ /* already gone */
3546
+ }
3547
+ sessions.delete(r.sessionId);
3548
+ }
3549
+ // 2. Copy the checkout to its canonical home (never move: the source stays
3550
+ // intact until everything below is wired). `cp -an` merges a partial prior
3551
+ // run without clobbering, so a re-run is safe.
3552
+ await runPrivileged("install", ["-d", "-o", r.user, "-g", r.user, path.dirname(r.to)], {
3553
+ timeoutMs: TREE_OP_TIMEOUT_MS,
3554
+ });
3555
+ await runPrivileged("install", ["-d", "-o", r.user, "-g", r.user, r.to], { timeoutMs: TREE_OP_TIMEOUT_MS });
3556
+ await runPrivileged("cp", ["-an", `${r.from}/.`, `${r.to}/`], { timeoutMs: TREE_OP_TIMEOUT_MS });
3557
+ // 3. Repair git's worktree admin link to point at the NEW checkout (the repo
3558
+ // did not move, only the checkout), then hand the checkout AND git's admin
3559
+ // dir to the drop user (`chownAgentStateToDropUser` follows the `.git` file
3560
+ // to the external admin dir).
3561
+ try {
3562
+ await runPrivileged("git", ["-C", r.to, "worktree", "repair"]);
3563
+ }
3564
+ catch (e) {
3565
+ console.error(`heal: git worktree repair ${r.sessionId.slice(0, 8)} (best-effort): ${e?.message ?? e}`);
3566
+ }
3567
+ await chownAgentStateToDropUser(r.to, r.user);
3568
+ // 4. Carry the transcript into the drop user's home (best-effort): the work is
3569
+ // already safe in the worktree, this only keeps the chat history visible on
3570
+ // reload. `loadHistory` finds a `<id>.jsonl` anywhere under the home.
3571
+ try {
3572
+ const src = newestTranscriptById(r.sessionId, os.homedir());
3573
+ if (src && fs.existsSync(src)) {
3574
+ const dstDir = path.join(agentStateHome(r.user), ".claude", "projects", path.basename(path.dirname(src)));
3575
+ await runPrivileged("install", ["-d", "-o", r.user, "-g", r.user, dstDir]);
3576
+ const dst = path.join(dstDir, path.basename(src));
3577
+ await runPrivileged("cp", ["-n", src, dst]);
3578
+ await runPrivileged("chown", [owner, dst]);
3579
+ }
3580
+ }
3581
+ catch (e) {
3582
+ console.error(`heal: transcript carry ${r.sessionId.slice(0, 8)} (best-effort): ${e?.message ?? e}`);
3583
+ }
3584
+ // 5. Repoint the channel to the new cwd (ASSERT only cwd, invariant 1) BEFORE
3585
+ // removing the source, so a crash here leaves the still-present source usable.
3586
+ upsertChannel({ sessionId: r.sessionId, cwd: r.to });
3587
+ // 6. Everything is wired at the canonical home — drop the stale source copy and
3588
+ // prune the repo's now-dangling worktree registration.
3589
+ await runPrivileged("rm", ["-rf", r.from], { timeoutMs: TREE_OP_TIMEOUT_MS });
3590
+ if (r.repo) {
3591
+ try {
3592
+ await runPrivileged("git", ["-C", r.repo, "worktree", "prune"]);
3593
+ }
3594
+ catch {
3595
+ /* best-effort tidy-up */
3596
+ }
3597
+ }
3598
+ console.log(`heal: relocated worktree ${r.sessionId.slice(0, 8)} → ${r.to} (resumes as ${r.user})`);
3599
+ }
3429
3600
  /** Step 1 — create the non-root commons user `main` (+ HOME). Idempotent. */
3430
3601
  async function migCreateCommonsUser() {
3431
3602
  if (osUserExistsSync(COMMONS_USER))