@phyzess/kitto 0.3.1 → 0.3.2

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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # Kitto
2
2
 
3
+ ## 0.3.2
4
+
5
+ - Locks: the installation lock (`$KITTO_HOME/.lock`) and the Pi adapter's write lock (`<configuration source>/config/pi/local/.sync-lock`) now record their owner — `owner.json` with pid, host, start time and command, or a `pid` file. A refused acquisition therefore reports whether the holder can still exist: `pid N started … is still running`, or `pid N is no longer running` with the statement that the lock is stale. `--break-lock` on `setup`/`update` clears a lock only when its recorded owner is provably gone and never displaces a live operation; a lock without an owner record (an older Kitto, or a hand-made directory) is left for manual inspection. Held locks are released on `SIGINT`/`SIGTERM`, which bash's `EXIT` trap alone never covered for the Pi adapter.
6
+ - Runtime: a failed deployment now says that the refreshed runtime stays unverified (`state.pendingRuntime`) and names both ways forward — rerun `update --apply`, or `setup --recover` to return to the previous runtime.
7
+ - Interpreter probes: `checkPiTools` used an 8s ceiling while the version check rode `run()`'s 600s default, so a version-manager shim (pyenv, asdf, mise) that is slow on its first run aborted the deployment after the runtime swap had already happened. The probe now separates missing, slow and failed: a slow shim warns and continues, while a missing or pre-3.10 interpreter still fails before any write. Docs describe the lock and probe semantics, and tests cover a stale installation and sync lock cleared by `--break-lock`, a live lock that `--break-lock` must refuse, and a stalling `python3` shim that warns instead of stranding the deployment.
8
+
3
9
  ## 0.3.1
4
10
 
5
11
  - Hosts: a selected host CLI below the tested baseline no longer blocks `setup` or `update`. The version check reports a warning and continues, and each native integration is gated on a capability probe instead of a version comparison (`codex plugin`, `dsh plugin`), so a stale Codex or DSH CLI skips only its own registration while rules, skills and MCP still deploy — for that host and for every other selected host. An unreadable `--version` warns instead of throwing; a missing binary stays fatal because no integration can run. `--require-baseline` restores the previous strict gate for release verification, and `installMissingHosts` still verifies the version it installed itself. Docs record that the baseline is an advisory label and the `kitto hosts --apply` target, not a write precondition.
package/bin/kitto.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { existsSync } from 'node:fs';
3
3
  import { mkdir, realpath, rm } from 'node:fs/promises';
4
4
  import { join, resolve } from 'node:path';
5
- import { setup, parseOptions, update } from '../lib/kitto.mjs';
5
+ import { allowStaleLockBreak, setup, parseOptions, update } from '../lib/kitto.mjs';
6
6
  import { worktreeCommand } from '../lib/worktree-audit.mjs';
7
7
  import { hostsCommand } from '../lib/hosts.mjs';
8
8
  import { readScopeRegistry, scopeHome, writeScopeRegistry } from '../lib/scopes.mjs';
@@ -18,6 +18,7 @@ const help = `Kitto — portable personal agent configuration
18
18
  [--dsh-profile PROFILE] [--install-agents] [--dry-run]
19
19
  [--require-baseline]
20
20
  [--include-private|--no-include-private]
21
+ kitto setup --break-lock Continue after a provably abandoned lock (setup/update)
21
22
  kitto setup --recover [--dry-run] Restore the last working Kitto code
22
23
  kitto update [--check|--apply] [--include-private|--no-include-private]
23
24
  Preview (the default; --check makes it explicit) or apply:
@@ -175,6 +176,14 @@ async function scopeCommand(args) {
175
176
 
176
177
  try {
177
178
  const [command, ...args] = process.argv.slice(2);
179
+ // --break-lock is accepted by the commands that take the installation lock.
180
+ // It removes a lock only when the recorded owner is provably gone, so a live
181
+ // operation is never displaced.
182
+ if (['setup', 'update'].includes(command) && args.includes('--break-lock')) {
183
+ allowStaleLockBreak(true);
184
+ args.splice(args.indexOf('--break-lock'), 1);
185
+ console.log('kitto: --break-lock removes a lock only when its recorded owner is no longer running.');
186
+ }
178
187
  if (!command || command === '--help' || command === '-h') console.log(help);
179
188
  else if (command === 'worktree') {
180
189
  if (['start', 'finish', 'apply'].includes(args[0])) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "kitto",
4
- "version": "0.3.1",
4
+ "version": "0.3.2",
5
5
  "description": "Maintain personal agent configuration on request"
6
6
  }
package/lib/kitto.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
3
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
4
4
  import { cp, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile, lstat, readlink, realpath } from 'node:fs/promises';
5
- import { homedir, tmpdir } from 'node:os';
5
+ import { homedir, hostname, tmpdir } from 'node:os';
6
6
  import { basename, dirname, join, resolve } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { applyInstructions, hostSkillRoots, instructionPlan } from './host-config.mjs';
@@ -97,14 +97,98 @@ async function atomicJson(path, value) {
97
97
  } finally { await rm(temporary, { force: true }); }
98
98
  }
99
99
 
100
- async function locked(home, callback) {
100
+ // A lock that only says "somebody is here" forces the operator to guess whether
101
+ // the holder is alive. Every lock records its owner, so a failed acquisition
102
+ // reports a fact instead of asking for an inspection: pid 4812 is running, or
103
+ // pid 4812 exited hours ago and this is residue.
104
+ let breakStaleLocks = false;
105
+ export function allowStaleLockBreak(value = true) { breakStaleLocks = value; }
106
+
107
+ const ownedLocks = new Set();
108
+ let lockSignalsBound = false;
109
+
110
+ function lockOwnerRecord() {
111
+ return { pid: process.pid, host: hostname(), startedAt: new Date().toISOString(),
112
+ command: process.argv.slice(2).join(' ').slice(0, 200) };
113
+ }
114
+
115
+ // EPERM means the pid exists but belongs to another user: still alive.
116
+ function processAlive(pid) {
117
+ if (!Number.isInteger(pid) || pid <= 0) return undefined;
118
+ try { process.kill(pid, 0); return true; }
119
+ catch (error) { return error.code === 'EPERM'; }
120
+ }
121
+
122
+ async function readLockOwner(lock) {
123
+ try { return JSON.parse(await readFile(join(lock, 'owner.json'), 'utf8')); }
124
+ catch { return undefined; }
125
+ }
126
+
127
+ function lockMessage(lock, owner, stale) {
128
+ if (!owner) {
129
+ return `${lock} exists without an owner record (an older Kitto, or a directory someone created by hand). `
130
+ + 'Verify no Kitto process is running, then delete that directory.';
131
+ }
132
+ const who = `pid ${owner.pid}${owner.startedAt ? ` started ${owner.startedAt}` : ''}${owner.command ? ` (${owner.command})` : ''}`;
133
+ return stale
134
+ ? `${lock} is a stale lock: ${who} is no longer running. Rerun with --break-lock to remove it, or delete that directory.`
135
+ : `Another Kitto operation holds ${lock}: ${who}. Wait for it to finish.`;
136
+ }
137
+
138
+ function bindLockSignals() {
139
+ if (lockSignalsBound) return;
140
+ lockSignalsBound = true;
141
+ for (const [signal, code] of [['SIGINT', 130], ['SIGTERM', 143]]) {
142
+ process.once(signal, () => {
143
+ for (const lock of ownedLocks) { try { rmSync(lock, { recursive: true, force: true }); } catch { /* best effort */ } }
144
+ process.exit(code);
145
+ });
146
+ }
147
+ }
148
+
149
+ async function acquireLock(home) {
101
150
  await mkdir(home, { recursive: true });
102
151
  const lock = join(home, '.lock');
103
- try { await mkdir(lock); } catch (e) {
104
- if (e.code === 'EEXIST') throw new Error(`Another Kitto operation holds ${lock}. Remove it only after verifying that process has stopped.`);
105
- throw e;
152
+ bindLockSignals();
153
+ for (let attempt = 0; attempt < 2; attempt++) {
154
+ try {
155
+ await mkdir(lock);
156
+ await writeFile(join(lock, 'owner.json'), JSON.stringify(lockOwnerRecord(), null, 1) + '\n', { mode: 0o600 });
157
+ ownedLocks.add(lock);
158
+ return lock;
159
+ } catch (error) {
160
+ if (error.code !== 'EEXIST') throw error;
161
+ const owner = await readLockOwner(lock);
162
+ const stale = owner ? processAlive(owner.pid) === false : false;
163
+ if (stale && breakStaleLocks) {
164
+ await rm(lock, { recursive: true, force: true });
165
+ console.log(`kitto: removed stale lock ${lock} (pid ${owner.pid} is no longer running).`);
166
+ continue;
167
+ }
168
+ throw new Error(lockMessage(lock, owner, stale));
169
+ }
170
+ }
171
+ throw new Error(`Cannot acquire ${join(home, '.lock')}: a stale lock reappeared after it was cleared.`);
172
+ }
173
+
174
+ // The Pi adapter takes its own lock beside the configuration checkout. A killed
175
+ // sync leaves it behind, and the recorded pid is what makes it actionable.
176
+ function breakStaleSyncLock(state) {
177
+ const lock = join(state.source, 'config/pi/local/.sync-lock');
178
+ if (!existsSync(lock)) return;
179
+ let pid = NaN;
180
+ try { pid = Number(readFileSync(join(lock, 'pid'), 'utf8').trim()); } catch { /* older lock without a pid */ }
181
+ if (processAlive(pid) !== false) return;
182
+ rmSync(lock, { recursive: true, force: true });
183
+ console.log(`kitto: removed stale sync lock ${lock} (pid ${pid} is no longer running).`);
184
+ }
185
+
186
+ async function locked(home, callback) {
187
+ const lock = await acquireLock(home);
188
+ try { return await callback(); } finally {
189
+ ownedLocks.delete(lock);
190
+ await rm(lock, { recursive: true, force: true });
106
191
  }
107
- try { return await callback(); } finally { await rm(lock, { recursive: true }); }
108
192
  }
109
193
 
110
194
  async function validateSource({ source, agents }) {
@@ -368,12 +452,37 @@ async function skillPlan(root, destination, owned = {}, keepExisting = false, ke
368
452
  return plans;
369
453
  }
370
454
 
455
+ function probeTool(name, args = ['--version'], timeout = 8000) {
456
+ const result = spawnSync(name, args, { stdio: 'ignore', timeout });
457
+ if (result.error?.code === 'ENOENT') return 'missing';
458
+ if (result.error?.code === 'ETIMEDOUT') return 'slow';
459
+ if (result.error) return 'failed';
460
+ return result.status === 0 ? 'ok' : 'failed';
461
+ }
462
+
463
+ function slowPythonNotice() {
464
+ console.warn('kitto: python3 did not answer within 8s; continuing. A version-manager shim (pyenv, asdf, mise) can be slow on its '
465
+ + 'first run, and the sync step reports the real result.');
466
+ }
467
+
468
+ // Python is required by the Pi adapter, but the interpreter may be a version
469
+ // manager shim that is far slower than the interpreter it resolves. Only a
470
+ // missing or too-old interpreter stops the run before any write; a probe that
471
+ // times out warns, so a slow shim cannot strand a deployment that otherwise
472
+ // finished. sync.sh still fails loudly when Python is genuinely unusable.
371
473
  function checkPiTools() {
372
- for (const name of ['bash', 'python3']) if (!available(name)) throw new Error(`Pi configuration requires ${name}.`);
373
- run('python3', ['-c', 'import sys; assert sys.version_info >= (3,10), "Python >=3.10 required for Pi"'], { capture: true });
474
+ if (probeTool('bash') === 'missing') throw new Error('Pi configuration requires bash on PATH.');
475
+ const present = probeTool('python3');
476
+ if (present === 'missing') throw new Error('Pi configuration requires python3 on PATH.');
477
+ if (present === 'failed') throw new Error('python3 is on PATH but cannot run; the Pi adapter needs Python >=3.10.');
478
+ if (present === 'slow') return slowPythonNotice();
479
+ const supported = probeTool('python3', ['-c', 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 3)']);
480
+ if (supported === 'slow') return slowPythonNotice();
481
+ if (supported !== 'ok') throw new Error('The Pi adapter needs Python >=3.10; upgrade the python3 on PATH.');
374
482
  }
375
483
 
376
484
  function syncCommand(state, command, apply = false, codeRoot = join(kittoHome(), 'runtime')) {
485
+ if (breakStaleLocks) breakStaleSyncLock(state);
377
486
  checkPiTools();
378
487
  return run('bash', [join(codeRoot, 'sync.sh'), command, ...(!apply && command !== 'status' ? ['--dry-run'] : [])], {
379
488
  env: { ...process.env, KITTO_CONFIG_ROOT: state.source, KITTO_SHARED_SKILLS_MANAGED: '1',
@@ -801,7 +910,15 @@ export async function update(args = []) {
801
910
  const pending = await refreshRuntime(state, true);
802
911
  // The process keeps the code it started with for this deployment; the next
803
912
  // Kitto call (and each restarted host) uses the replaced runtime.
804
- await deploy(state, true, plan, packageRoot);
913
+ try {
914
+ await deploy(state, true, plan, packageRoot);
915
+ } catch (error) {
916
+ // The runtime swap already happened on disk but is not verified yet; say
917
+ // so, because otherwise only state.json reveals why recover matters.
918
+ if (pending) console.error(`kitto: runtime ${pending.version} stays unverified because the deployment did not finish. `
919
+ + 'Rerun `kitto update --apply` to finish, or `kitto setup --recover` to return to the previous runtime.');
920
+ throw error;
921
+ }
805
922
  await finalizeRuntime(state, pending);
806
923
  console.log(`Kitto update complete: runtime ${state.version}, configuration ${sourceRevision(state.source).commit.slice(0, 7)}. Restart native hosts to load new plugin code.`);
807
924
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phyzess/kitto",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Portable personal configuration for Pi, Codex and DeepSeek Harness",
5
5
  "type": "module",
6
6
  "bin": { "kitto": "bin/kitto.mjs" },
package/sync.sh CHANGED
@@ -77,16 +77,33 @@ TMP="$(mktemp -d)"
77
77
  LOCK=""
78
78
  cleanup() {
79
79
  rm -rf "$TMP"
80
- [ -z "$LOCK" ] || rmdir "$LOCK"
80
+ [ -z "$LOCK" ] || rm -rf "$LOCK"
81
81
  }
82
82
  trap cleanup EXIT
83
+ # bash does not run the EXIT trap on SIGTERM/SIGKILL, and a killed sync would
84
+ # leave the write lock behind for the next run to trip over.
85
+ trap 'cleanup; exit 130' INT
86
+ trap 'cleanup; exit 143' TERM
83
87
  if [ "$DRY" = 0 ] && [[ "$CMD" =~ ^(pull|push|deps)$ ]]; then
84
88
  mkdir -p "$LOCAL"
85
89
  if ! mkdir "$LOCAL/.sync-lock" 2>/dev/null; then
86
- fail "另一个同步操作正在运行;若进程已退出,请检查后移除 $LOCAL/.sync-lock"
90
+ # Report whether the recorded holder can still be running instead of
91
+ # asking the operator to inspect the directory by hand.
92
+ holder=""
93
+ if [ -f "$LOCAL/.sync-lock/pid" ]; then
94
+ holder="$(cat "$LOCAL/.sync-lock/pid" 2>/dev/null)"
95
+ fi
96
+ if [ -n "$holder" ] && kill -0 "$holder" 2>/dev/null; then
97
+ fail "另一个同步操作仍在运行(pid $holder)。等它结束后重试。"
98
+ elif [ -n "$holder" ]; then
99
+ fail "残留的同步锁:pid $holder 已退出。重跑命令并加 --break-lock 自动清理,或 rm -rf $LOCAL/.sync-lock"
100
+ else
101
+ fail "$LOCAL/.sync-lock 存在但没有 pid 记录(旧版 Kitto 留下的)。确认没有进程在写后 rm -rf $LOCAL/.sync-lock"
102
+ fi
87
103
  exit 1
88
104
  fi
89
105
  LOCK="$LOCAL/.sync-lock"
106
+ printf '%s\n' "$$" > "$LOCK/pid"
90
107
  fi
91
108
 
92
109
  run() {