threadnote 0.6.3 → 0.7.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.
@@ -3523,8 +3523,8 @@ var DEFAULT_SEED_PATTERNS = [
3523
3523
  ];
3524
3524
 
3525
3525
  // src/hooks.ts
3526
- var import_promises6 = require("node:fs/promises");
3527
- var import_node_path7 = require("node:path");
3526
+ var import_promises7 = require("node:fs/promises");
3527
+ var import_node_path8 = require("node:path");
3528
3528
 
3529
3529
  // src/mcp.ts
3530
3530
  var import_node_fs2 = require("node:fs");
@@ -4487,8 +4487,8 @@ function existsSyncDirectory(path) {
4487
4487
  }
4488
4488
 
4489
4489
  // src/memory.ts
4490
- var import_promises4 = require("node:fs/promises");
4491
- var import_node_path4 = require("node:path");
4490
+ var import_promises5 = require("node:fs/promises");
4491
+ var import_node_path5 = require("node:path");
4492
4492
 
4493
4493
  // src/manifest.ts
4494
4494
  var import_promises3 = require("node:fs/promises");
@@ -7230,2460 +7230,2698 @@ function renderTemplate(template, config) {
7230
7230
  return template.replaceAll("{{THREADNOTE_HOME}}", config.agentContextHome).replaceAll("{{OPENVIKING_ACCOUNT}}", config.account).replaceAll("{{OPENVIKING_AGENT_ID}}", config.agentId).replaceAll("{{OPENVIKING_HOST}}", config.host).replaceAll("{{OPENVIKING_PORT}}", String(config.port)).replaceAll("{{OPENVIKING_USER}}", config.user);
7231
7231
  }
7232
7232
 
7233
- // src/memory.ts
7234
- function parseMemoryKind(value) {
7235
- if (["durable", "handoff", "incident", "preference", "smoke"].includes(value)) {
7236
- return value;
7233
+ // src/share.ts
7234
+ var import_promises4 = require("node:fs/promises");
7235
+ var import_node_os4 = require("node:os");
7236
+ var import_node_path4 = require("node:path");
7237
+ var TEAMS_FILE_VERSION = 1;
7238
+ var SHARED_SEGMENT = "shared";
7239
+ var SHAREABLE_MEMORY_KIND_DIRS = ["durable"];
7240
+ var AUTO_SHARE_FETCH_INTERVAL_MS = 5 * 60 * 1e3;
7241
+ var DEFAULT_GIT_REMOTE_NAME = "origin";
7242
+ var SCRUBBER_PATTERNS = [
7243
+ // Credentials: never redactable. Blocking is the only safe response —
7244
+ // automated redaction risks false negatives that leave material in git.
7245
+ { name: "private key", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
7246
+ { name: "API key (sk-...)", regex: /\bsk-[A-Za-z0-9_-]{16,}/ },
7247
+ { name: "GitHub token", regex: /\bgh[pousr]_[A-Za-z0-9_]{16,}/ },
7248
+ { name: "GitHub fine-grained PAT", regex: /\bgithub_pat_[A-Za-z0-9_]{20,}/ },
7249
+ { name: "GitLab PAT", regex: /\bglpat-[A-Za-z0-9_-]{20,}/ },
7250
+ { name: "bearer token", regex: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/i },
7251
+ // Matches bare JWTs (three base64url segments). May surface a JWE token in
7252
+ // legitimate docs; if that becomes noisy we can switch to warn-only.
7253
+ { name: "JWT", regex: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
7254
+ { name: "AWS access key", regex: /\bAKIA[0-9A-Z]{16}\b/ },
7255
+ // Slack tokens: xoxa/xoxb/xoxc (configuration)/xoxd (legacy user cookie)/
7256
+ // xoxe (refresh)/xoxp/xoxr/xoxs, with optional -N- segment for the workspace tier.
7257
+ { name: "Slack token", regex: /\bxox[abcdeprs](?:-\d-)?[A-Za-z0-9._-]{10,}/i },
7258
+ // Soft leaks: block by default (so the agent sees them and decides), but
7259
+ // allow opt-in redaction so curated memories with incidental matches can
7260
+ // ship without a manual rewrite. Local home paths are the recurring
7261
+ // real-world leak; the regexes greedily consume the whole path segment
7262
+ // (including subdirectories) up to whitespace or common closing punctuation
7263
+ // so redaction collapses an entire path to a single placeholder rather than
7264
+ // leaving the subpath visible.
7265
+ { name: "macOS home path", placeholder: "<local-path>", regex: /\/Users\/[^\s)>"'`,]+/ },
7266
+ { name: "linux home path", placeholder: "<local-path>", regex: /\b\/home\/[^\s)>"'`,]+/ }
7267
+ ];
7268
+ function applyScrubber(content, { redact }) {
7269
+ let cleaned = content;
7270
+ const redactions = [];
7271
+ for (const pattern of SCRUBBER_PATTERNS) {
7272
+ if (!pattern.regex.test(cleaned)) {
7273
+ continue;
7274
+ }
7275
+ if (!pattern.placeholder || !redact) {
7276
+ return { blocker: pattern.name, cleaned: content, redactions: [] };
7277
+ }
7278
+ const flags = pattern.regex.flags.includes("g") ? pattern.regex.flags : `${pattern.regex.flags}g`;
7279
+ const globalRegex = new RegExp(pattern.regex.source, flags);
7280
+ const matches = cleaned.match(globalRegex) ?? [];
7281
+ cleaned = cleaned.replace(globalRegex, pattern.placeholder);
7282
+ redactions.push({ count: matches.length, name: pattern.name });
7237
7283
  }
7238
- throw new Error(`Unsupported memory kind "${value}". Expected durable, handoff, incident, preference, or smoke.`);
7284
+ return { cleaned, redactions };
7239
7285
  }
7240
- function parseMemoryStatus(value) {
7241
- if (["active", "archived", "superseded"].includes(value)) {
7242
- return value;
7286
+ var autoShareStates = /* @__PURE__ */ new Map();
7287
+ async function runShareInit(config, remoteUrl, options) {
7288
+ if (!remoteUrl.trim()) {
7289
+ throw new Error("Provide a git remote URL for the shared memories repo.");
7243
7290
  }
7244
- throw new Error(`Unsupported memory status "${value}". Expected active, archived, or superseded.`);
7245
- }
7246
- async function runRemember(config, options) {
7247
- const text = await getInputText(options.text, options.stdin === true);
7248
- if (!text.trim()) {
7249
- throw new Error("Provide memory text with --text or --stdin.");
7291
+ const dryRun = options.dryRun === true;
7292
+ const teamName = normalizeTeamName(options.team);
7293
+ const teamsFile = await readTeamsFile(config);
7294
+ if (teamsFile.teams[teamName]) {
7295
+ throw new Error(
7296
+ `Team "${teamName}" is already configured (remote ${teamsFile.teams[teamName].remote}). Remove it first with: threadnote share remove --team ${teamName}`
7297
+ );
7250
7298
  }
7251
- const metadata = {
7252
- kind: options.kind ?? "durable",
7253
- project: normalizeOptionalMetadata(options.project),
7254
- sourceAgentClient: options.sourceAgentClient ?? "codex",
7255
- status: options.status ?? "active",
7256
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7257
- topic: normalizeOptionalMetadata(options.topic)
7299
+ const worktree = teamWorktreePath(config, teamName);
7300
+ const gitdir = teamGitdirPath(config, teamName);
7301
+ await assertWorktreeUsable(worktree);
7302
+ if (await exists(gitdir)) {
7303
+ throw new Error(`Gitdir already exists at ${gitdir}; remove it or pick a different team name.`);
7304
+ }
7305
+ await ensureDirectory((0, import_node_path4.dirname)(worktree), dryRun);
7306
+ await ensureDirectory((0, import_node_path4.dirname)(gitdir), dryRun);
7307
+ const git = await requiredExecutable("git");
7308
+ await maybeRun(dryRun, git, ["clone", `--separate-git-dir=${gitdir}`, "--", remoteUrl, worktree]);
7309
+ const newConfig = {
7310
+ addedAt: (/* @__PURE__ */ new Date()).toISOString(),
7311
+ gitdir,
7312
+ name: teamName,
7313
+ remote: remoteUrl,
7314
+ worktree
7258
7315
  };
7259
- await storeMemory(config, {
7260
- bodyText: text.trim(),
7261
- dryRun: options.dryRun === true,
7262
- metadata,
7263
- replaceUri: options.replace,
7264
- title: "MEMORY"
7265
- });
7316
+ const updatedTeams = {
7317
+ defaultTeam: shouldSetDefault(options, teamsFile) ? teamName : teamsFile.defaultTeam ?? teamName,
7318
+ teams: { ...teamsFile.teams, [teamName]: newConfig },
7319
+ version: TEAMS_FILE_VERSION
7320
+ };
7321
+ if (dryRun) {
7322
+ console.log(`Would write teams file: ${teamsFilePath(config)}`);
7323
+ console.log(`Would set ${teamName} as default? ${updatedTeams.defaultTeam === teamName}`);
7324
+ } else {
7325
+ await writeTeamsFile(config, updatedTeams);
7326
+ console.log(`Configured shared team "${teamName}" -> ${portablePath(worktree)}`);
7327
+ }
7328
+ if (!dryRun) {
7329
+ await ensureSharedGitignore(worktree, git, options.push !== false);
7330
+ const ingested = await ingestWorktreeFiles(config, newConfig, "create");
7331
+ console.log(`Ingested ${ingested} shared memory file(s) into OpenViking.`);
7332
+ }
7266
7333
  }
7267
- async function runMigrateMemories(config, options) {
7268
- const dryRun = options.dryRun === true;
7269
- const limit = options.limit ? parsePositiveInteger(options.limit, "migration limit") : void 0;
7270
- const sourceAccounts = await legacySourceAccounts(config, options);
7271
- if (sourceAccounts.length === 0) {
7272
- console.log("No local OpenViking accounts found to scan.");
7334
+ var SHARED_GITIGNORE_PATTERNS = ["**/.abstract.md", "**/.overview.md"];
7335
+ var SHARED_GITIGNORE_HEADER = "# Threadnote: ignore OpenViking-generated directory summaries.";
7336
+ async function ensureSharedGitignore(worktree, git, push) {
7337
+ const gitignorePath = (0, import_node_path4.join)(worktree, ".gitignore");
7338
+ const existing = await readFileIfExists(gitignorePath) ?? "";
7339
+ const lines = existing.split("\n").map((line) => line.trim());
7340
+ const missingPatterns = SHARED_GITIGNORE_PATTERNS.filter((pattern) => !lines.includes(pattern));
7341
+ if (missingPatterns.length === 0) {
7273
7342
  return;
7274
7343
  }
7275
- const candidates = await legacyMemoryCandidates(config, sourceAccounts);
7276
- const existingHashes = await existingDurableMemoryHashes(config);
7277
- const ov = await openVikingCliForMode(dryRun);
7278
- const migrationPath = (0, import_node_path4.join)(config.agentContextHome, "legacy-memory-migration.txt");
7279
- let duplicateCount = 0;
7280
- let migratedCount = 0;
7281
- let sensitiveCount = 0;
7282
- if (!dryRun && candidates.length > 0) {
7283
- await ensureDurableMemoryDirectory(ov, config);
7344
+ const hasHeader = lines.includes(SHARED_GITIGNORE_HEADER);
7345
+ const segments = [];
7346
+ if (existing.length > 0 && !existing.endsWith("\n")) {
7347
+ segments.push("\n");
7284
7348
  }
7285
- try {
7286
- for (const candidate of candidates) {
7287
- if (existingHashes.has(candidate.hash)) {
7288
- duplicateCount += 1;
7289
- continue;
7290
- }
7291
- if (existingHashes.has(candidate.comparableHash)) {
7292
- duplicateCount += 1;
7293
- continue;
7294
- }
7295
- const sensitiveReason = sensitiveMemoryReason(candidate.text);
7296
- if (sensitiveReason) {
7297
- sensitiveCount += 1;
7298
- console.log(
7299
- `SKIP ${legacySourceLabel(candidate)}: possible ${sensitiveReason}; inspect the source archive manually if needed.`
7349
+ if (existing.length > 0) {
7350
+ segments.push("\n");
7351
+ }
7352
+ if (!hasHeader) {
7353
+ segments.push(SHARED_GITIGNORE_HEADER, "\n");
7354
+ }
7355
+ segments.push(missingPatterns.join("\n"), "\n");
7356
+ await (0, import_promises4.writeFile)(gitignorePath, `${existing}${segments.join("")}`, { encoding: "utf8" });
7357
+ console.log(`Added ${missingPatterns.join(", ")} to ${portablePath(gitignorePath)}`);
7358
+ await maybeRun(false, git, ["-C", worktree, "add", ".gitignore"]);
7359
+ const commitResult = await runCommand(
7360
+ git,
7361
+ ["-C", worktree, "commit", "-m", "share: ignore OpenViking directory summaries"],
7362
+ { allowFailure: true }
7363
+ );
7364
+ if (commitResult.exitCode !== 0) {
7365
+ const detail = commitResult.stderr.trim() || commitResult.stdout.trim();
7366
+ if (!/nothing to commit|no changes added/i.test(detail)) {
7367
+ console.warn(
7368
+ `.gitignore housekeeping commit was rejected (${detail || "unknown"}); it will be retried on the next share sync.`
7369
+ );
7370
+ return;
7371
+ }
7372
+ }
7373
+ if (push) {
7374
+ await maybeRun(false, git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
7375
+ }
7376
+ }
7377
+ async function runShareStatus(config, options) {
7378
+ const team = await resolveTeam(config, options.team);
7379
+ const git = await requiredExecutable("git");
7380
+ console.log(`Team: ${team.name}`);
7381
+ console.log(`Remote: ${team.config.remote}`);
7382
+ console.log(`Worktree: ${portablePath(team.config.worktree)}`);
7383
+ console.log(`Gitdir: ${portablePath(team.config.gitdir)}`);
7384
+ await maybeRun(options.dryRun === true, git, ["-C", team.config.worktree, "status", "--short", "--branch"]);
7385
+ await maybeRun(options.dryRun === true, git, ["-C", team.config.worktree, "fetch", DEFAULT_GIT_REMOTE_NAME], {
7386
+ allowFailure: true
7387
+ });
7388
+ const ahead = await gitOutput(team.config.worktree, ["rev-list", "--count", "@{u}..HEAD"], options.dryRun === true);
7389
+ const behind = await gitOutput(team.config.worktree, ["rev-list", "--count", "HEAD..@{u}"], options.dryRun === true);
7390
+ if (ahead !== void 0) {
7391
+ console.log(`Ahead of upstream: ${ahead}`);
7392
+ }
7393
+ if (behind !== void 0) {
7394
+ console.log(`Behind upstream: ${behind}`);
7395
+ }
7396
+ }
7397
+ async function syncSharedReposBeforeAgentRead(config) {
7398
+ const state = autoShareState(config);
7399
+ return enqueueShareOperation(state, async () => {
7400
+ await loadPendingReindexes(config, state);
7401
+ const warnings = await refreshShareUpdateStateLocked(config, state, { force: false });
7402
+ const syncTeams = /* @__PURE__ */ new Set([...state.behindTeams, ...state.pendingReindexes.keys()]);
7403
+ if (syncTeams.size === 0) {
7404
+ return { syncedTeams: [], warnings };
7405
+ }
7406
+ const syncedTeams = [];
7407
+ const remainingBehind = new Set(state.behindTeams);
7408
+ for (const team of syncTeams) {
7409
+ try {
7410
+ const warning = await runShareSyncQuiet(config, state, { team });
7411
+ if (warning) {
7412
+ warnings.push(warning);
7413
+ } else {
7414
+ remainingBehind.delete(team);
7415
+ syncedTeams.push(team);
7416
+ }
7417
+ } catch (err) {
7418
+ warnings.push(
7419
+ `Auto-sync for shared team "${team}" failed: ${err instanceof Error ? err.message : String(err)}`
7300
7420
  );
7301
- continue;
7302
- }
7303
- if (limit !== void 0 && migratedCount >= limit) {
7304
- break;
7305
7421
  }
7306
- const memoryUri = migratedDurableMemoryUri(config, candidate.hash);
7307
- if (!dryRun && await vikingResourceExists(ov, config, memoryUri)) {
7308
- duplicateCount += 1;
7309
- existingHashes.add(candidate.hash);
7422
+ }
7423
+ state.behindTeams = remainingBehind;
7424
+ state.lastCheckedAt = Date.now();
7425
+ return { syncedTeams, warnings };
7426
+ });
7427
+ }
7428
+ function autoShareState(config) {
7429
+ const key = `${config.agentContextHome}:${config.account}:${config.user}`;
7430
+ let state = autoShareStates.get(key);
7431
+ if (!state) {
7432
+ state = { behindTeams: /* @__PURE__ */ new Set(), lastCheckedAt: 0, pendingReindexes: /* @__PURE__ */ new Map() };
7433
+ autoShareStates.set(key, state);
7434
+ }
7435
+ return state;
7436
+ }
7437
+ function pendingReindexesPath(config) {
7438
+ return (0, import_node_path4.join)(config.agentContextHome, "share", "auto-sync-pending-reindexes.json");
7439
+ }
7440
+ async function loadPendingReindexes(config, state) {
7441
+ const raw = await readFileIfExists(pendingReindexesPath(config));
7442
+ if (!raw) {
7443
+ state.pendingReindexes = /* @__PURE__ */ new Map();
7444
+ return;
7445
+ }
7446
+ const parsed = parseJsonConfigObject(raw);
7447
+ if (!parsed || typeof parsed.teams !== "object" || parsed.teams === null || Array.isArray(parsed.teams)) {
7448
+ state.pendingReindexes = /* @__PURE__ */ new Map();
7449
+ return;
7450
+ }
7451
+ const pending = /* @__PURE__ */ new Map();
7452
+ for (const [team, value] of Object.entries(parsed.teams)) {
7453
+ if (!Array.isArray(value)) {
7454
+ continue;
7455
+ }
7456
+ const changes = [];
7457
+ for (const item of value) {
7458
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
7310
7459
  continue;
7311
7460
  }
7312
- console.log(`${dryRun ? "Would migrate" : "Migrating"} ${legacySourceLabel(candidate)} -> ${memoryUri}`);
7313
- if (!dryRun) {
7314
- await (0, import_promises4.writeFile)(migrationPath, candidate.text, { encoding: "utf8", mode: 384 });
7315
- await (0, import_promises4.chmod)(migrationPath, 384);
7316
- await writeDurableMemoryFile(ov, config, memoryUri, migrationPath, "create");
7317
- existingHashes.add(candidate.hash);
7461
+ const entry = item;
7462
+ if (typeof entry.path === "string" && typeof entry.relativePath === "string" && (entry.status === "added" || entry.status === "removed" || entry.status === "modified")) {
7463
+ changes.push({ path: entry.path, relativePath: entry.relativePath, status: entry.status });
7318
7464
  }
7319
- migratedCount += 1;
7320
7465
  }
7321
- } finally {
7322
- if (!dryRun) {
7323
- await (0, import_promises4.rm)(migrationPath, { force: true });
7466
+ if (changes.length > 0) {
7467
+ pending.set(team, changes);
7324
7468
  }
7325
7469
  }
7326
- console.log(
7327
- [
7328
- `Migration summary: ${migratedCount} ${dryRun ? "would be migrated" : "migrated"}`,
7329
- `${duplicateCount} duplicate(s) skipped`,
7330
- `${sensitiveCount} sensitive-looking item(s) skipped`,
7331
- `${candidates.length} legacy Threadnote item(s) scanned`,
7332
- `source account(s): ${sourceAccounts.join(", ")}`
7333
- ].join("; ")
7334
- );
7470
+ state.pendingReindexes = pending;
7335
7471
  }
7336
- async function runMigrateLifecycle(config, options) {
7337
- const dryRun = options.dryRun === true || options.apply !== true;
7338
- const limit = options.limit ? parsePositiveInteger(options.limit, "lifecycle migration limit") : void 0;
7339
- const ov = await openVikingCliForMode(dryRun);
7340
- const candidates = await legacyLifecycleHandoffCandidates(config);
7341
- const migrationPath = (0, import_node_path4.join)(config.agentContextHome, "lifecycle-memory-migration.txt");
7342
- let existingCount = 0;
7343
- let migratedCount = 0;
7344
- let skippedCount = 0;
7472
+ async function writePendingReindexes(config, state) {
7473
+ const path = pendingReindexesPath(config);
7474
+ if (state.pendingReindexes.size === 0) {
7475
+ await (0, import_promises4.rm)(path, { force: true });
7476
+ return;
7477
+ }
7478
+ const contents = {
7479
+ teams: Object.fromEntries(state.pendingReindexes),
7480
+ version: 1
7481
+ };
7482
+ await (0, import_promises4.mkdir)((0, import_node_path4.dirname)(path), { recursive: true });
7483
+ const tempPath = `${path}.${process.pid}.tmp`;
7484
+ await (0, import_promises4.writeFile)(tempPath, `${JSON.stringify(contents, void 0, 2)}
7485
+ `, { encoding: "utf8", mode: 384 });
7486
+ await (0, import_promises4.rename)(tempPath, path);
7487
+ }
7488
+ async function refreshShareUpdateStateLocked(config, state, options) {
7489
+ const now = Date.now();
7490
+ if (!options.force && state.lastCheckedAt > 0 && now - state.lastCheckedAt < AUTO_SHARE_FETCH_INTERVAL_MS) {
7491
+ return [];
7492
+ }
7345
7493
  try {
7346
- for (const candidate of candidates) {
7347
- if (limit !== void 0 && migratedCount >= limit) {
7348
- break;
7494
+ const statuses = await fetchShareUpdateStatuses(config);
7495
+ const nextBehindTeams = new Set(state.behindTeams);
7496
+ for (const status of statuses) {
7497
+ if (status.warning) {
7498
+ continue;
7349
7499
  }
7350
- const destinationUri = lifecycleMigrationUri(config, candidate.metadata, sha256(candidate.original.trim()));
7351
- const migratedMemory = formatMemoryDocument(
7352
- "HANDOFF",
7353
- candidate.metadata,
7354
- ["Migrated legacy handoff from the historical events trail.", "", candidate.original.trim()].join("\n")
7355
- );
7356
- console.log(`${dryRun ? "Would migrate" : "Migrating"} ${candidate.sourceUri} -> ${destinationUri}`);
7357
- if (!dryRun) {
7358
- if (await vikingResourceExists(ov, config, destinationUri)) {
7359
- existingCount += 1;
7360
- console.log(`Archived copy already exists; cleaning up legacy source: ${candidate.sourceUri}`);
7361
- } else {
7362
- await (0, import_promises4.writeFile)(migrationPath, migratedMemory, { encoding: "utf8", mode: 384 });
7363
- await (0, import_promises4.chmod)(migrationPath, 384);
7364
- await ensureMemoryDirectory(ov, config, memoryDirectoryUri(config, candidate.metadata));
7365
- await writeDurableMemoryFile(ov, config, destinationUri, migrationPath, "create");
7366
- }
7367
- const removedOriginal = await removeVikingResourceWithRetry(ov, config, candidate.sourceUri);
7368
- if (!removedOriginal) {
7369
- console.error(
7370
- `Migrated copy stored, but original is still processing. Retry later: threadnote forget ${candidate.sourceUri}`
7371
- );
7372
- skippedCount += 1;
7373
- }
7500
+ if (status.behind > 0) {
7501
+ nextBehindTeams.add(status.team);
7502
+ } else {
7503
+ nextBehindTeams.delete(status.team);
7374
7504
  }
7375
- migratedCount += 1;
7376
7505
  }
7506
+ state.behindTeams = nextBehindTeams;
7507
+ return statuses.flatMap((status) => status.warning ? [status.warning] : []);
7377
7508
  } finally {
7378
- if (!dryRun) {
7379
- await (0, import_promises4.rm)(migrationPath, { force: true });
7380
- }
7509
+ state.lastCheckedAt = Date.now();
7381
7510
  }
7382
- console.log(
7383
- [
7384
- `Lifecycle migration summary: ${migratedCount} clear legacy handoff(s) ${dryRun ? "would be migrated" : "migrated"}`,
7385
- `${existingCount} existing archived copy/copies reused`,
7386
- `${skippedCount} legacy source(s) still processing`,
7387
- `${candidates.length} clear legacy handoff candidate(s) found`,
7388
- dryRun ? "Run with --apply to perform this migration." : void 0
7389
- ].filter((part) => part !== void 0).join("; ")
7390
- );
7391
7511
  }
7392
- async function runRecall(config, options) {
7393
- const ov = await openVikingCliForMode(options.dryRun === true);
7394
- const inferredUri = options.uri ?? (options.inferScope === false ? void 0 : await inferRecallUri(config, options.query));
7395
- const args = ["search", options.query];
7396
- if (inferredUri) {
7397
- args.push("--uri", inferredUri);
7398
- console.log(`Recall scope: ${inferredUri}`);
7399
- }
7400
- if (options.nodeLimit) {
7401
- args.push("--node-limit", String(parsePositiveInteger(options.nodeLimit, "node limit")));
7402
- }
7403
- await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
7404
- await augmentRecallWithSeededResources(config, ov, options, inferredUri);
7405
- await printExactMemoryMatches(config, ov, options.query, {
7406
- dryRun: options.dryRun === true,
7407
- includeArchived: options.includeArchived === true
7408
- });
7512
+ function enqueueShareOperation(state, action) {
7513
+ const previous = state.operationPromise ?? Promise.resolve();
7514
+ const current = previous.catch(() => void 0).then(action);
7515
+ state.operationPromise = current.catch(() => void 0);
7516
+ return current;
7409
7517
  }
7410
- async function augmentRecallWithSeededResources(config, ov, options, inferredUri) {
7411
- if (options.uri || options.inferScope === false) {
7412
- return;
7413
- }
7414
- const project = await inferProjectFromQuery(config.manifestPath, options.query);
7415
- if (!project) {
7416
- return;
7417
- }
7418
- const projectResourceUri = trimTrailingSlash(project.uri);
7419
- if (!projectResourceUri.startsWith("viking://") || projectResourceUri === inferredUri) {
7420
- return;
7518
+ async function fetchShareUpdateStatuses(config) {
7519
+ const teamsFile = await readTeamsFile(config);
7520
+ const teams = Object.entries(teamsFile.teams);
7521
+ if (teams.length === 0) {
7522
+ return [];
7421
7523
  }
7422
- const args = ["search", options.query, "--uri", projectResourceUri];
7423
- if (options.nodeLimit) {
7424
- args.push("--node-limit", String(parsePositiveInteger(options.nodeLimit, "node limit")));
7524
+ const git = await requiredExecutable("git");
7525
+ const statuses = [];
7526
+ for (const [name, team] of teams) {
7527
+ const fetchResult = await runCommand(git, ["-C", team.worktree, "fetch", DEFAULT_GIT_REMOTE_NAME], {
7528
+ allowFailure: true
7529
+ });
7530
+ if (fetchResult.exitCode !== 0) {
7531
+ statuses.push({
7532
+ behind: 0,
7533
+ team: name,
7534
+ warning: `Auto-sync check for shared team "${name}" failed: ${fetchResult.stderr.trim() || fetchResult.stdout.trim() || "unknown git fetch error"}`
7535
+ });
7536
+ continue;
7537
+ }
7538
+ const behind = await gitOutput(team.worktree, ["rev-list", "--count", "HEAD..@{u}"], false);
7539
+ if (behind === void 0) {
7540
+ statuses.push({
7541
+ behind: 0,
7542
+ team: name,
7543
+ warning: `Auto-sync check for shared team "${name}" failed: could not read upstream behind count.`
7544
+ });
7545
+ continue;
7546
+ }
7547
+ statuses.push({ behind: Number.parseInt(behind, 10) || 0, team: name });
7425
7548
  }
7426
- console.log(`
7427
- Also searching seeded resources: ${projectResourceUri}`);
7428
- await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
7549
+ return statuses;
7429
7550
  }
7430
- async function runRead(config, uri, options) {
7431
- assertVikingUri(uri);
7432
- const ov = await openVikingCliForMode(options.dryRun === true);
7433
- const result = await maybeRun(options.dryRun === true, ov, withIdentity(config, ["read", uri]));
7434
- if (result && result.stdout.includes("[Directory overview is not ready]") && (uri.endsWith("/.overview.md") || uri.endsWith("/.abstract.md"))) {
7435
- const parentUri2 = parentVikingUri(uri);
7436
- console.log("\nThis is a generated summary placeholder. To read the underlying content, inspect leaf nodes:");
7437
- console.log(` threadnote list ${parentUri2} --all --recursive`);
7551
+ async function runShareSync(config, options) {
7552
+ const team = await resolveTeam(config, options.team);
7553
+ const dryRun = options.dryRun === true;
7554
+ const git = await requiredExecutable("git");
7555
+ const worktree = team.config.worktree;
7556
+ if (!dryRun) {
7557
+ await ensureSharedGitignore(worktree, git, false);
7438
7558
  }
7439
- }
7440
- async function runList(config, uri, options) {
7441
- assertVikingUri(uri);
7442
- const ov = await openVikingCliForMode(options.dryRun === true);
7443
- const args = ["ls", uri];
7444
- if (options.all === true) {
7445
- args.push("--all");
7559
+ if (await hasUncommittedChanges(worktree)) {
7560
+ if (options.autoCommit === false) {
7561
+ throw new Error(
7562
+ `Worktree ${worktree} has uncommitted changes. Commit them yourself or rerun without --no-auto-commit.`
7563
+ );
7564
+ }
7565
+ const message = options.message ?? `share: sync ${(/* @__PURE__ */ new Date()).toISOString()}`;
7566
+ await stageShareableChanges(dryRun, git, worktree);
7567
+ await maybeRun(dryRun, git, ["-C", worktree, "commit", "-m", message], { allowFailure: true });
7446
7568
  }
7447
- if (options.recursive === true) {
7448
- args.push("--recursive");
7569
+ const beforeRev = await gitOutput(worktree, ["rev-parse", "HEAD"], dryRun);
7570
+ await maybeRun(dryRun, git, ["-C", worktree, "fetch", DEFAULT_GIT_REMOTE_NAME]);
7571
+ const pullResult = dryRun ? void 0 : await runCommand(git, ["-C", worktree, "pull", "--rebase", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
7572
+ if (dryRun) {
7573
+ console.log(`Would run: ${formatShellCommand(git, ["-C", worktree, "pull", "--rebase", DEFAULT_GIT_REMOTE_NAME])}`);
7574
+ } else if (pullResult && pullResult.exitCode !== 0) {
7575
+ if (await exists((0, import_node_path4.join)(team.config.gitdir, "rebase-merge")) || await exists((0, import_node_path4.join)(team.config.gitdir, "rebase-apply"))) {
7576
+ throw new Error(
7577
+ `git pull --rebase reported conflicts in ${worktree}. The worktree is in a rebase-in-progress state.
7578
+ Resolve the conflicts in-place, run \`git -C ${worktree} rebase --continue\` (or --abort), then re-run \`threadnote share sync\`.`
7579
+ );
7580
+ }
7581
+ throw new Error(
7582
+ `git pull --rebase failed in ${worktree}: ${pullResult.stderr.trim() || pullResult.stdout.trim() || "unknown error"}`
7583
+ );
7449
7584
  }
7450
- if (options.simple === true) {
7451
- args.push("--simple");
7585
+ const afterRev = await gitOutput(worktree, ["rev-parse", "HEAD"], dryRun);
7586
+ if (!dryRun && beforeRev && afterRev && beforeRev !== afterRev) {
7587
+ const changes = await listChangedFiles(worktree, beforeRev, afterRev);
7588
+ await applyChangesToOpenViking(config, team.config, changes);
7589
+ console.log(`Reindexed ${changes.length} file change(s) into OpenViking.`);
7590
+ } else if (!dryRun) {
7591
+ console.log("No upstream changes to reindex.");
7452
7592
  }
7453
- if (options.nodeLimit) {
7454
- args.push("--node-limit", String(parsePositiveInteger(options.nodeLimit, "node limit")));
7593
+ if (options.push !== false) {
7594
+ await maybeRun(dryRun, git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
7455
7595
  }
7456
- await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
7457
- }
7458
- async function runHandoff(config, options) {
7459
- const { bodyText, metadata } = await buildHandoff(options);
7460
- await storeMemory(config, {
7461
- bodyText,
7462
- dryRun: options.dryRun === true,
7463
- metadata,
7464
- replaceUri: options.replace,
7465
- title: "HANDOFF"
7466
- });
7467
7596
  }
7468
- async function runArchive(config, uri, options) {
7469
- assertVikingUri(uri);
7470
- const ov = await openVikingCliForMode(options.dryRun === true);
7471
- const readResult = await maybeRun(options.dryRun === true, ov, withIdentity(config, ["read", uri]));
7472
- const original = readResult?.stdout.trim();
7473
- if (options.dryRun === true) {
7474
- const fallbackMetadata = {
7475
- archivedFrom: uri,
7476
- kind: options.kind ?? "handoff",
7477
- project: normalizeOptionalMetadata(options.project),
7478
- sourceAgentClient: "threadnote",
7479
- status: "archived",
7480
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7481
- topic: normalizeOptionalMetadata(options.topic)
7482
- };
7483
- await storeMemory(config, {
7484
- bodyText: ["Archived original Threadnote memory.", "", "<original memory content would be read here>"].join("\n"),
7485
- dryRun: true,
7486
- metadata: fallbackMetadata,
7487
- title: "MEMORY"
7488
- });
7489
- console.log(formatShellCommand(ov, withIdentity(config, ["rm", uri])));
7490
- return;
7597
+ async function runShareSyncQuiet(config, state, options) {
7598
+ const team = await resolveTeam(config, options.team);
7599
+ const git = await requiredExecutable("git");
7600
+ const worktree = team.config.worktree;
7601
+ const pendingChanges = state.pendingReindexes.get(team.name);
7602
+ if (pendingChanges) {
7603
+ await applyChangesToOpenViking(config, team.config, pendingChanges, { quiet: true });
7604
+ state.pendingReindexes.delete(team.name);
7605
+ await writePendingReindexes(config, state);
7491
7606
  }
7492
- if (!original) {
7493
- throw new Error(`Could not read ${uri} before archiving.`);
7607
+ if (await hasUncommittedChanges(worktree)) {
7608
+ return `Shared team "${team.name}" has uncommitted changes; skipped automatic sync. Run \`threadnote share sync --team ${team.name}\` to publish or resolve them.`;
7494
7609
  }
7495
- const inferredMetadata = inferMemoryMetadata(original);
7496
- const metadata = {
7497
- archivedFrom: uri,
7498
- kind: options.kind ?? inferredMetadata.kind ?? "handoff",
7499
- project: normalizeOptionalMetadata(options.project) ?? inferredMetadata.project,
7500
- sourceAgentClient: "threadnote",
7501
- status: "archived",
7502
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7503
- topic: normalizeOptionalMetadata(options.topic) ?? inferredMetadata.topic
7504
- };
7505
- await storeMemory(config, {
7506
- bodyText: ["Archived original Threadnote memory.", "", original].join("\n"),
7507
- dryRun: false,
7508
- metadata,
7509
- title: "MEMORY"
7510
- });
7511
- const removedOriginal = await removeVikingResourceWithRetry(ov, config, uri);
7512
- if (removedOriginal) {
7513
- console.log(`Archived original memory: ${uri}`);
7514
- } else {
7515
- console.error(`Archive stored, but original memory is still processing. Retry later: threadnote forget ${uri}`);
7610
+ const ahead = await gitOutput(worktree, ["rev-list", "--count", "@{u}..HEAD"], false);
7611
+ if (ahead === void 0) {
7612
+ return `Shared team "${team.name}" upstream status is unknown; skipped automatic sync. Run \`threadnote share sync --team ${team.name}\` to inspect and resolve it.`;
7516
7613
  }
7517
- }
7518
- async function runForget(config, uri, options) {
7519
- assertVikingUri(uri);
7520
- const ov = await openVikingCliForMode(options.dryRun === true);
7521
- if (options.dryRun === true) {
7522
- await maybeRun(true, ov, withIdentity(config, ["rm", uri]));
7523
- return;
7614
+ if ((Number.parseInt(ahead, 10) || 0) > 0) {
7615
+ return `Shared team "${team.name}" has local commits ahead of upstream; skipped automatic sync. Run \`threadnote share sync --team ${team.name}\` to publish or reconcile them.`;
7524
7616
  }
7525
- const removed = await removeVikingResourceWithRetry(ov, config, uri);
7526
- if (!removed) {
7527
- throw new Error(`Resource is still being processed; retry later: threadnote forget ${uri}`);
7617
+ const beforeRev = await gitOutput(worktree, ["rev-parse", "HEAD"], false);
7618
+ const pullResult = await runCommand(git, ["-C", worktree, "rebase", "@{u}"], { allowFailure: true });
7619
+ if (pullResult.exitCode !== 0) {
7620
+ if (await exists((0, import_node_path4.join)(team.config.gitdir, "rebase-merge")) || await exists((0, import_node_path4.join)(team.config.gitdir, "rebase-apply"))) {
7621
+ throw new Error(
7622
+ `Automatic share sync hit git conflicts in ${worktree}. Resolve them in-place, run \`git -C ${worktree} rebase --continue\` (or --abort), then rerun recall/read.`
7623
+ );
7624
+ }
7625
+ throw new Error(
7626
+ `Automatic share sync failed in ${worktree}: ${pullResult.stderr.trim() || pullResult.stdout.trim() || "unknown error"}`
7627
+ );
7528
7628
  }
7629
+ const afterRev = await gitOutput(worktree, ["rev-parse", "HEAD"], false);
7630
+ if (beforeRev && afterRev && beforeRev !== afterRev) {
7631
+ const changes = await listChangedFiles(worktree, beforeRev, afterRev);
7632
+ if (changes.length > 0) {
7633
+ state.pendingReindexes.set(team.name, changes);
7634
+ await writePendingReindexes(config, state);
7635
+ await applyChangesToOpenViking(config, team.config, changes, { quiet: true });
7636
+ state.pendingReindexes.delete(team.name);
7637
+ await writePendingReindexes(config, state);
7638
+ }
7639
+ }
7640
+ return void 0;
7529
7641
  }
7530
- async function runExportPack(config, options) {
7531
- const ov = await openVikingCliForMode(options.dryRun === true);
7532
- const defaultPath = (0, import_node_path4.join)(config.agentContextHome, `threadnote-${safeTimestamp()}.ovpack`);
7533
- const outputPath = expandPath(options.path ?? defaultPath);
7534
- await maybeRun(options.dryRun === true, ov, withIdentity(config, ["export", options.uri ?? "viking://", outputPath]));
7642
+ async function stageShareableChanges(dryRun, git, worktree) {
7643
+ const pathspecs = [":(top)README.md", ":(top).gitignore", ...SHAREABLE_MEMORY_KIND_DIRS.map((dir) => `:(top)${dir}`)];
7644
+ await maybeRun(dryRun, git, ["-C", worktree, "add", "--", ...pathspecs], { allowFailure: true });
7535
7645
  }
7536
- async function runImportPack(config, options) {
7537
- if (!options.path) {
7538
- throw new Error("Provide --path for import-pack.");
7646
+ async function runSharePublish(config, sourceUri, options) {
7647
+ assertVikingUri(sourceUri);
7648
+ const team = await resolveTeam(config, options.team);
7649
+ const dryRun = options.dryRun === true;
7650
+ const preview = options.preview === true;
7651
+ if (isInSharedNamespace(config, sourceUri)) {
7652
+ throw new Error(`Memory ${sourceUri} is already in the shared namespace.`);
7539
7653
  }
7540
- const ov = await openVikingCliForMode(options.dryRun === true);
7541
- await maybeRun(
7542
- options.dryRun === true,
7543
- ov,
7544
- withIdentity(config, ["import", expandPath(options.path), options.targetUri ?? "viking://"])
7545
- );
7546
- }
7547
- async function inferRecallUri(config, query) {
7548
- if (!/\bskills?\b/.test(query.toLowerCase())) {
7549
- return void 0;
7550
- }
7551
- const project = await inferProjectFromQuery(config.manifestPath, query);
7552
- return project ? `viking://resources/agent-skills/repo-local-${uriSegment(project.name)}` : "viking://resources/agent-skills";
7553
- }
7554
- async function printExactMemoryMatches(config, ov, query, options) {
7555
- const terms = exactRecallTerms(query);
7556
- if (terms.length === 0) {
7557
- return;
7558
- }
7559
- const scopes = exactMemoryScopes(config, options.includeArchived);
7560
- const outputs = [];
7561
- for (const term of terms) {
7562
- for (const scope of scopes) {
7563
- const args = withIdentity(config, ["grep", term, "--uri", scope, "--node-limit", "5"]);
7564
- if (options.dryRun) {
7565
- outputs.push(formatShellCommand(ov, args));
7566
- continue;
7567
- }
7568
- const result = await runCommand(ov, args, { allowFailure: true });
7569
- const output2 = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join("\n");
7570
- if (result.exitCode === 0 && grepOutputHasMatches(output2)) {
7571
- outputs.push(output2);
7572
- }
7654
+ const ov = await openVikingCliForMode(dryRun);
7655
+ const rawContent = await readMemoryContent(config, ov, sourceUri, dryRun);
7656
+ const stripped = stripPersonalProvenance(rawContent);
7657
+ const scrub = applyScrubber(stripped, { redact: options.redact === true });
7658
+ const targetUri = sharedUriFor(config, sourceUri, team.name);
7659
+ if (preview) {
7660
+ console.log(`PREVIEW source: ${sourceUri}`);
7661
+ console.log(`PREVIEW destination: ${targetUri}`);
7662
+ if (scrub.blocker) {
7663
+ console.log(
7664
+ `PREVIEW BLOCKED: ${scrub.blocker}. Strip the sensitive value or rerun with --redact for soft-leak patterns.`
7665
+ );
7666
+ return;
7573
7667
  }
7574
- }
7575
- if (outputs.length === 0) {
7668
+ for (const redaction of scrub.redactions) {
7669
+ console.log(`PREVIEW redact: ${redaction.count}\xD7 ${redaction.name}`);
7670
+ }
7671
+ console.log("-----BEGIN PREVIEW-----");
7672
+ console.log(scrub.cleaned);
7673
+ console.log("-----END PREVIEW-----");
7576
7674
  return;
7577
7675
  }
7578
- console.log("\nExact durable memory matches:");
7579
- console.log(outputs.join("\n\n"));
7580
- }
7581
- async function storeMemory(config, options) {
7582
- if (options.replaceUri) {
7583
- assertVikingUri(options.replaceUri);
7676
+ if (scrub.blocker) {
7677
+ throw new Error(
7678
+ `Refusing to publish ${sourceUri}: possible ${scrub.blocker}. Strip the sensitive value or pass --redact for soft-leak patterns.`
7679
+ );
7584
7680
  }
7585
- const ov = await openVikingCliForMode(options.dryRun);
7586
- const memoryPath = (0, import_node_path4.join)(config.agentContextHome, "last-memory.txt");
7587
- const candidateMetadata = { ...options.metadata, supersedes: options.replaceUri };
7588
- const candidateMemory = formatMemoryDocument(options.title, candidateMetadata, options.bodyText);
7589
- const memoryUri = memoryUriFor(config, candidateMemory, candidateMetadata);
7590
- const isInPlaceUpdate = options.replaceUri !== void 0 && options.replaceUri === memoryUri;
7591
- const finalMetadata = isInPlaceUpdate ? { ...options.metadata, supersedes: void 0 } : candidateMetadata;
7592
- const memory = isInPlaceUpdate ? formatMemoryDocument(options.title, finalMetadata, options.bodyText) : candidateMemory;
7593
- const writeMode = await memoryWriteMode(ov, config, memoryUri, finalMetadata);
7594
- if (options.dryRun) {
7595
- console.log(memory);
7596
- console.log("\nWould run:");
7597
- console.log(
7598
- formatShellCommand(
7599
- ov,
7600
- withIdentity(config, [
7601
- "write",
7602
- memoryUri,
7603
- "--from-file",
7604
- memoryPath,
7605
- "--mode",
7606
- writeMode,
7607
- "--wait",
7608
- "--timeout",
7609
- "120"
7610
- ])
7611
- )
7681
+ for (const redaction of scrub.redactions) {
7682
+ console.log(`Redacted ${redaction.count}\xD7 ${redaction.name} before publish.`);
7683
+ }
7684
+ const content = scrub.cleaned;
7685
+ if (!dryRun && await vikingResourceExists(ov, config, targetUri)) {
7686
+ throw new Error(
7687
+ `Refusing to publish: ${targetUri} already exists in the shared namespace. Inspect it via threadnote read; if it should be replaced, forget the existing shared copy first.`
7612
7688
  );
7613
- if (options.replaceUri && !isInPlaceUpdate) {
7614
- console.log(formatShellCommand(ov, withIdentity(config, ["rm", options.replaceUri])));
7615
- }
7616
- return;
7617
7689
  }
7618
- await (0, import_promises4.writeFile)(memoryPath, memory, { encoding: "utf8", mode: 384 });
7619
- await (0, import_promises4.chmod)(memoryPath, 384);
7620
- await ensureMemoryDirectory(ov, config, memoryDirectoryUri(config, finalMetadata));
7621
- await writeDurableMemoryFile(ov, config, memoryUri, memoryPath, writeMode);
7622
- console.log(`Stored memory: ${memoryUri}`);
7623
- if (options.replaceUri && !isInPlaceUpdate) {
7624
- const removedReplacedMemory = await removeVikingResourceWithRetry(ov, config, options.replaceUri);
7625
- if (removedReplacedMemory) {
7626
- console.log(`Forgot replaced memory: ${options.replaceUri}`);
7627
- } else {
7628
- console.error(
7629
- `Replacement stored, but the superseded memory is still processing. Retry later: threadnote forget ${options.replaceUri}`
7690
+ await ensureSharedDirectoryChain(config, ov, targetUri, dryRun);
7691
+ await writeMemoryFile(config, ov, targetUri, content, "create", dryRun);
7692
+ await removeWithRollback(config, ov, sourceUri, targetUri, team.config.worktree, dryRun, "publish");
7693
+ const git = await requiredExecutable("git");
7694
+ const worktree = team.config.worktree;
7695
+ const relativePath = vikingUriToWorktreeRelative(config, targetUri, team.name);
7696
+ const message = options.message ?? `share: publish ${relativePath}`;
7697
+ await maybeRun(dryRun, git, ["-C", worktree, "add", "--", relativePath]);
7698
+ await maybeRun(dryRun, git, ["-C", worktree, "commit", "-m", message], { allowFailure: true });
7699
+ if (options.push !== false) {
7700
+ const pushResult = dryRun ? void 0 : await runCommand(git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
7701
+ if (dryRun) {
7702
+ console.log(`Would run: ${formatShellCommand(git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME])}`);
7703
+ } else if (pushResult && pushResult.exitCode !== 0) {
7704
+ const detail = pushResult.stderr.trim() || pushResult.stdout.trim() || "unknown error";
7705
+ throw new Error(
7706
+ `Memory was committed locally but git push failed: ${detail}
7707
+ Resolve the remote issue (auth, network, branch protection), then run: threadnote share sync`
7630
7708
  );
7631
7709
  }
7632
- } else if (isInPlaceUpdate) {
7633
- console.log(`Updated existing memory in place: ${memoryUri}`);
7634
7710
  }
7711
+ console.log(`Published ${sourceUri} -> ${targetUri}`);
7635
7712
  }
7636
- async function writeDurableMemoryFile(ov, config, memoryUri, memoryPath, writeMode) {
7637
- const args = withIdentity(config, [
7638
- "write",
7639
- memoryUri,
7640
- "--from-file",
7641
- memoryPath,
7642
- "--mode",
7643
- writeMode,
7644
- "--wait",
7645
- "--timeout",
7646
- "120"
7647
- ]);
7648
- for (let attempt = 0; attempt < 4; attempt += 1) {
7649
- console.log(`${attempt === 0 ? "Running" : "Retrying"}: ${formatShellCommand(ov, args)}`);
7650
- const result = await runCommand(ov, args, { allowFailure: true });
7651
- if (result.exitCode === 0) {
7652
- if (result.stdout.trim()) {
7653
- console.log(result.stdout.trim());
7654
- }
7655
- if (result.stderr.trim()) {
7656
- console.error(result.stderr.trim());
7657
- }
7658
- return;
7659
- }
7660
- if (await vikingResourceExists(ov, config, memoryUri)) {
7661
- console.log("OpenViking accepted the memory but returned before the wait completed; waiting for indexing.");
7662
- await waitForOpenVikingQueue(ov, config);
7663
- return;
7664
- }
7665
- if (!isResourceBusy(result.stderr, result.stdout) || attempt === 3) {
7666
- throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
7667
- }
7668
- await sleep(1e3 * (attempt + 1));
7713
+ async function runShareUnpublish(config, sourceUri, options) {
7714
+ assertVikingUri(sourceUri);
7715
+ const team = await resolveTeam(config, options.team);
7716
+ const dryRun = options.dryRun === true;
7717
+ if (!isInTeamNamespace(config, sourceUri, team.name)) {
7718
+ throw new Error(`Memory ${sourceUri} is not in team "${team.name}" shared namespace.`);
7669
7719
  }
7670
- }
7671
- async function waitForOpenVikingQueue(ov, config) {
7672
- const result = await runCommand(ov, withIdentity(config, ["wait", "--timeout", "120"]), { allowFailure: true });
7673
- if (result.stdout.trim()) {
7674
- console.log(result.stdout.trim());
7720
+ const ov = await openVikingCliForMode(dryRun);
7721
+ const content = await readMemoryContent(config, ov, sourceUri, dryRun);
7722
+ const targetUri = personalUriFor(config, sourceUri, team.name);
7723
+ if (!dryRun && await vikingResourceExists(ov, config, targetUri)) {
7724
+ throw new Error(
7725
+ `Refusing to unpublish: a personal memory already exists at ${targetUri}. Move or forget it first, then retry.`
7726
+ );
7675
7727
  }
7676
- if (result.stderr.trim()) {
7677
- console.error(result.stderr.trim());
7728
+ await writeMemoryFile(config, ov, targetUri, content, "create", dryRun);
7729
+ await removeWithRollback(config, ov, sourceUri, targetUri, team.config.worktree, dryRun, "unpublish");
7730
+ const git = await requiredExecutable("git");
7731
+ const worktree = team.config.worktree;
7732
+ const relativePath = vikingUriToWorktreeRelative(config, sourceUri, team.name);
7733
+ const message = options.message ?? `share: unpublish ${relativePath}`;
7734
+ await maybeRun(dryRun, git, ["-C", worktree, "rm", relativePath], { allowFailure: true });
7735
+ await maybeRun(dryRun, git, ["-C", worktree, "commit", "-m", message], { allowFailure: true });
7736
+ if (options.push !== false) {
7737
+ await maybeRun(dryRun, git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
7678
7738
  }
7739
+ console.log(`Unpublished ${sourceUri} -> ${targetUri}`);
7679
7740
  }
7680
- async function removeVikingResourceWithRetry(ov, config, uri) {
7681
- const args = withIdentity(config, ["rm", uri]);
7682
- for (let attempt = 0; attempt < 4; attempt += 1) {
7683
- console.log(`${attempt === 0 ? "Running" : "Retrying"}: ${formatShellCommand(ov, args)}`);
7684
- const result = await runCommand(ov, args, { allowFailure: true });
7685
- if (result.exitCode === 0) {
7686
- if (result.stdout.trim()) {
7687
- console.log(result.stdout.trim());
7688
- }
7689
- if (result.stderr.trim()) {
7690
- console.error(result.stderr.trim());
7691
- }
7692
- return true;
7693
- }
7694
- if (isResourceBusy(result.stderr, result.stdout) && attempt === 3) {
7695
- return false;
7696
- }
7697
- if (!isResourceBusy(result.stderr, result.stdout)) {
7698
- throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
7699
- }
7700
- await sleep(1e3 * (attempt + 1));
7741
+ async function runShareList(config, _options) {
7742
+ const teams = await readTeamsFile(config);
7743
+ const entries = Object.values(teams.teams);
7744
+ if (entries.length === 0) {
7745
+ console.log("No shared teams configured. Run: threadnote share init <remote-url>");
7746
+ return;
7747
+ }
7748
+ for (const team of entries) {
7749
+ const marker = team.name === teams.defaultTeam ? " (default)" : "";
7750
+ console.log(`- ${team.name}${marker}`);
7751
+ console.log(` remote: ${team.remote}`);
7752
+ console.log(` worktree: ${portablePath(team.worktree)}`);
7753
+ console.log(` gitdir: ${portablePath(team.gitdir)}`);
7754
+ console.log(` added: ${team.addedAt}`);
7701
7755
  }
7702
- return false;
7703
- }
7704
- async function vikingResourceExists(ov, config, uri) {
7705
- const stat4 = await runCommand(ov, withIdentity(config, ["stat", uri]), { allowFailure: true });
7706
- return stat4.exitCode === 0;
7707
- }
7708
- async function ensureDurableMemoryDirectory(ov, config) {
7709
- await ensureMemoryDirectory(ov, config, durableMemoryDirectoryUri(config));
7710
7756
  }
7711
- async function ensureMemoryDirectory(ov, config, directoryUri) {
7712
- for (const uri of vikingDirectoryChain(directoryUri)) {
7713
- const statResult = await runCommand(ov, withIdentity(config, ["stat", uri]), { allowFailure: true });
7714
- if (statResult.exitCode === 0) {
7715
- continue;
7757
+ async function runShareRemove(config, options) {
7758
+ const team = await resolveTeam(config, options.team);
7759
+ const dryRun = options.dryRun === true;
7760
+ const teamsFile = await readTeamsFile(config);
7761
+ const remaining = {};
7762
+ for (const [name, value] of Object.entries(teamsFile.teams)) {
7763
+ if (name !== team.name) {
7764
+ remaining[name] = value;
7716
7765
  }
7717
- await maybeRun(
7718
- false,
7719
- ov,
7720
- withIdentity(config, ["mkdir", uri, "--description", "Threadnote lifecycle-aware local memories."])
7721
- );
7766
+ }
7767
+ const remainingNames = Object.keys(remaining);
7768
+ const nextDefault = teamsFile.defaultTeam === team.name ? remainingNames[0] : teamsFile.defaultTeam;
7769
+ const updated = { defaultTeam: nextDefault, teams: remaining, version: TEAMS_FILE_VERSION };
7770
+ if (dryRun) {
7771
+ console.log(`Would update teams file: ${teamsFilePath(config)}`);
7772
+ } else {
7773
+ await writeTeamsFile(config, updated);
7774
+ console.log(`Removed team "${team.name}" from teams.json.`);
7775
+ }
7776
+ if (options.keepFiles !== true) {
7777
+ await removePath(team.config.worktree, "shared worktree", dryRun);
7778
+ await removePath(team.config.gitdir, "shared gitdir", dryRun);
7779
+ } else {
7780
+ console.log(`Keeping files at ${portablePath(team.config.worktree)} and ${portablePath(team.config.gitdir)}`);
7722
7781
  }
7723
7782
  }
7724
- function durableMemoryDirectoryUri(config) {
7725
- return `viking://user/${uriSegment(config.user)}/memories/events`;
7726
- }
7727
- function migratedDurableMemoryUri(config, hash) {
7728
- return `${durableMemoryDirectoryUri(config)}/threadnote-migrated-${hash.slice(0, 16)}.md`;
7729
- }
7730
- async function hasLegacyLifecycleHandoffCandidates(config) {
7731
- return (await legacyLifecycleHandoffCandidates(config, 1)).length > 0;
7732
- }
7733
- async function legacyLifecycleHandoffCandidates(config, limit) {
7734
- const eventsRoot = (0, import_node_path4.join)(localUserMemoriesRoot(config), "events");
7735
- let entries;
7736
- try {
7737
- entries = await (0, import_promises4.readdir)(eventsRoot, { withFileTypes: true });
7738
- } catch (_err) {
7739
- return [];
7783
+ function normalizeTeamName(input2) {
7784
+ const candidate = (input2 ?? "default").trim();
7785
+ if (!candidate) {
7786
+ return "default";
7740
7787
  }
7741
- const candidates = [];
7742
- for (const entry of entries) {
7743
- if (!entry.isFile() || entry.name.startsWith(".") || !entry.name.endsWith(".md")) {
7744
- continue;
7745
- }
7746
- const sourcePath = (0, import_node_path4.join)(eventsRoot, entry.name);
7747
- const original = await readTextIfExists(sourcePath);
7748
- if (!original || !isClearLegacyHandoffMemory(original) || sensitiveMemoryReason(original)) {
7749
- continue;
7750
- }
7751
- const sourceUri = `${durableMemoryDirectoryUri(config)}/${entry.name}`;
7752
- candidates.push({
7753
- metadata: {
7754
- archivedFrom: sourceUri,
7755
- kind: "handoff",
7756
- project: inferLegacyProject(original),
7757
- sourceAgentClient: "threadnote",
7758
- status: "archived",
7759
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
7760
- },
7761
- original,
7762
- sourceUri
7763
- });
7764
- if (limit !== void 0 && candidates.length >= limit) {
7765
- break;
7766
- }
7788
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(candidate) || /^\.+$/.test(candidate)) {
7789
+ throw new Error(
7790
+ `Invalid team name "${input2}". Team names must start with a lowercase letter or digit and contain only [a-z0-9._-]. Single-dot or dot-only names are rejected so they don't collapse to the shared-root or parent directory.`
7791
+ );
7767
7792
  }
7768
- return candidates;
7793
+ return candidate;
7769
7794
  }
7770
- function lifecycleMigrationUri(config, metadata, hash) {
7771
- return `${memoryDirectoryUri(config, metadata)}/legacy-${hash.slice(0, 16)}.md`;
7795
+ function teamsFilePath(config) {
7796
+ return (0, import_node_path4.join)(config.agentContextHome, "share", "teams.json");
7772
7797
  }
7773
- function exactMemoryScopes(config, includeArchived) {
7774
- const userBase = `viking://user/${uriSegment(config.user)}/memories`;
7775
- const scopes = [
7776
- `${userBase}/preferences`,
7777
- `${userBase}/durable/projects`,
7778
- `${userBase}/handoffs/active`,
7779
- `${userBase}/incidents/active`,
7780
- `${userBase}/events`,
7781
- `${userBase}/shared`,
7782
- `viking://agent/${uriSegment(config.agentId)}/memories`,
7783
- // Seeded project resources (READMEs, AGENTS.md, SKILL.md, docs/**) live
7784
- // under viking://resources/repos/<project>. Include them so an exact-term
7785
- // grep in a recall surfaces matches in seeded guidance, not only memories.
7786
- "viking://resources/repos"
7787
- ];
7788
- return includeArchived ? [...scopes, `${userBase}/durable/archived`, `${userBase}/handoffs/archived`, `${userBase}/incidents/archived`] : scopes;
7798
+ function teamWorktreePath(config, team) {
7799
+ return (0, import_node_path4.join)(
7800
+ config.agentContextHome,
7801
+ "data",
7802
+ "viking",
7803
+ config.account,
7804
+ "user",
7805
+ uriSegment(config.user),
7806
+ "memories",
7807
+ SHARED_SEGMENT,
7808
+ team
7809
+ );
7789
7810
  }
7790
- function memoryUriFor(config, memory, metadata) {
7791
- const filename = shouldUseStableMemoryUri(metadata) ? `${uriSegment(metadata.topic ?? "current")}.md` : `threadnote-${safeTimestamp()}-${sha256(memory).slice(0, 12)}.md`;
7792
- return `${memoryDirectoryUri(config, metadata)}/${filename}`;
7811
+ function teamGitdirPath(config, team) {
7812
+ return (0, import_node_path4.join)(config.agentContextHome, "share", "teams", `${team}.gitdir`);
7793
7813
  }
7794
- function memoryDirectoryUri(config, metadata) {
7795
- const baseUri = `viking://user/${uriSegment(config.user)}/memories`;
7796
- const projectSegment = uriSegment(metadata.project ?? "general");
7797
- switch (metadata.kind) {
7798
- case "preference":
7799
- return metadata.status === "active" ? `${baseUri}/preferences` : `${baseUri}/preferences/${uriSegment(metadata.status)}`;
7800
- case "handoff":
7801
- return `${baseUri}/handoffs/${uriSegment(metadata.status)}/${projectSegment}`;
7802
- case "incident":
7803
- return `${baseUri}/incidents/${uriSegment(metadata.status)}/${projectSegment}`;
7804
- case "smoke":
7805
- return `${baseUri}/smoke/${uriSegment(metadata.status)}`;
7806
- case "durable":
7807
- return metadata.status === "active" ? `${baseUri}/durable/projects/${projectSegment}` : `${baseUri}/durable/${uriSegment(metadata.status)}/${projectSegment}`;
7814
+ async function readTeamsFile(config) {
7815
+ const path = teamsFilePath(config);
7816
+ const raw = await readFileIfExists(path);
7817
+ if (!raw) {
7818
+ return { teams: {}, version: TEAMS_FILE_VERSION };
7808
7819
  }
7809
- }
7810
- function shouldUseStableMemoryUri(metadata) {
7811
- return metadata.status === "active" && metadata.topic !== void 0 && metadata.kind !== "smoke";
7812
- }
7813
- async function memoryWriteMode(ov, config, memoryUri, metadata) {
7814
- if (!shouldUseStableMemoryUri(metadata)) {
7815
- return "create";
7820
+ const parsed = parseJsonConfigObject(raw);
7821
+ if (!parsed) {
7822
+ throw new Error(`Could not parse teams file ${path}`);
7816
7823
  }
7817
- return await vikingResourceExists(ov, config, memoryUri) ? "replace" : "create";
7818
- }
7819
- function vikingDirectoryChain(directoryUri) {
7820
- const prefix = "viking://";
7821
- if (!directoryUri.startsWith(prefix)) {
7822
- return [directoryUri];
7824
+ if (typeof parsed.version === "number" && parsed.version > TEAMS_FILE_VERSION) {
7825
+ throw new Error(
7826
+ `Teams file ${path} was written with version ${parsed.version}; this Threadnote binary understands up to version ${TEAMS_FILE_VERSION}. Upgrade Threadnote (\`threadnote update\`) before continuing.`
7827
+ );
7823
7828
  }
7824
- const parts = directoryUri.slice(prefix.length).split("/").filter(Boolean);
7825
- const startIndex = parts[0] === "user" && parts.length > 2 ? 3 : 1;
7826
- const chain = [];
7827
- for (let index = startIndex; index <= parts.length; index += 1) {
7828
- chain.push(`${prefix}${parts.slice(0, index).join("/")}`);
7829
+ const teams = {};
7830
+ if (typeof parsed.teams === "object" && parsed.teams !== null && !Array.isArray(parsed.teams)) {
7831
+ for (const [name, value] of Object.entries(parsed.teams)) {
7832
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
7833
+ console.warn(`Skipping non-object team entry "${name}" in ${path}.`);
7834
+ continue;
7835
+ }
7836
+ const entry = value;
7837
+ if (typeof entry.remote !== "string" || entry.remote.length === 0) {
7838
+ console.warn(`Skipping team entry "${name}" in ${path}: missing or empty "remote" field.`);
7839
+ continue;
7840
+ }
7841
+ teams[name] = {
7842
+ addedAt: typeof entry.addedAt === "string" ? entry.addedAt : (/* @__PURE__ */ new Date(0)).toISOString(),
7843
+ gitdir: typeof entry.gitdir === "string" ? entry.gitdir : teamGitdirPath(config, name),
7844
+ name,
7845
+ remote: entry.remote,
7846
+ worktree: typeof entry.worktree === "string" ? entry.worktree : teamWorktreePath(config, name)
7847
+ };
7848
+ }
7829
7849
  }
7830
- return chain;
7831
- }
7832
- function formatMemoryDocument(title, metadata, body) {
7833
- const header = [
7834
- title,
7835
- `kind: ${metadata.kind}`,
7836
- `status: ${metadata.status}`,
7837
- metadata.project ? `project: ${metadata.project}` : void 0,
7838
- metadata.topic ? `topic: ${metadata.topic}` : void 0,
7839
- `source_agent_client: ${metadata.sourceAgentClient}`,
7840
- `timestamp: ${metadata.timestamp}`,
7841
- metadata.supersedes ? `supersedes: ${metadata.supersedes}` : void 0,
7842
- metadata.archivedFrom ? `archived_from: ${metadata.archivedFrom}` : void 0
7843
- ].filter((line) => line !== void 0);
7844
- return [...header, "", body.trim()].join("\n");
7850
+ const defaultTeam = typeof parsed.defaultTeam === "string" ? parsed.defaultTeam : void 0;
7851
+ return { defaultTeam, teams, version: TEAMS_FILE_VERSION };
7845
7852
  }
7846
- function inferMemoryMetadata(memory) {
7847
- const header = memory.slice(0, Math.max(0, memory.indexOf("\n\n")) || memory.length);
7848
- const firstLine2 = header.split("\n")[0]?.trim();
7849
- const kind = parseOptionalMemoryKind(parseHeaderValue(header, "kind")) ?? (firstLine2 === "HANDOFF" ? "handoff" : void 0);
7850
- const status = parseOptionalMemoryStatus(parseHeaderValue(header, "status"));
7851
- const project = normalizeOptionalMetadata(parseHeaderValue(header, "project")) ?? normalizeOptionalMetadata(parseHeaderValue(header, "repo"));
7852
- const topic = normalizeOptionalMetadata(parseHeaderValue(header, "topic")) ?? normalizeOptionalMetadata(parseHeaderValue(header, "task"));
7853
- return {
7854
- kind,
7855
- project,
7856
- sourceAgentClient: parseHeaderValue(header, "source_agent_client") ?? void 0,
7857
- status,
7858
- topic
7853
+ async function writeTeamsFile(config, contents) {
7854
+ const path = teamsFilePath(config);
7855
+ await (0, import_promises4.mkdir)((0, import_node_path4.dirname)(path), { recursive: true });
7856
+ const serializable = {
7857
+ defaultTeam: contents.defaultTeam,
7858
+ teams: contents.teams,
7859
+ version: contents.version
7859
7860
  };
7861
+ await (0, import_promises4.writeFile)(path, `${JSON.stringify(serializable, void 0, 2)}
7862
+ `, { encoding: "utf8", mode: 384 });
7860
7863
  }
7861
- function parseHeaderValue(header, key) {
7862
- const prefix = `${key}:`;
7863
- return header.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length).trim();
7864
- }
7865
- function isClearLegacyHandoffMemory(memory) {
7866
- if (/^kind:\s*/m.test(memory) || /^status:\s*/m.test(memory)) {
7867
- return false;
7868
- }
7869
- const trimmed = memory.trim();
7870
- if (trimmed.startsWith("HANDOFF\n")) {
7871
- return true;
7864
+ async function resolveTeam(config, requested) {
7865
+ const teamsFile = await readTeamsFile(config);
7866
+ const entries = Object.entries(teamsFile.teams);
7867
+ if (entries.length === 0) {
7868
+ throw new Error("No shared teams configured. Run: threadnote share init <remote-url>");
7872
7869
  }
7873
- if (!trimmed.startsWith("MEMORY\n")) {
7874
- return false;
7870
+ const wantName = requested ? normalizeTeamName(requested) : teamsFile.defaultTeam ?? entries[0][0];
7871
+ const found = teamsFile.teams[wantName];
7872
+ if (!found) {
7873
+ const known = entries.map(([name]) => name).join(", ");
7874
+ throw new Error(`Team "${wantName}" is not configured. Known teams: ${known}`);
7875
7875
  }
7876
- return /^(?:#+\s*)?(?:final\s+)?handoff(?:\s+update)?\b/i.test(memoryBody(trimmed));
7877
- }
7878
- function memoryBody(memory) {
7879
- const separatorIndex = memory.indexOf("\n\n");
7880
- return separatorIndex === -1 ? "" : memory.slice(separatorIndex + 2).trim();
7876
+ return { config: found, name: wantName };
7881
7877
  }
7882
- function inferLegacyProject(memory) {
7883
- const explicit = parseHeaderValue(memory, "project") ?? parseHeaderValue(memory, "repo") ?? parseHeaderValue(memory, "repo_path") ?? /\brepo(?:_path)?\s+([~/A-Za-z0-9_.:/-]+)/.exec(memory)?.[1];
7884
- if (!explicit) {
7885
- return "general";
7878
+ function shouldSetDefault(options, existing) {
7879
+ if (options.setDefault === true) {
7880
+ return true;
7886
7881
  }
7887
- const trimmed = explicit.trim().replace(/[`.,;]+$/g, "");
7888
- return trimmed.includes("/") ? (0, import_node_path4.basename)(trimmed) : trimmed;
7882
+ return existing.defaultTeam === void 0;
7889
7883
  }
7890
- function parseOptionalMemoryKind(value) {
7891
- if (!value) {
7892
- return void 0;
7884
+ async function assertWorktreeUsable(worktree) {
7885
+ if (!await exists(worktree)) {
7886
+ return;
7893
7887
  }
7894
- try {
7895
- return parseMemoryKind(value);
7896
- } catch (_err) {
7897
- return void 0;
7888
+ if (!await isDirectory(worktree)) {
7889
+ throw new Error(`Cannot use ${worktree} as a worktree: not a directory.`);
7898
7890
  }
7899
- }
7900
- function parseOptionalMemoryStatus(value) {
7901
- if (!value) {
7902
- return void 0;
7891
+ const entries = await (0, import_promises4.readdir)(worktree);
7892
+ if (entries.length > 0) {
7893
+ const preview = entries.slice(0, 5).join(", ");
7894
+ const suffix = entries.length > 5 ? `, +${entries.length - 5} more` : "";
7895
+ throw new Error(
7896
+ `Worktree ${worktree} is not empty (contains: ${preview}${suffix}). Move or remove its contents, then retry threadnote share init.`
7897
+ );
7903
7898
  }
7904
- try {
7905
- return parseMemoryStatus(value);
7906
- } catch (_err) {
7907
- return void 0;
7908
- }
7909
- }
7910
- function normalizeOptionalMetadata(value) {
7911
- const trimmed = value?.trim();
7912
- return trimmed ? trimmed : void 0;
7913
7899
  }
7914
- async function legacySourceAccounts(config, options) {
7915
- const explicitAccounts = options.sourceAccount?.filter((account) => account.trim().length > 0) ?? [];
7916
- if (explicitAccounts.length > 0) {
7917
- return uniqueStrings(explicitAccounts);
7918
- }
7919
- if (options.allAccounts === true) {
7920
- const accounts = await childDirectoryNames(localVikingDataRoot(config));
7921
- return accounts.filter((account) => !account.startsWith("_"));
7900
+ async function ingestWorktreeFiles(config, team, initialMode) {
7901
+ const ov = await openVikingCliForMode(false);
7902
+ const files = await walkMemoryFiles(team.worktree);
7903
+ for (const file of files) {
7904
+ const uri = workfileToVikingUri(config, team, file);
7905
+ await ensureSharedDirectoryChain(config, ov, uri, false);
7906
+ await ingestSingleFile(ov, config, uri, file, initialMode);
7922
7907
  }
7923
- return [config.account];
7908
+ return files.length;
7924
7909
  }
7925
- async function legacyMemoryCandidates(config, sourceAccounts) {
7926
- const candidates = [];
7927
- for (const sourceAccount of sourceAccounts) {
7928
- const sessionRoot = (0, import_node_path4.join)(localVikingDataRoot(config), sourceAccount, "session");
7929
- for (const sourceSession of await childDirectoryNames(sessionRoot)) {
7930
- const historyRoot = (0, import_node_path4.join)(sessionRoot, sourceSession, "history");
7931
- for (const sourceArchive of await childDirectoryNames(historyRoot)) {
7932
- if (!sourceArchive.startsWith("archive_")) {
7910
+ async function walkMemoryFiles(root) {
7911
+ const out = [];
7912
+ async function visit(path, depth) {
7913
+ let entries;
7914
+ try {
7915
+ entries = await (0, import_promises4.readdir)(path, { withFileTypes: true });
7916
+ } catch (err) {
7917
+ console.warn(`Skipping ${path} during shared-tree walk: ${err instanceof Error ? err.message : String(err)}`);
7918
+ return;
7919
+ }
7920
+ for (const entry of entries) {
7921
+ if (entry.name === ".git") {
7922
+ continue;
7923
+ }
7924
+ const full = (0, import_node_path4.join)(path, entry.name);
7925
+ if (entry.isDirectory()) {
7926
+ if (depth === 0 && !SHAREABLE_MEMORY_KIND_DIRS.includes(entry.name)) {
7933
7927
  continue;
7934
7928
  }
7935
- const sourcePath = (0, import_node_path4.join)(historyRoot, sourceArchive, "messages.jsonl");
7936
- for (const text of await legacyMemoryTexts(sourcePath)) {
7937
- candidates.push({
7938
- comparableHash: sha256(comparableMemoryText(text)),
7939
- hash: sha256(text),
7940
- sourceAccount,
7941
- sourceArchive,
7942
- sourceSession,
7943
- text
7944
- });
7945
- }
7929
+ await visit(full, depth + 1);
7930
+ continue;
7931
+ }
7932
+ if (!entry.isFile()) {
7933
+ continue;
7934
+ }
7935
+ if (depth === 0) {
7936
+ continue;
7937
+ }
7938
+ if (!entry.name.endsWith(".md")) {
7939
+ continue;
7946
7940
  }
7941
+ out.push(full);
7947
7942
  }
7948
7943
  }
7949
- return candidates.sort((left, right) => legacySourceLabel(left).localeCompare(legacySourceLabel(right)));
7944
+ await visit(root, 0);
7945
+ return out;
7950
7946
  }
7951
- async function legacyMemoryTexts(sourcePath) {
7952
- const raw = await readTextIfExists(sourcePath);
7953
- if (!raw) {
7954
- return [];
7947
+ function workfileToVikingUri(config, team, filePath) {
7948
+ const rel = (0, import_node_path4.relative)(team.worktree, filePath).split(import_node_path4.sep).join("/");
7949
+ return `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team.name}/${rel}`;
7950
+ }
7951
+ function isInSharedNamespace(config, uri) {
7952
+ return uri.startsWith(`viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/`);
7953
+ }
7954
+ function isInTeamNamespace(config, uri, team) {
7955
+ return uri.startsWith(`viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team}/`);
7956
+ }
7957
+ function sharedUriFor(config, personalUri, team) {
7958
+ const prefix = `viking://user/${uriSegment(config.user)}/memories/`;
7959
+ if (!personalUri.startsWith(prefix)) {
7960
+ throw new Error(`Refusing to publish memory outside the current user namespace: ${personalUri}`);
7955
7961
  }
7956
- const memories = [];
7957
- for (const line of raw.split("\n")) {
7958
- const trimmedLine = line.trim();
7959
- if (!trimmedLine) {
7960
- continue;
7962
+ const rest = personalUri.slice(prefix.length);
7963
+ return `${prefix}${SHARED_SEGMENT}/${team}/${rest}`;
7964
+ }
7965
+ function personalUriFor(config, sharedUri, team) {
7966
+ const prefix = `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team}/`;
7967
+ if (!sharedUri.startsWith(prefix)) {
7968
+ throw new Error(`Refusing to unpublish a URI outside team "${team}" shared namespace: ${sharedUri}`);
7969
+ }
7970
+ const rest = sharedUri.slice(prefix.length);
7971
+ return `viking://user/${uriSegment(config.user)}/memories/${rest}`;
7972
+ }
7973
+ function vikingUriToWorktreeRelative(config, uri, team) {
7974
+ const prefix = `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team}/`;
7975
+ if (!uri.startsWith(prefix)) {
7976
+ throw new Error(`URI ${uri} is not inside team "${team}" shared subtree.`);
7977
+ }
7978
+ return uri.slice(prefix.length);
7979
+ }
7980
+ function stripPersonalProvenance(content) {
7981
+ const lines = content.split("\n");
7982
+ let headerEnd = lines.length;
7983
+ for (let index = 0; index < lines.length; index += 1) {
7984
+ if (lines[index].trim() === "") {
7985
+ headerEnd = index;
7986
+ break;
7961
7987
  }
7962
- try {
7963
- const parsed = JSON.parse(trimmedLine);
7964
- const text = legacyMessageText(parsed)?.trim();
7965
- if (text && isLegacyThreadnoteMemory(text)) {
7966
- memories.push(text);
7967
- }
7968
- } catch (_err) {
7988
+ }
7989
+ const cleaned = [];
7990
+ for (let index = 0; index < headerEnd; index += 1) {
7991
+ if (/^(?:supersedes|archived_from):\s/.test(lines[index])) {
7969
7992
  continue;
7970
7993
  }
7994
+ cleaned.push(lines[index]);
7971
7995
  }
7972
- return memories;
7973
- }
7974
- function legacyMessageText(value) {
7975
- if (!isJsonObject(value)) {
7976
- return void 0;
7996
+ for (let index = headerEnd; index < lines.length; index += 1) {
7997
+ cleaned.push(lines[index]);
7977
7998
  }
7978
- if (typeof value.content === "string") {
7979
- return value.content;
7999
+ return cleaned.join("\n");
8000
+ }
8001
+ async function readMemoryContent(config, ov, uri, dryRun) {
8002
+ const args = withIdentity(config, ["read", uri]);
8003
+ if (dryRun) {
8004
+ console.log(`Would run: ${formatShellCommand(ov, args)}`);
8005
+ return "<dry-run memory body>";
7980
8006
  }
7981
- if (!Array.isArray(value.parts)) {
7982
- return void 0;
8007
+ const result = await runCommand(ov, args);
8008
+ if (!result.stdout.trim()) {
8009
+ throw new Error(`Refusing to publish empty memory at ${uri}`);
7983
8010
  }
7984
- const parts = value.parts.map((part) => isJsonObject(part) && part.type === "text" && typeof part.text === "string" ? part.text : void 0).filter((text) => text !== void 0);
7985
- return parts.length > 0 ? parts.join("\n") : void 0;
7986
- }
7987
- function isLegacyThreadnoteMemory(text) {
7988
- return text.startsWith("MEMORY\n") || text.startsWith("HANDOFF\n");
7989
- }
7990
- async function existingDurableMemoryHashes(config) {
7991
- const hashes = /* @__PURE__ */ new Set();
7992
- await collectDurableMemoryHashes(localVikingDataRoot(config), hashes);
7993
- return hashes;
8011
+ return result.stdout;
7994
8012
  }
7995
- async function collectDurableMemoryHashes(root, hashes) {
7996
- let entries;
7997
- try {
7998
- entries = await (0, import_promises4.readdir)(root, { withFileTypes: true });
7999
- } catch (_err) {
8000
- return;
8001
- }
8002
- for (const entry of entries) {
8003
- const path = (0, import_node_path4.join)(root, entry.name);
8004
- if (entry.isDirectory()) {
8005
- await collectDurableMemoryHashes(path, hashes);
8013
+ async function ensureSharedDirectoryChain(config, ov, memoryUri, dryRun, options = {}) {
8014
+ const directoryUri = parentUri(memoryUri);
8015
+ for (const uri of sharedDirectoryChain(config, directoryUri)) {
8016
+ const args = withIdentity(config, ["stat", uri]);
8017
+ if (dryRun) {
8018
+ if (options.quiet !== true) {
8019
+ console.log(`Would run: ${formatShellCommand(ov, args)}`);
8020
+ }
8006
8021
  continue;
8007
8022
  }
8008
- if (!entry.isFile() || entry.name.startsWith(".") || !entry.name.endsWith(".md") || !isDurableMemoryPath(path)) {
8023
+ const statResult = await runCommand(ov, args, { allowFailure: true });
8024
+ if (statResult.exitCode === 0) {
8009
8025
  continue;
8010
8026
  }
8011
- const content = await readTextIfExists(path);
8012
- if (content) {
8013
- const trimmedContent = content.trim();
8014
- hashes.add(sha256(trimmedContent));
8015
- hashes.add(sha256(comparableMemoryText(trimmedContent)));
8027
+ if (options.quiet === true) {
8028
+ await runCommand(ov, withIdentity(config, ["mkdir", uri, "--description", "Threadnote shared memories."]));
8029
+ } else {
8030
+ await maybeRun(false, ov, withIdentity(config, ["mkdir", uri, "--description", "Threadnote shared memories."]));
8016
8031
  }
8017
8032
  }
8018
8033
  }
8019
- function isDurableMemoryPath(path) {
8020
- return path.split(import_node_path4.sep).includes("memories");
8034
+ function parentUri(uri) {
8035
+ const lastSlash = uri.lastIndexOf("/");
8036
+ return lastSlash === -1 ? uri : uri.slice(0, lastSlash);
8021
8037
  }
8022
- async function childDirectoryNames(path) {
8023
- let entries;
8024
- try {
8025
- entries = await (0, import_promises4.readdir)(path, { withFileTypes: true });
8026
- } catch (_err) {
8027
- return [];
8038
+ function sharedDirectoryChain(config, directoryUri) {
8039
+ const prefix = `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/`;
8040
+ if (!directoryUri.startsWith(prefix)) {
8041
+ return [directoryUri];
8028
8042
  }
8029
- return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
8043
+ const parts = directoryUri.slice(prefix.length).split("/").filter(Boolean);
8044
+ const chain = [];
8045
+ for (let index = 1; index <= parts.length; index += 1) {
8046
+ chain.push(`${prefix}${parts.slice(0, index).join("/")}`);
8047
+ }
8048
+ return chain;
8030
8049
  }
8031
- async function readTextIfExists(path) {
8032
- try {
8033
- const pathStat = await (0, import_promises4.stat)(path);
8034
- if (!pathStat.isFile()) {
8035
- return void 0;
8050
+ async function writeMemoryFile(config, ov, uri, content, initialMode, dryRun, options = {}) {
8051
+ if (dryRun) {
8052
+ const args = withIdentity(config, [
8053
+ "write",
8054
+ uri,
8055
+ "--from-file",
8056
+ "<staged temp file>",
8057
+ "--mode",
8058
+ initialMode,
8059
+ "--wait",
8060
+ "--timeout",
8061
+ "120"
8062
+ ]);
8063
+ if (options.quiet !== true) {
8064
+ console.log(`Would run: ${formatShellCommand(ov, args)}`);
8036
8065
  }
8037
- return await (0, import_promises4.readFile)(path, "utf8");
8038
- } catch (_err) {
8039
- return void 0;
8066
+ return;
8040
8067
  }
8041
- }
8042
- function sensitiveMemoryReason(text) {
8043
- const patterns = [
8044
- { name: "private key", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
8045
- { name: "API key", regex: /\bsk-[A-Za-z0-9_-]{16,}/ },
8046
- { name: "GitHub token", regex: /\bgh[pousr]_[A-Za-z0-9_]{16,}/ },
8047
- { name: "bearer token", regex: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/i },
8048
- { name: "AWS access key", regex: /\bAKIA[0-9A-Z]{16}\b/ }
8049
- ];
8050
- return patterns.find((pattern) => pattern.regex.test(text))?.name;
8051
- }
8052
- function comparableMemoryText(text) {
8053
- const trimmed = text.trim();
8054
- if (!trimmed.startsWith("MEMORY\n")) {
8055
- return trimmed;
8068
+ const stagingDir = await (0, import_promises4.mkdtemp)((0, import_node_path4.join)((0, import_node_os4.tmpdir)(), "threadnote-share-"));
8069
+ const tempPath = (0, import_node_path4.join)(stagingDir, "body.txt");
8070
+ try {
8071
+ await (0, import_promises4.writeFile)(tempPath, content, { encoding: "utf8", mode: 384 });
8072
+ await writeOvFileWithRetry(config, ov, uri, tempPath, initialMode, options);
8073
+ } finally {
8074
+ await (0, import_promises4.rm)(stagingDir, { force: true, recursive: true });
8056
8075
  }
8057
- const separatorIndex = trimmed.indexOf("\n\n");
8058
- return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 2).trim();
8059
- }
8060
- function legacySourceLabel(candidate) {
8061
- return `${candidate.sourceAccount}/${candidate.sourceSession}/${candidate.sourceArchive}`;
8062
- }
8063
- function localVikingDataRoot(config) {
8064
- return (0, import_node_path4.join)(config.agentContextHome, "data", "viking");
8065
- }
8066
- function localUserMemoriesRoot(config) {
8067
- return (0, import_node_path4.join)(localVikingDataRoot(config), config.account, "user", uriSegment(config.user), "memories");
8068
- }
8069
- function uniqueStrings(values) {
8070
- return [...new Set(values)].sort();
8071
8076
  }
8072
- function isResourceBusy(stderr, stdout) {
8073
- const output2 = `${stderr}
8074
- ${stdout}`.toLowerCase();
8075
- return output2.includes("resource is busy") || output2.includes("resource is being processed");
8076
- }
8077
- async function buildHandoff(options) {
8078
- const repoRoot = await gitValue(["rev-parse", "--show-toplevel"]) ?? getInvocationCwd();
8079
- const branch = await gitValue(["branch", "--show-current"], repoRoot) ?? "unknown";
8080
- const status = await gitValue(["status", "--short"], repoRoot) ?? "";
8081
- const diffStat = await gitValue(["diff", "--stat", "HEAD"], repoRoot) ?? "";
8082
- const touchedFiles = await gitTouchedFiles(repoRoot);
8083
- const repoName = (0, import_node_path4.basename)(repoRoot);
8084
- const metadata = {
8085
- kind: "handoff",
8086
- project: normalizeOptionalMetadata(options.project) ?? repoName,
8087
- sourceAgentClient: options.sourceAgentClient ?? "codex",
8088
- status: "active",
8089
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8090
- topic: normalizeOptionalMetadata(options.topic)
8091
- };
8092
- const bodyText = [
8093
- `repo: ${repoName}`,
8094
- `repo_path: ${repoRoot}`,
8095
- `branch: ${branch || "unknown"}`,
8096
- `task: ${options.task ?? "unspecified"}`,
8097
- "",
8098
- "files_touched:",
8099
- formatBlock(touchedFiles, "- none"),
8100
- "",
8101
- "git_status:",
8102
- formatBlock(status, "- clean"),
8103
- "",
8104
- "diff_stat:",
8105
- formatBlock(diffStat, "- none"),
8106
- "",
8107
- "tests:",
8108
- options.tests ?? "- not recorded",
8109
- "",
8110
- "blockers:",
8111
- options.blockers ?? "- none recorded",
8112
- "",
8113
- "next_step:",
8114
- options.nextStep ?? "- inspect the current repo state and continue from this handoff"
8115
- ].join("\n");
8116
- return { bodyText, metadata };
8117
- }
8118
- async function gitTouchedFiles(cwd) {
8119
- const changedFiles = await gitValue(["diff", "--name-only", "HEAD"], cwd);
8120
- const untrackedFiles = await gitValue(["ls-files", "--others", "--exclude-standard"], cwd);
8121
- const files = /* @__PURE__ */ new Set();
8122
- for (const value of [changedFiles, untrackedFiles]) {
8123
- for (const line of (value ?? "").split("\n")) {
8124
- const trimmed = line.trim();
8125
- if (trimmed) {
8126
- files.add(trimmed);
8077
+ async function writeOvFileWithRetry(config, ov, uri, fromFile, initialMode, options = {}) {
8078
+ const maxAttempts = 4;
8079
+ const existedBeforeWrite = await vikingResourceExists(ov, config, uri);
8080
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
8081
+ const existsNow = attempt === 0 ? existedBeforeWrite : await vikingResourceExists(ov, config, uri);
8082
+ const ourWriteLanded = existsNow && !existedBeforeWrite;
8083
+ const mode = attempt === 0 ? initialMode : ourWriteLanded ? "replace" : initialMode;
8084
+ const args = withIdentity(config, [
8085
+ "write",
8086
+ uri,
8087
+ "--from-file",
8088
+ fromFile,
8089
+ "--mode",
8090
+ mode,
8091
+ "--wait",
8092
+ "--timeout",
8093
+ "120"
8094
+ ]);
8095
+ if (options.quiet !== true) {
8096
+ console.log(`${attempt === 0 ? "Running" : "Retrying"}: ${formatShellCommand(ov, args)}`);
8097
+ }
8098
+ const result = await runCommand(ov, args, { allowFailure: true });
8099
+ if (result.exitCode === 0) {
8100
+ if (options.quiet !== true && result.stdout.trim()) {
8101
+ console.log(result.stdout.trim());
8102
+ }
8103
+ if (options.quiet !== true && result.stderr.trim()) {
8104
+ console.error(result.stderr.trim());
8105
+ }
8106
+ return;
8107
+ }
8108
+ if (isTransientOvFailure(result.stderr, result.stdout) && await vikingResourceExists(ov, config, uri) && !existedBeforeWrite) {
8109
+ if (options.quiet !== true) {
8110
+ console.log(
8111
+ "OpenViking accepted the write but returned an error before the wait completed; draining the queue."
8112
+ );
8127
8113
  }
8114
+ await waitForOvQueue(ov, config, options);
8115
+ return;
8116
+ }
8117
+ if (!isTransientOvFailure(result.stderr, result.stdout) || attempt === maxAttempts - 1) {
8118
+ throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
8128
8119
  }
8120
+ await sleep(1e3 * (attempt + 1));
8129
8121
  }
8130
- return [...files].sort().join("\n");
8131
8122
  }
8132
- function formatBlock(value, emptyValue) {
8133
- const trimmed = value.trim();
8134
- if (!trimmed) {
8135
- return emptyValue;
8123
+ async function waitForOvQueue(ov, config, options = {}) {
8124
+ const result = await runCommand(ov, withIdentity(config, ["wait", "--timeout", "120"]), { allowFailure: true });
8125
+ if (options.quiet !== true && result.stdout.trim()) {
8126
+ console.log(result.stdout.trim());
8127
+ }
8128
+ if (options.quiet !== true && result.stderr.trim()) {
8129
+ console.error(result.stderr.trim());
8136
8130
  }
8137
- return trimmed.split("\n").map((line) => `- ${line}`).join("\n");
8138
8131
  }
8139
-
8140
- // src/update-check.ts
8141
- var import_node_child_process2 = require("node:child_process");
8142
- var import_promises5 = require("node:fs/promises");
8143
- var import_node_path5 = require("node:path");
8144
- var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
8145
- var NPM_LATEST_URL = "https://registry.npmjs.org/threadnote/latest";
8146
- var FETCH_TIMEOUT_MS = 3e3;
8147
- async function checkForThreadnoteUpdate(args) {
8148
- if (args.currentVersion === "unknown") {
8149
- return void 0;
8132
+ function isTransientOvFailure(stderr, stdout) {
8133
+ const output2 = `${stderr}
8134
+ ${stdout}`.toLowerCase();
8135
+ return output2.includes("resource is busy") || output2.includes("resource is being processed") || output2.includes("network error") || output2.includes("error sending request") || output2.includes("http request failed") || output2.includes("connection refused") || output2.includes("connection reset") || output2.includes("timed out");
8136
+ }
8137
+ async function ingestSingleFile(ov, config, uri, filePath, initialMode, options = {}) {
8138
+ const content = await (0, import_promises4.readFile)(filePath, "utf8");
8139
+ await writeMemoryFile(config, ov, uri, content, initialMode, false, options);
8140
+ }
8141
+ async function removeWithRollback(config, ov, sourceUri, rollbackUri, worktree, dryRun, label) {
8142
+ try {
8143
+ await removeMemoryUri(config, ov, sourceUri, dryRun);
8144
+ } catch (sourceErr) {
8145
+ if (dryRun) {
8146
+ throw sourceErr;
8147
+ }
8148
+ console.error(
8149
+ `Source removal failed during ${label}; rolling back ${rollbackUri} so the system is back to the pre-${label} state.`
8150
+ );
8151
+ try {
8152
+ await removeMemoryUri(config, ov, rollbackUri, false);
8153
+ } catch (rollbackErr) {
8154
+ console.error(
8155
+ `Rollback of ${rollbackUri} also failed. Manual cleanup needed via: threadnote forget ${rollbackUri}
8156
+ Rollback error: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`
8157
+ );
8158
+ }
8159
+ await bestEffortRemoveWorktreeFile(rollbackUri, worktree, label);
8160
+ throw sourceErr;
8150
8161
  }
8151
- const cached = await readUpdateCache(args.cachePath);
8152
- if (cached && isCacheFresh(cached)) {
8153
- return compareVersions(args.currentVersion, cached.latestVersion);
8162
+ }
8163
+ async function bestEffortRemoveWorktreeFile(rollbackUri, worktree, label) {
8164
+ if (label !== "publish") {
8165
+ return;
8154
8166
  }
8155
- const fresh = await fetchLatestVersion();
8156
- if (fresh) {
8157
- await writeUpdateCache(args.cachePath, {
8158
- checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
8159
- latestVersion: fresh,
8160
- version: 1
8161
- });
8162
- return compareVersions(args.currentVersion, fresh);
8167
+ const prefix = "viking://";
8168
+ if (!rollbackUri.startsWith(prefix)) {
8169
+ return;
8163
8170
  }
8164
- if (cached) {
8165
- return compareVersions(args.currentVersion, cached.latestVersion);
8171
+ const parts = rollbackUri.slice(prefix.length).split("/");
8172
+ const sharedIndex = parts.indexOf("shared");
8173
+ if (sharedIndex === -1 || sharedIndex + 2 >= parts.length) {
8174
+ return;
8166
8175
  }
8167
- return void 0;
8176
+ const relative3 = parts.slice(sharedIndex + 2).join("/");
8177
+ if (!relative3) {
8178
+ return;
8179
+ }
8180
+ await (0, import_promises4.rm)((0, import_node_path4.join)(worktree, relative3), { force: true });
8168
8181
  }
8169
- function spawnDetachedAutoUpdate() {
8170
- try {
8171
- const entry = process.argv[1];
8172
- if (typeof entry !== "string" || entry.length === 0) {
8173
- return;
8182
+ async function removeMemoryUri(config, ov, uri, dryRun, options = {}) {
8183
+ const args = withIdentity(config, ["rm", uri]);
8184
+ if (dryRun) {
8185
+ if (options.quiet !== true) {
8186
+ console.log(`Would run: ${formatShellCommand(ov, args)}`);
8174
8187
  }
8175
- const child = (0, import_node_child_process2.spawn)(process.execPath, [entry, "update", "--yes"], {
8176
- detached: true,
8177
- stdio: "ignore"
8178
- });
8179
- child.unref();
8180
- } catch {
8188
+ return;
8181
8189
  }
8182
- }
8183
- function compareVersions(currentVersion, latestVersion) {
8184
- return {
8185
- currentVersion,
8186
- latestVersion,
8187
- outdated: isNewerVersion(latestVersion, currentVersion)
8188
- };
8189
- }
8190
- function isNewerVersion(candidate, baseline) {
8191
- const candidateParts = parseVersion(candidate);
8192
- const baselineParts = parseVersion(baseline);
8193
- for (let index = 0; index < 3; index += 1) {
8194
- if (candidateParts[index] !== baselineParts[index]) {
8195
- return candidateParts[index] > baselineParts[index];
8190
+ const maxAttempts = 4;
8191
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
8192
+ const result = await runCommand(ov, args, { allowFailure: true });
8193
+ if (result.exitCode === 0) {
8194
+ if (options.quiet !== true && result.stdout.trim()) {
8195
+ console.log(result.stdout.trim());
8196
+ }
8197
+ return;
8198
+ }
8199
+ if (!isTransientOvFailure(result.stderr, result.stdout) || attempt === maxAttempts - 1) {
8200
+ throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
8196
8201
  }
8202
+ await sleep(1e3 * (attempt + 1));
8197
8203
  }
8198
- return false;
8199
8204
  }
8200
- function parseVersion(value) {
8201
- const parts = value.split(".").map((part) => parseInt(part, 10));
8202
- return [parts[0] || 0, parts[1] || 0, parts[2] || 0];
8205
+ async function vikingResourceExists(ov, config, uri) {
8206
+ const result = await runCommand(ov, withIdentity(config, ["stat", uri]), { allowFailure: true });
8207
+ return result.exitCode === 0;
8203
8208
  }
8204
- function isCacheFresh(cache) {
8205
- const checkedAt = new Date(cache.checkedAt).getTime();
8206
- return Number.isFinite(checkedAt) && Date.now() - checkedAt < CACHE_TTL_MS;
8209
+ async function hasUncommittedChanges(worktree) {
8210
+ const result = await runCommand("git", ["-C", worktree, "status", "--porcelain"], { allowFailure: true });
8211
+ return result.stdout.trim().length > 0;
8207
8212
  }
8208
- async function readUpdateCache(cachePath) {
8209
- try {
8210
- const raw = await (0, import_promises5.readFile)(cachePath, "utf8");
8211
- const parsed = JSON.parse(raw);
8212
- if (parsed.version !== 1 || typeof parsed.latestVersion !== "string" || typeof parsed.checkedAt !== "string") {
8213
- return void 0;
8214
- }
8215
- return { checkedAt: parsed.checkedAt, latestVersion: parsed.latestVersion, version: 1 };
8216
- } catch {
8213
+ async function gitOutput(worktree, args, dryRun) {
8214
+ if (dryRun) {
8217
8215
  return void 0;
8218
8216
  }
8219
- }
8220
- async function writeUpdateCache(cachePath, contents) {
8221
- try {
8222
- await (0, import_promises5.mkdir)((0, import_node_path5.dirname)(cachePath), { recursive: true });
8223
- await (0, import_promises5.writeFile)(cachePath, `${JSON.stringify(contents)}
8224
- `, { encoding: "utf8", mode: 384 });
8225
- } catch {
8226
- }
8227
- }
8228
- async function fetchLatestVersion() {
8229
- try {
8230
- const response = await fetch(NPM_LATEST_URL, {
8231
- headers: { accept: "application/json" },
8232
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
8233
- });
8234
- if (!response.ok) {
8235
- return void 0;
8236
- }
8237
- const data = await response.json();
8238
- return typeof data.version === "string" && data.version.length > 0 ? data.version : void 0;
8239
- } catch {
8217
+ const result = await runCommand("git", ["-C", worktree, ...args], { allowFailure: true });
8218
+ if (result.exitCode !== 0) {
8240
8219
  return void 0;
8241
8220
  }
8221
+ return result.stdout.trim();
8242
8222
  }
8243
-
8244
- // src/version.ts
8245
- var import_node_fs4 = require("node:fs");
8246
- var import_node_path6 = require("node:path");
8247
- var cachedVersion;
8248
- function getThreadnoteVersion() {
8249
- if (cachedVersion !== void 0) {
8250
- return cachedVersion;
8223
+ async function listChangedFiles(worktree, beforeRev, afterRev) {
8224
+ const result = await runCommand("git", ["-C", worktree, "diff", "--name-status", "-z", `${beforeRev}..${afterRev}`], {
8225
+ allowFailure: true
8226
+ });
8227
+ if (result.exitCode !== 0) {
8228
+ return [];
8251
8229
  }
8252
- try {
8253
- const packageJsonPath = (0, import_node_path6.join)(__dirname, "..", "package.json");
8254
- const parsed = JSON.parse((0, import_node_fs4.readFileSync)(packageJsonPath, "utf8"));
8255
- cachedVersion = typeof parsed.version === "string" && parsed.version.length > 0 ? parsed.version : "unknown";
8256
- } catch {
8257
- cachedVersion = "unknown";
8258
- }
8259
- return cachedVersion;
8260
- }
8261
-
8262
- // src/hooks.ts
8263
- var MANAGED_HOOKS = [
8264
- {
8265
- event: "PreCompact",
8266
- command: HOOK_PRE_COMPACT_COMMAND,
8267
- description: "Auto-store a handoff snapshot before context compaction so the next turn can recall it."
8268
- },
8269
- {
8270
- event: "SessionStart",
8271
- command: HOOK_SESSION_START_COMMAND,
8272
- description: "Pre-load the latest handoff for the current repo into the new session context."
8273
- }
8274
- ];
8275
- async function runHooksInstall(config, agent, options) {
8276
- const apply = options.apply === true && options.dryRun !== true;
8277
- const remove = options.remove === true;
8278
- switch (agent) {
8279
- case "claude":
8280
- await runClaudeHooksInstall({ apply, remove });
8281
- return;
8282
- case "codex":
8283
- printCodexHooksNotice(remove);
8284
- return;
8285
- case "cursor":
8286
- printNoHooksSupported("cursor", remove);
8287
- return;
8288
- case "copilot":
8289
- printNoHooksSupported("copilot", remove);
8290
- return;
8291
- }
8292
- }
8293
- async function runClaudeHooksInstall(options) {
8294
- const path = expandPath(CLAUDE_SETTINGS_PATH);
8295
- const existingRaw = await exists(path) ? await (0, import_promises6.readFile)(path, "utf8") : "{}";
8296
- const parsed = parseJsonConfigObject(existingRaw) ?? {};
8297
- const next = options.remove ? withoutThreadnoteHooks(parsed) : withThreadnoteHooks(parsed);
8298
- const before = JSON.stringify(parsed);
8299
- const after = JSON.stringify(next);
8300
- if (before === after) {
8301
- console.log(`Claude hooks already ${options.remove ? "absent" : "managed"} in ${path}.`);
8302
- return;
8303
- }
8304
- console.log(`${options.apply ? "Updating" : "Would update"} ${path}:`);
8305
- for (const entry of MANAGED_HOOKS) {
8306
- console.log(` ${options.remove ? "-" : "+"} ${entry.event}: ${entry.command}`);
8307
- }
8308
- if (!options.apply) {
8309
- console.log("\nRe-run with --apply to actually modify the file.");
8310
- return;
8311
- }
8312
- await (0, import_promises6.mkdir)((0, import_node_path7.dirname)(path), { recursive: true });
8313
- const serialized = `${JSON.stringify(next, void 0, 2)}
8314
- `;
8315
- await (0, import_promises6.writeFile)(path, serialized, { encoding: "utf8", mode: 384 });
8316
- await (0, import_promises6.chmod)(path, 384);
8317
- console.log(`${options.remove ? "Removed" : "Installed"} threadnote-managed Claude hooks.`);
8318
- }
8319
- function withThreadnoteHooks(input2) {
8320
- const hooks = ensureMutableObject(input2.hooks);
8321
- for (const entry of MANAGED_HOOKS) {
8322
- const list = ensureMutableArray(hooks[entry.event]).filter((item) => !isManagedThreadnoteEntry(item));
8323
- list.push({
8324
- [THREADNOTE_HOOK_MARKER]: THREADNOTE_HOOK_MARKER_VALUE,
8325
- matcher: "",
8326
- hooks: [{ type: "command", command: entry.command }]
8327
- });
8328
- hooks[entry.event] = list;
8230
+ const entries = result.stdout.split("\0").filter((part) => part.length > 0);
8231
+ const changes = [];
8232
+ for (let index = 0; index < entries.length; ) {
8233
+ const raw = entries[index];
8234
+ const head = raw.slice(0, 1);
8235
+ if (head === "R" || head === "C") {
8236
+ const oldRel = entries[index + 1];
8237
+ const newRel = entries[index + 2];
8238
+ if (oldRel && newRel) {
8239
+ changes.push({ path: (0, import_node_path4.join)(worktree, oldRel), relativePath: oldRel, status: "removed" });
8240
+ changes.push({ path: (0, import_node_path4.join)(worktree, newRel), relativePath: newRel, status: "added" });
8241
+ }
8242
+ index += 3;
8243
+ continue;
8244
+ }
8245
+ const rel = entries[index + 1];
8246
+ if (rel) {
8247
+ const status = head === "A" ? "added" : head === "D" ? "removed" : "modified";
8248
+ changes.push({ path: (0, import_node_path4.join)(worktree, rel), relativePath: rel, status });
8249
+ }
8250
+ index += 2;
8329
8251
  }
8330
- return { ...input2, hooks };
8252
+ return changes;
8331
8253
  }
8332
- function withoutThreadnoteHooks(input2) {
8333
- if (!isJsonObject(input2.hooks)) {
8334
- return input2;
8335
- }
8336
- const hooks = {};
8337
- for (const [event, value] of Object.entries(input2.hooks)) {
8338
- if (!Array.isArray(value)) {
8339
- hooks[event] = value;
8254
+ async function applyChangesToOpenViking(config, team, changes, options = {}) {
8255
+ const ov = await openVikingCliForMode(false);
8256
+ for (const change of changes) {
8257
+ if (!change.relativePath.endsWith(".md")) {
8340
8258
  continue;
8341
8259
  }
8342
- const filtered = value.filter((item) => !isManagedThreadnoteEntry(item));
8343
- if (filtered.length > 0) {
8344
- hooks[event] = filtered;
8260
+ const firstSegment = change.relativePath.split("/")[0];
8261
+ if (!SHAREABLE_MEMORY_KIND_DIRS.includes(firstSegment)) {
8262
+ continue;
8345
8263
  }
8264
+ const uri = workfileToVikingUri(config, team, change.path);
8265
+ if (change.status === "removed") {
8266
+ await removeMemoryUri(config, ov, uri, false, options);
8267
+ continue;
8268
+ }
8269
+ if (!await isFile(change.path)) {
8270
+ continue;
8271
+ }
8272
+ const ovHasResource = await vikingResourceExists(ov, config, uri);
8273
+ if (ovHasResource) {
8274
+ const reason = change.status === "modified" ? "overwriting local with upstream (local edits to the shared subtree are not preserved across sync)" : "aligning OV to upstream (resource pre-existed in OV, likely from an earlier local publish or sync)";
8275
+ if (options.quiet !== true) {
8276
+ console.warn(`share sync: ${uri}: ${reason}.`);
8277
+ }
8278
+ }
8279
+ await ensureSharedDirectoryChain(config, ov, uri, false, options);
8280
+ const writeMode = ovHasResource ? "replace" : "create";
8281
+ await ingestSingleFile(ov, config, uri, change.path, writeMode, options);
8346
8282
  }
8347
- if (Object.keys(hooks).length === 0) {
8348
- const next = { ...input2 };
8349
- delete next.hooks;
8350
- return next;
8351
- }
8352
- return { ...input2, hooks };
8353
- }
8354
- function isManagedThreadnoteEntry(value) {
8355
- return isJsonObject(value) && value[THREADNOTE_HOOK_MARKER] === THREADNOTE_HOOK_MARKER_VALUE;
8356
- }
8357
- function ensureMutableObject(value) {
8358
- return isJsonObject(value) ? { ...value } : {};
8359
8283
  }
8360
- function ensureMutableArray(value) {
8361
- return Array.isArray(value) ? [...value] : [];
8284
+
8285
+ // src/memory.ts
8286
+ function parseMemoryKind(value) {
8287
+ if (["durable", "handoff", "incident", "preference", "smoke"].includes(value)) {
8288
+ return value;
8289
+ }
8290
+ throw new Error(`Unsupported memory kind "${value}". Expected durable, handoff, incident, preference, or smoke.`);
8362
8291
  }
8363
- function printCodexHooksNotice(remove) {
8364
- if (remove) {
8365
- console.log("Codex CLI does not expose a managed hook surface today, so there is nothing to remove.");
8366
- return;
8292
+ function parseMemoryStatus(value) {
8293
+ if (["active", "archived", "superseded"].includes(value)) {
8294
+ return value;
8367
8295
  }
8368
- console.log(
8369
- [
8370
- "Codex CLI does not currently expose lifecycle hooks (no PreCompact or SessionStart analog).",
8371
- "Threadnote already installs Codex user instructions at ~/.codex/AGENTS.md; that remains the active guidance surface.",
8372
- "If a future Codex release adds hook events, threadnote will pick them up via `install-hooks codex`."
8373
- ].join("\n")
8374
- );
8296
+ throw new Error(`Unsupported memory status "${value}". Expected active, archived, or superseded.`);
8375
8297
  }
8376
- function printNoHooksSupported(agent, remove) {
8377
- if (remove) {
8378
- console.log(`${agent} does not expose a hook surface; nothing to remove.`);
8379
- return;
8298
+ async function runRemember(config, options) {
8299
+ const text = await getInputText(options.text, options.stdin === true);
8300
+ if (!text.trim()) {
8301
+ throw new Error("Provide memory text with --text or --stdin.");
8380
8302
  }
8381
- console.log(
8382
- [
8383
- `${agent} does not expose agent-mode hooks today.`,
8384
- "Threadnote already installs user-level instructions for this agent; that remains the active guidance surface.",
8385
- "Hooks support will be added if the agent gains a hook surface upstream."
8386
- ].join("\n")
8387
- );
8303
+ const metadata = {
8304
+ kind: options.kind ?? "durable",
8305
+ project: normalizeOptionalMetadata(options.project),
8306
+ sourceAgentClient: options.sourceAgentClient ?? "codex",
8307
+ status: options.status ?? "active",
8308
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8309
+ topic: normalizeOptionalMetadata(options.topic)
8310
+ };
8311
+ await storeMemory(config, {
8312
+ bodyText: text.trim(),
8313
+ dryRun: options.dryRun === true,
8314
+ metadata,
8315
+ replaceUri: options.replace,
8316
+ title: "MEMORY"
8317
+ });
8388
8318
  }
8389
- async function hasManagedClaudeHooks() {
8390
- const path = expandPath(CLAUDE_SETTINGS_PATH);
8391
- if (!await exists(path)) {
8392
- return false;
8319
+ async function runMigrateMemories(config, options) {
8320
+ const dryRun = options.dryRun === true;
8321
+ const limit = options.limit ? parsePositiveInteger(options.limit, "migration limit") : void 0;
8322
+ const sourceAccounts = await legacySourceAccounts(config, options);
8323
+ if (sourceAccounts.length === 0) {
8324
+ console.log("No local OpenViking accounts found to scan.");
8325
+ return;
8393
8326
  }
8394
- const raw = await (0, import_promises6.readFile)(path, "utf8");
8395
- const parsed = parseJsonConfigObject(raw);
8396
- if (!parsed || !isJsonObject(parsed.hooks)) {
8397
- return false;
8327
+ const candidates = await legacyMemoryCandidates(config, sourceAccounts);
8328
+ const existingHashes = await existingDurableMemoryHashes(config);
8329
+ const ov = await openVikingCliForMode(dryRun);
8330
+ const migrationPath = (0, import_node_path5.join)(config.agentContextHome, "legacy-memory-migration.txt");
8331
+ let duplicateCount = 0;
8332
+ let migratedCount = 0;
8333
+ let sensitiveCount = 0;
8334
+ if (!dryRun && candidates.length > 0) {
8335
+ await ensureDurableMemoryDirectory(ov, config);
8398
8336
  }
8399
- for (const value of Object.values(parsed.hooks)) {
8400
- if (!Array.isArray(value)) {
8401
- continue;
8337
+ try {
8338
+ for (const candidate of candidates) {
8339
+ if (existingHashes.has(candidate.hash)) {
8340
+ duplicateCount += 1;
8341
+ continue;
8342
+ }
8343
+ if (existingHashes.has(candidate.comparableHash)) {
8344
+ duplicateCount += 1;
8345
+ continue;
8346
+ }
8347
+ const sensitiveReason = sensitiveMemoryReason(candidate.text);
8348
+ if (sensitiveReason) {
8349
+ sensitiveCount += 1;
8350
+ console.log(
8351
+ `SKIP ${legacySourceLabel(candidate)}: possible ${sensitiveReason}; inspect the source archive manually if needed.`
8352
+ );
8353
+ continue;
8354
+ }
8355
+ if (limit !== void 0 && migratedCount >= limit) {
8356
+ break;
8357
+ }
8358
+ const memoryUri = migratedDurableMemoryUri(config, candidate.hash);
8359
+ if (!dryRun && await vikingResourceExists2(ov, config, memoryUri)) {
8360
+ duplicateCount += 1;
8361
+ existingHashes.add(candidate.hash);
8362
+ continue;
8363
+ }
8364
+ console.log(`${dryRun ? "Would migrate" : "Migrating"} ${legacySourceLabel(candidate)} -> ${memoryUri}`);
8365
+ if (!dryRun) {
8366
+ await (0, import_promises5.writeFile)(migrationPath, candidate.text, { encoding: "utf8", mode: 384 });
8367
+ await (0, import_promises5.chmod)(migrationPath, 384);
8368
+ await writeDurableMemoryFile(ov, config, memoryUri, migrationPath, "create");
8369
+ existingHashes.add(candidate.hash);
8370
+ }
8371
+ migratedCount += 1;
8402
8372
  }
8403
- if (value.some((item) => isManagedThreadnoteEntry(item))) {
8404
- return true;
8373
+ } finally {
8374
+ if (!dryRun) {
8375
+ await (0, import_promises5.rm)(migrationPath, { force: true });
8405
8376
  }
8406
8377
  }
8407
- return false;
8408
- }
8409
- async function runPreCompactHook(config, options = {}) {
8410
- try {
8411
- const repoRoot = await gitValue(["rev-parse", "--show-toplevel"]);
8412
- const project = repoRoot ? (0, import_node_path7.basename)(repoRoot) : "general";
8413
- await runHandoff(config, {
8414
- blockers: "- none recorded",
8415
- dryRun: options.dryRun === true,
8416
- nextStep: "Continue from this auto-snapshot. A manual `threadnote handoff` will produce a richer write-up if you have more context.",
8417
- project,
8418
- sourceAgentClient: "claude",
8419
- task: "Auto-snapshot captured at Claude PreCompact (deterministic safety net before context compaction).",
8420
- tests: "- not recorded (auto-snapshot)",
8421
- topic: HOOK_AUTO_PRECOMPACT_TOPIC
8422
- });
8423
- } catch (err) {
8424
- process.stderr.write(
8425
- `threadnote pre-compact-hook: snapshot skipped (${err instanceof Error ? err.message : String(err)})
8426
- `
8427
- );
8428
- }
8429
- }
8430
- async function runSessionStartHook(config, options = {}) {
8431
- try {
8432
- const repoRoot = await gitValue(["rev-parse", "--show-toplevel"]);
8433
- if (!repoRoot) {
8434
- return;
8435
- }
8436
- const project = (0, import_node_path7.basename)(repoRoot);
8437
- await emitUpdateBannerIfOutdated(config);
8438
- process.stdout.write(`## Threadnote \u2014 latest context for ${project}
8439
-
8440
- `);
8441
- await runRecall(config, {
8442
- dryRun: options.dryRun === true,
8443
- inferScope: true,
8444
- nodeLimit: "5",
8445
- query: `${project} latest handoff durable feature memory`
8446
- });
8447
- } catch (err) {
8448
- process.stderr.write(
8449
- `threadnote session-start-hook: recall skipped (${err instanceof Error ? err.message : String(err)})
8450
- `
8451
- );
8452
- }
8453
- }
8454
- async function emitUpdateBannerIfOutdated(config) {
8455
- try {
8456
- const result = await checkForThreadnoteUpdate({
8457
- cachePath: (0, import_node_path7.join)(config.agentContextHome, ".update-state.json"),
8458
- currentVersion: getThreadnoteVersion()
8459
- });
8460
- if (!result || !result.outdated) {
8461
- return;
8462
- }
8463
- if (process.env.THREADNOTE_AUTO_UPDATE === "1") {
8464
- process.stdout.write(
8465
- `[threadnote] v${result.latestVersion} available (current v${result.currentVersion}). Auto-updating in the background; the new version takes effect next session.
8466
-
8467
- `
8468
- );
8469
- spawnDetachedAutoUpdate();
8470
- return;
8471
- }
8472
- process.stdout.write(
8473
- `[threadnote] v${result.latestVersion} available (current v${result.currentVersion}). Run: threadnote update
8474
-
8475
- `
8476
- );
8477
- } catch {
8478
- }
8378
+ console.log(
8379
+ [
8380
+ `Migration summary: ${migratedCount} ${dryRun ? "would be migrated" : "migrated"}`,
8381
+ `${duplicateCount} duplicate(s) skipped`,
8382
+ `${sensitiveCount} sensitive-looking item(s) skipped`,
8383
+ `${candidates.length} legacy Threadnote item(s) scanned`,
8384
+ `source account(s): ${sourceAccounts.join(", ")}`
8385
+ ].join("; ")
8386
+ );
8479
8387
  }
8480
-
8481
- // src/seeding.ts
8482
- var import_promises7 = require("node:fs/promises");
8483
- var import_node_path8 = require("node:path");
8484
- async function runSeed(config, options) {
8485
- const manifest = await readSeedManifest(config.manifestPath);
8486
- const ignorePatterns = await loadIgnorePatterns();
8487
- const ov = await openVikingCliForMode(options.dryRun === true);
8488
- const statePath = (0, import_node_path8.join)(config.agentContextHome, SEED_STATE_FILE);
8489
- const state = options.force === true ? { files: {}, version: 1 } : await readSeedState(statePath);
8490
- const projects = filterProjects(manifest.projects, options.only);
8491
- let importedCount = 0;
8388
+ async function runMigrateLifecycle(config, options) {
8389
+ const dryRun = options.dryRun === true || options.apply !== true;
8390
+ const limit = options.limit ? parsePositiveInteger(options.limit, "lifecycle migration limit") : void 0;
8391
+ const ov = await openVikingCliForMode(dryRun);
8392
+ const candidates = await legacyLifecycleHandoffCandidates(config);
8393
+ const migrationPath = (0, import_node_path5.join)(config.agentContextHome, "lifecycle-memory-migration.txt");
8394
+ let existingCount = 0;
8395
+ let migratedCount = 0;
8492
8396
  let skippedCount = 0;
8493
- let unchangedCount = 0;
8494
- for (const project of projects) {
8495
- const projectRoot = expandPath(project.path);
8496
- if (!await exists(projectRoot)) {
8497
- console.log(`WARN project missing: ${project.name} (${projectRoot})`);
8498
- continue;
8499
- }
8500
- const candidates = await collectSeedCandidates(project, projectRoot, ignorePatterns);
8397
+ try {
8501
8398
  for (const candidate of candidates) {
8502
- const fileStat = await statSeedFile(candidate.filePath);
8503
- const recorded = state.files[candidate.destinationUri];
8504
- if (fileStat && recorded && recorded.mtimeMs === fileStat.mtimeMs && recorded.size === fileStat.size) {
8505
- unchangedCount += 1;
8506
- continue;
8507
- }
8508
- const importPath = await prepareSeedFile(config, candidate, options.dryRun === true);
8509
- if (!importPath) {
8510
- skippedCount += 1;
8511
- continue;
8399
+ if (limit !== void 0 && migratedCount >= limit) {
8400
+ break;
8512
8401
  }
8513
- const args = withIdentity(config, ["add-resource", importPath, "--to", candidate.destinationUri, "--wait"]);
8514
- await maybeRun(options.dryRun === true, ov, args);
8515
- importedCount += 1;
8516
- if (fileStat && options.dryRun !== true) {
8517
- state.files[candidate.destinationUri] = { mtimeMs: fileStat.mtimeMs, size: fileStat.size };
8402
+ const destinationUri = lifecycleMigrationUri(config, candidate.metadata, sha256(candidate.original.trim()));
8403
+ const migratedMemory = formatMemoryDocument(
8404
+ "HANDOFF",
8405
+ candidate.metadata,
8406
+ ["Migrated legacy handoff from the historical events trail.", "", candidate.original.trim()].join("\n")
8407
+ );
8408
+ console.log(`${dryRun ? "Would migrate" : "Migrating"} ${candidate.sourceUri} -> ${destinationUri}`);
8409
+ if (!dryRun) {
8410
+ if (await vikingResourceExists2(ov, config, destinationUri)) {
8411
+ existingCount += 1;
8412
+ console.log(`Archived copy already exists; cleaning up legacy source: ${candidate.sourceUri}`);
8413
+ } else {
8414
+ await (0, import_promises5.writeFile)(migrationPath, migratedMemory, { encoding: "utf8", mode: 384 });
8415
+ await (0, import_promises5.chmod)(migrationPath, 384);
8416
+ await ensureMemoryDirectory(ov, config, memoryDirectoryUri(config, candidate.metadata));
8417
+ await writeDurableMemoryFile(ov, config, destinationUri, migrationPath, "create");
8418
+ }
8419
+ const removedOriginal = await removeVikingResourceWithRetry(ov, config, candidate.sourceUri);
8420
+ if (!removedOriginal) {
8421
+ console.error(
8422
+ `Migrated copy stored, but original is still processing. Retry later: threadnote forget ${candidate.sourceUri}`
8423
+ );
8424
+ skippedCount += 1;
8425
+ }
8518
8426
  }
8427
+ migratedCount += 1;
8428
+ }
8429
+ } finally {
8430
+ if (!dryRun) {
8431
+ await (0, import_promises5.rm)(migrationPath, { force: true });
8519
8432
  }
8520
- }
8521
- if (options.dryRun !== true) {
8522
- await writeSeedState(statePath, state);
8523
8433
  }
8524
8434
  console.log(
8525
- `Seed complete: ${importedCount} candidate(s), ${unchangedCount} unchanged, ${skippedCount} skipped for safety.`
8435
+ [
8436
+ `Lifecycle migration summary: ${migratedCount} clear legacy handoff(s) ${dryRun ? "would be migrated" : "migrated"}`,
8437
+ `${existingCount} existing archived copy/copies reused`,
8438
+ `${skippedCount} legacy source(s) still processing`,
8439
+ `${candidates.length} clear legacy handoff candidate(s) found`,
8440
+ dryRun ? "Run with --apply to perform this migration." : void 0
8441
+ ].filter((part) => part !== void 0).join("; ")
8526
8442
  );
8527
8443
  }
8528
- function filterProjects(projects, only) {
8529
- if (!only || only.length === 0) {
8530
- return projects;
8444
+ async function runRecall(config, options) {
8445
+ if (options.dryRun !== true) {
8446
+ await syncSharedReposAndLog(config);
8531
8447
  }
8532
- const known = new Set(projects.map((project) => project.name));
8533
- const missing = only.filter((name) => !known.has(name));
8534
- if (missing.length > 0) {
8535
- const all = [...known].join(", ");
8536
- throw new Error(`Unknown project(s) in --only: ${missing.join(", ")}. Manifest projects: ${all}`);
8448
+ const ov = await openVikingCliForMode(options.dryRun === true);
8449
+ const inferredUri = options.uri ?? (options.inferScope === false ? void 0 : await inferRecallUri(config, options.query));
8450
+ const args = ["search", options.query];
8451
+ if (inferredUri) {
8452
+ args.push("--uri", inferredUri);
8453
+ console.log(`Recall scope: ${inferredUri}`);
8537
8454
  }
8538
- const want = new Set(only);
8539
- return projects.filter((project) => want.has(project.name));
8455
+ if (options.nodeLimit) {
8456
+ args.push("--node-limit", String(parsePositiveInteger(options.nodeLimit, "node limit")));
8457
+ }
8458
+ await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
8459
+ await augmentRecallWithSeededResources(config, ov, options, inferredUri);
8460
+ await printExactMemoryMatches(config, ov, options.query, {
8461
+ dryRun: options.dryRun === true,
8462
+ includeArchived: options.includeArchived === true
8463
+ });
8540
8464
  }
8541
- async function statSeedFile(path) {
8542
- try {
8543
- const result = await (0, import_promises7.stat)(path);
8544
- return { mtimeMs: result.mtimeMs, size: result.size };
8545
- } catch (_err) {
8546
- return void 0;
8465
+ async function augmentRecallWithSeededResources(config, ov, options, inferredUri) {
8466
+ if (options.uri || options.inferScope === false) {
8467
+ return;
8468
+ }
8469
+ const project = await inferProjectFromQuery(config.manifestPath, options.query);
8470
+ if (!project) {
8471
+ return;
8472
+ }
8473
+ const projectResourceUri = trimTrailingSlash(project.uri);
8474
+ if (!projectResourceUri.startsWith("viking://") || projectResourceUri === inferredUri) {
8475
+ return;
8476
+ }
8477
+ const args = ["search", options.query, "--uri", projectResourceUri];
8478
+ if (options.nodeLimit) {
8479
+ args.push("--node-limit", String(parsePositiveInteger(options.nodeLimit, "node limit")));
8547
8480
  }
8481
+ console.log(`
8482
+ Also searching seeded resources: ${projectResourceUri}`);
8483
+ await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
8548
8484
  }
8549
- async function readSeedState(path) {
8485
+ async function runRead(config, uri, options) {
8486
+ assertVikingUri(uri);
8487
+ if (options.dryRun !== true) {
8488
+ await syncSharedReposAndLog(config);
8489
+ }
8490
+ const ov = await openVikingCliForMode(options.dryRun === true);
8491
+ const result = await maybeRun(options.dryRun === true, ov, withIdentity(config, ["read", uri]));
8492
+ if (result && result.stdout.includes("[Directory overview is not ready]") && (uri.endsWith("/.overview.md") || uri.endsWith("/.abstract.md"))) {
8493
+ const parentUri2 = parentVikingUri(uri);
8494
+ console.log("\nThis is a generated summary placeholder. To read the underlying content, inspect leaf nodes:");
8495
+ console.log(` threadnote list ${parentUri2} --all --recursive`);
8496
+ }
8497
+ }
8498
+ async function syncSharedReposAndLog(config) {
8550
8499
  try {
8551
- const raw = await (0, import_promises7.readFile)(path, "utf8");
8552
- const parsed = JSON.parse(raw);
8553
- if (parsed.version !== 1 || !isJsonObject(parsed.files)) {
8554
- return { files: {}, version: 1 };
8500
+ const syncResult = await syncSharedReposBeforeAgentRead(config);
8501
+ if (syncResult.syncedTeams.length > 0) {
8502
+ console.error(`Auto-synced shared memories: ${syncResult.syncedTeams.join(", ")}`);
8555
8503
  }
8556
- const files = {};
8557
- for (const [uri, entry] of Object.entries(parsed.files)) {
8558
- if (isJsonObject(entry) && typeof entry.mtimeMs === "number" && typeof entry.size === "number") {
8559
- files[uri] = { mtimeMs: entry.mtimeMs, size: entry.size };
8560
- }
8504
+ for (const warning of syncResult.warnings) {
8505
+ console.error(`Auto-sync warning: ${warning}`);
8561
8506
  }
8562
- return { files, version: 1 };
8563
- } catch (_err) {
8564
- return { files: {}, version: 1 };
8507
+ } catch (err) {
8508
+ console.error(`Auto-sync warning: ${err instanceof Error ? err.message : String(err)}`);
8565
8509
  }
8566
8510
  }
8567
- async function writeSeedState(path, state) {
8568
- await ensureDirectory((0, import_node_path8.dirname)(path), false);
8569
- await (0, import_promises7.writeFile)(path, `${JSON.stringify(state, void 0, 2)}
8570
- `, { encoding: "utf8", mode: 384 });
8571
- }
8572
- async function runInitManifest(config, options) {
8573
- const manifestPath = expandPath(
8574
- options.path ?? process.env.THREADNOTE_MANIFEST ?? (0, import_node_path8.join)(config.agentContextHome, USER_MANIFEST_NAME)
8575
- );
8576
- const repoInputs = options.repo && options.repo.length > 0 ? options.repo : [getInvocationCwd()];
8577
- const existingManifest = options.replace === true || !await exists(manifestPath) ? void 0 : await readSeedManifest(manifestPath);
8578
- const existingProjects = existingManifest?.projects ?? [];
8579
- const projects = [...existingProjects];
8580
- const seen = /* @__PURE__ */ new Set();
8581
- for (const project of existingProjects) {
8582
- seen.add(await projectIdentity(project.path));
8511
+ async function runList(config, uri, options) {
8512
+ assertVikingUri(uri);
8513
+ const ov = await openVikingCliForMode(options.dryRun === true);
8514
+ const args = ["ls", uri];
8515
+ if (options.all === true) {
8516
+ args.push("--all");
8583
8517
  }
8584
- for (const repoInput of repoInputs) {
8585
- const repoRoot = await resolveRepoRoot(repoInput);
8586
- const identity = await projectIdentity(repoRoot);
8587
- if (seen.has(identity)) {
8588
- console.log(`Already in manifest: ${repoRoot}`);
8589
- continue;
8590
- }
8591
- seen.add(identity);
8592
- projects.push(projectManifestForRepo(repoRoot, projects));
8518
+ if (options.recursive === true) {
8519
+ args.push("--recursive");
8593
8520
  }
8594
- const outputManifest = {
8595
- version: 1,
8596
- projects: projects.map((project) => ({
8597
- name: project.name,
8598
- path: project.path,
8599
- uri: project.uri,
8600
- seed: [...project.seed]
8601
- }))
8602
- };
8603
- if (existingManifest?.futureMonorepo) {
8604
- const futureMonorepoKey = "future_monorepo";
8605
- const pathCandidatesKey = "path_candidates";
8606
- outputManifest[futureMonorepoKey] = {
8607
- [pathCandidatesKey]: [...existingManifest.futureMonorepo.pathCandidates],
8608
- uri: existingManifest.futureMonorepo.uri
8609
- };
8521
+ if (options.simple === true) {
8522
+ args.push("--simple");
8610
8523
  }
8611
- const output2 = jsYaml.dump(outputManifest, { lineWidth: 120, noRefs: true });
8612
- if (options.dryRun === true) {
8613
- console.log(`# Would write ${manifestPath}`);
8614
- console.log(output2.trimEnd());
8615
- return;
8524
+ if (options.nodeLimit) {
8525
+ args.push("--node-limit", String(parsePositiveInteger(options.nodeLimit, "node limit")));
8616
8526
  }
8617
- await ensureDirectory((0, import_node_path8.dirname)(manifestPath), false);
8618
- await (0, import_promises7.writeFile)(manifestPath, output2, { encoding: "utf8", mode: 384 });
8619
- await (0, import_promises7.chmod)(manifestPath, 384);
8620
- console.log(`Wrote manifest: ${manifestPath}`);
8621
- console.log("Seed with:");
8622
- console.log(" threadnote seed --dry-run");
8623
- console.log(" threadnote seed");
8527
+ await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
8624
8528
  }
8625
- async function runSeedSkills(config, options) {
8529
+ async function runHandoff(config, options) {
8530
+ const { bodyText, metadata } = await buildHandoff(options);
8531
+ await storeMemory(config, {
8532
+ bodyText,
8533
+ dryRun: options.dryRun === true,
8534
+ metadata,
8535
+ replaceUri: options.replace,
8536
+ title: "HANDOFF"
8537
+ });
8538
+ }
8539
+ async function runArchive(config, uri, options) {
8540
+ assertVikingUri(uri);
8626
8541
  const ov = await openVikingCliForMode(options.dryRun === true);
8627
- const skills = await collectSkillCandidates(config);
8628
- const nativeMode = options.native === true;
8629
- console.log(
8630
- nativeMode ? "Skill seed mode: native OpenViking skills. This requires a working VLM config." : "Skill seed mode: resource catalog. Use --native only after configuring a working VLM provider."
8631
- );
8632
- for (const skill of skills) {
8633
- console.log(`Skill ${skill.source}: ${skill.filePath}`);
8634
- const args = nativeMode ? ["add-skill", skill.filePath, "--wait"] : ["add-resource", skill.filePath, "--to", skillResourceUri(skill), "--wait"];
8635
- await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
8542
+ const readResult = await maybeRun(options.dryRun === true, ov, withIdentity(config, ["read", uri]));
8543
+ const original = readResult?.stdout.trim();
8544
+ if (options.dryRun === true) {
8545
+ const fallbackMetadata = {
8546
+ archivedFrom: uri,
8547
+ kind: options.kind ?? "handoff",
8548
+ project: normalizeOptionalMetadata(options.project),
8549
+ sourceAgentClient: "threadnote",
8550
+ status: "archived",
8551
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8552
+ topic: normalizeOptionalMetadata(options.topic)
8553
+ };
8554
+ await storeMemory(config, {
8555
+ bodyText: ["Archived original Threadnote memory.", "", "<original memory content would be read here>"].join("\n"),
8556
+ dryRun: true,
8557
+ metadata: fallbackMetadata,
8558
+ title: "MEMORY"
8559
+ });
8560
+ console.log(formatShellCommand(ov, withIdentity(config, ["rm", uri])));
8561
+ return;
8636
8562
  }
8637
- console.log(`Skill seed complete: ${skills.length} unique skill(s).`);
8638
- }
8639
- async function resolveRepoRoot(repoInput) {
8640
- const inputPath = expandPath(repoInput);
8641
- if (!await isDirectory(inputPath)) {
8642
- throw new Error(`Repo path is not a directory: ${inputPath}`);
8563
+ if (!original) {
8564
+ throw new Error(`Could not read ${uri} before archiving.`);
8643
8565
  }
8644
- return await gitValue(["rev-parse", "--show-toplevel"], inputPath) ?? inputPath;
8645
- }
8646
- async function projectIdentity(path) {
8647
- const expanded = expandPath(path);
8648
- try {
8649
- return await (0, import_promises7.realpath)(expanded);
8650
- } catch (_err) {
8651
- return expanded;
8566
+ const inferredMetadata = inferMemoryMetadata(original);
8567
+ const metadata = {
8568
+ archivedFrom: uri,
8569
+ kind: options.kind ?? inferredMetadata.kind ?? "handoff",
8570
+ project: normalizeOptionalMetadata(options.project) ?? inferredMetadata.project,
8571
+ sourceAgentClient: "threadnote",
8572
+ status: "archived",
8573
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8574
+ topic: normalizeOptionalMetadata(options.topic) ?? inferredMetadata.topic
8575
+ };
8576
+ await storeMemory(config, {
8577
+ bodyText: ["Archived original Threadnote memory.", "", original].join("\n"),
8578
+ dryRun: false,
8579
+ metadata,
8580
+ title: "MEMORY"
8581
+ });
8582
+ const removedOriginal = await removeVikingResourceWithRetry(ov, config, uri);
8583
+ if (removedOriginal) {
8584
+ console.log(`Archived original memory: ${uri}`);
8585
+ } else {
8586
+ console.error(`Archive stored, but original memory is still processing. Retry later: threadnote forget ${uri}`);
8652
8587
  }
8653
8588
  }
8654
- function projectManifestForRepo(repoRoot, existingProjects) {
8655
- const baseName = uriSegment((0, import_node_path8.basename)(repoRoot));
8656
- const usedNames = new Set(existingProjects.map((project) => project.name));
8657
- const usedUris = new Set(existingProjects.map((project) => project.uri));
8658
- let name = baseName;
8659
- let uri = `viking://resources/repos/${name}`;
8660
- if (usedNames.has(name) || usedUris.has(uri)) {
8661
- name = `${baseName}-${sha256(repoRoot).slice(0, 8)}`;
8662
- uri = `viking://resources/repos/${name}`;
8589
+ async function runForget(config, uri, options) {
8590
+ assertVikingUri(uri);
8591
+ const ov = await openVikingCliForMode(options.dryRun === true);
8592
+ if (options.dryRun === true) {
8593
+ await maybeRun(true, ov, withIdentity(config, ["rm", uri]));
8594
+ return;
8663
8595
  }
8664
- return {
8665
- name,
8666
- path: portablePath(repoRoot),
8667
- seed: DEFAULT_SEED_PATTERNS,
8668
- uri
8669
- };
8670
- }
8671
- async function collectSeedCandidates(project, projectRoot, ignorePatterns) {
8672
- const candidates = [];
8673
- const seen = /* @__PURE__ */ new Set();
8674
- for (const pattern of project.seed) {
8675
- const files = await resolveProjectPattern(projectRoot, pattern);
8676
- for (const filePath of files) {
8677
- const relativePath = toPosixPath((0, import_node_path8.relative)(projectRoot, filePath));
8678
- if (seen.has(relativePath) || matchesIgnore(relativePath, ignorePatterns)) {
8679
- continue;
8680
- }
8681
- seen.add(relativePath);
8682
- candidates.push({
8683
- destinationUri: `${trimTrailingSlash(project.uri)}/${relativePath}`,
8684
- filePath,
8685
- projectName: project.name,
8686
- relativePath
8687
- });
8688
- }
8596
+ const removed = await removeVikingResourceWithRetry(ov, config, uri);
8597
+ if (!removed) {
8598
+ throw new Error(`Resource is still being processed; retry later: threadnote forget ${uri}`);
8689
8599
  }
8690
- return candidates;
8691
8600
  }
8692
- async function resolveProjectPattern(projectRoot, pattern) {
8693
- const normalizedPattern = toPosixPath(pattern);
8694
- if (!hasGlob(normalizedPattern)) {
8695
- const filePath = (0, import_node_path8.join)(projectRoot, normalizedPattern);
8696
- return await isFile(filePath) ? [filePath] : [];
8697
- }
8698
- const globBase = getGlobBase(normalizedPattern);
8699
- const basePath = (0, import_node_path8.join)(projectRoot, globBase);
8700
- if (!await exists(basePath)) {
8701
- return [];
8601
+ async function runExportPack(config, options) {
8602
+ const ov = await openVikingCliForMode(options.dryRun === true);
8603
+ const defaultPath = (0, import_node_path5.join)(config.agentContextHome, `threadnote-${safeTimestamp()}.ovpack`);
8604
+ const outputPath = expandPath(options.path ?? defaultPath);
8605
+ await maybeRun(options.dryRun === true, ov, withIdentity(config, ["export", options.uri ?? "viking://", outputPath]));
8606
+ }
8607
+ async function runImportPack(config, options) {
8608
+ if (!options.path) {
8609
+ throw new Error("Provide --path for import-pack.");
8702
8610
  }
8703
- const regex = globToRegExp(normalizedPattern);
8704
- const files = await walkFiles(basePath);
8705
- return files.filter((filePath) => regex.test(toPosixPath((0, import_node_path8.relative)(projectRoot, filePath))));
8611
+ const ov = await openVikingCliForMode(options.dryRun === true);
8612
+ await maybeRun(
8613
+ options.dryRun === true,
8614
+ ov,
8615
+ withIdentity(config, ["import", expandPath(options.path), options.targetUri ?? "viking://"])
8616
+ );
8706
8617
  }
8707
- async function prepareSeedFile(config, candidate, dryRun) {
8708
- const content = await (0, import_promises7.readFile)(candidate.filePath, "utf8");
8709
- const redactedContent = shouldRedactPath(candidate.relativePath) ? redactContent(candidate.relativePath, content) : content;
8710
- const secretMatches = detectSecretMatches(redactedContent);
8711
- if (secretMatches.length > 0) {
8712
- console.log(
8713
- `SKIP ${candidate.projectName}/${candidate.relativePath}: possible secret (${secretMatches.slice(0, MAX_SECRET_MATCHES_TO_PRINT).join(", ")})`
8714
- );
8618
+ async function inferRecallUri(config, query) {
8619
+ if (!/\bskills?\b/.test(query.toLowerCase())) {
8715
8620
  return void 0;
8716
8621
  }
8717
- if (redactedContent === content) {
8718
- return candidate.filePath;
8719
- }
8720
- const redactedPath = (0, import_node_path8.join)(config.agentContextHome, "redacted", candidate.projectName, candidate.relativePath);
8721
- if (dryRun) {
8722
- console.log(`Would write redacted copy: ${redactedPath}`);
8723
- return redactedPath;
8724
- }
8725
- await ensureDirectory((0, import_node_path8.dirname)(redactedPath), false);
8726
- await (0, import_promises7.writeFile)(redactedPath, redactedContent, { encoding: "utf8", mode: 384 });
8727
- await (0, import_promises7.chmod)(redactedPath, 384);
8728
- return redactedPath;
8622
+ const project = await inferProjectFromQuery(config.manifestPath, query);
8623
+ return project ? `viking://resources/agent-skills/repo-local-${uriSegment(project.name)}` : "viking://resources/agent-skills";
8729
8624
  }
8730
- async function collectSkillCandidates(config) {
8731
- const sources = [
8732
- { pattern: "~/.codex/skills/**/SKILL.md", source: "codex-global" },
8733
- { pattern: "~/.codex/plugins/cache/**/skills/**/SKILL.md", source: "codex-plugin-cache" },
8734
- { pattern: "~/.claude/skills/**/SKILL.md", source: "claude-global" }
8735
- ];
8736
- try {
8737
- const manifest = await readSeedManifest(config.manifestPath);
8738
- for (const project of manifest.projects) {
8739
- sources.push({
8740
- pattern: `${project.path}/.claude/skills/**/SKILL.md`,
8741
- source: `repo-local:${project.name}`
8742
- });
8743
- }
8744
- } catch (err) {
8745
- console.log(`WARN cannot read manifest for repo-local skill discovery: ${errorMessage(err)}`);
8625
+ async function printExactMemoryMatches(config, ov, query, options) {
8626
+ const terms = exactRecallTerms(query);
8627
+ if (terms.length === 0) {
8628
+ return;
8746
8629
  }
8747
- const seenHashes = /* @__PURE__ */ new Set();
8748
- const skills = [];
8749
- for (const source of sources) {
8750
- const files = await resolveAbsolutePattern(expandPath(source.pattern));
8751
- for (const filePath of files) {
8752
- const content = await (0, import_promises7.readFile)(filePath, "utf8");
8753
- const matches = detectSecretMatches(content);
8754
- if (matches.length > 0) {
8755
- console.log(`SKIP skill with possible secret: ${filePath}`);
8630
+ const scopes = exactMemoryScopes(config, options.includeArchived);
8631
+ const outputs = [];
8632
+ for (const term of terms) {
8633
+ for (const scope of scopes) {
8634
+ const args = withIdentity(config, ["grep", term, "--uri", scope, "--node-limit", "5"]);
8635
+ if (options.dryRun) {
8636
+ outputs.push(formatShellCommand(ov, args));
8756
8637
  continue;
8757
8638
  }
8758
- const hash = sha256(content);
8759
- if (seenHashes.has(hash)) {
8760
- continue;
8639
+ const result = await runCommand(ov, args, { allowFailure: true });
8640
+ const output2 = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join("\n");
8641
+ if (result.exitCode === 0 && grepOutputHasMatches(output2)) {
8642
+ outputs.push(output2);
8761
8643
  }
8762
- seenHashes.add(hash);
8763
- skills.push({ filePath, hash, source: source.source });
8764
8644
  }
8765
8645
  }
8766
- return skills;
8767
- }
8768
- async function resolveAbsolutePattern(pattern) {
8769
- const normalizedPattern = toPosixPath(pattern);
8770
- if (!hasGlob(normalizedPattern)) {
8771
- return await isFile(normalizedPattern) ? [normalizedPattern] : [];
8772
- }
8773
- const globBase = getGlobBase(normalizedPattern);
8774
- const basePath = globBase.startsWith("/") ? globBase : `/${globBase}`;
8775
- if (!await exists(basePath)) {
8776
- return [];
8646
+ if (outputs.length === 0) {
8647
+ return;
8777
8648
  }
8778
- const regex = globToRegExp(normalizedPattern);
8779
- const files = await walkFiles(basePath);
8780
- return files.filter((filePath) => regex.test(toPosixPath(filePath)));
8781
- }
8782
- function skillResourceUri(skill) {
8783
- return `viking://resources/agent-skills/${uriSegment(skill.source)}/${uriSegment((0, import_node_path8.basename)((0, import_node_path8.dirname)(skill.filePath)))}-${skill.hash.slice(0, 12)}.md`;
8649
+ console.log("\nExact durable memory matches:");
8650
+ console.log(outputs.join("\n\n"));
8784
8651
  }
8785
- async function loadIgnorePatterns() {
8786
- const raw = await (0, import_promises7.readFile)((0, import_node_path8.join)(toolRoot(), ".threadnoteignore"), "utf8");
8787
- return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
8652
+ async function storeMemory(config, options) {
8653
+ if (options.replaceUri) {
8654
+ assertVikingUri(options.replaceUri);
8655
+ }
8656
+ const ov = await openVikingCliForMode(options.dryRun);
8657
+ const memoryPath = (0, import_node_path5.join)(config.agentContextHome, "last-memory.txt");
8658
+ const candidateMetadata = { ...options.metadata, supersedes: options.replaceUri };
8659
+ const candidateMemory = formatMemoryDocument(options.title, candidateMetadata, options.bodyText);
8660
+ const memoryUri = memoryUriFor(config, candidateMemory, candidateMetadata);
8661
+ const isInPlaceUpdate = options.replaceUri !== void 0 && options.replaceUri === memoryUri;
8662
+ const finalMetadata = isInPlaceUpdate ? { ...options.metadata, supersedes: void 0 } : candidateMetadata;
8663
+ const memory = isInPlaceUpdate ? formatMemoryDocument(options.title, finalMetadata, options.bodyText) : candidateMemory;
8664
+ const writeMode = await memoryWriteMode(ov, config, memoryUri, finalMetadata);
8665
+ if (options.dryRun) {
8666
+ console.log(memory);
8667
+ console.log("\nWould run:");
8668
+ console.log(
8669
+ formatShellCommand(
8670
+ ov,
8671
+ withIdentity(config, [
8672
+ "write",
8673
+ memoryUri,
8674
+ "--from-file",
8675
+ memoryPath,
8676
+ "--mode",
8677
+ writeMode,
8678
+ "--wait",
8679
+ "--timeout",
8680
+ "120"
8681
+ ])
8682
+ )
8683
+ );
8684
+ if (options.replaceUri && !isInPlaceUpdate) {
8685
+ console.log(formatShellCommand(ov, withIdentity(config, ["rm", options.replaceUri])));
8686
+ }
8687
+ return;
8688
+ }
8689
+ await (0, import_promises5.writeFile)(memoryPath, memory, { encoding: "utf8", mode: 384 });
8690
+ await (0, import_promises5.chmod)(memoryPath, 384);
8691
+ await ensureMemoryDirectory(ov, config, memoryDirectoryUri(config, finalMetadata));
8692
+ await writeDurableMemoryFile(ov, config, memoryUri, memoryPath, writeMode);
8693
+ console.log(`Stored memory: ${memoryUri}`);
8694
+ if (options.replaceUri && !isInPlaceUpdate) {
8695
+ const removedReplacedMemory = await removeVikingResourceWithRetry(ov, config, options.replaceUri);
8696
+ if (removedReplacedMemory) {
8697
+ console.log(`Forgot replaced memory: ${options.replaceUri}`);
8698
+ } else {
8699
+ console.error(
8700
+ `Replacement stored, but the superseded memory is still processing. Retry later: threadnote forget ${options.replaceUri}`
8701
+ );
8702
+ }
8703
+ } else if (isInPlaceUpdate) {
8704
+ console.log(`Updated existing memory in place: ${memoryUri}`);
8705
+ }
8788
8706
  }
8789
- function matchesIgnore(relativePath, patterns) {
8790
- const path = toPosixPath(relativePath);
8791
- for (const pattern of patterns) {
8792
- const normalizedPattern = toPosixPath(pattern);
8793
- if (normalizedPattern.endsWith("/")) {
8794
- const directory = normalizedPattern.slice(0, -1);
8795
- if (path === directory || path.includes(`/${directory}/`) || path.startsWith(`${directory}/`)) {
8796
- return true;
8707
+ async function writeDurableMemoryFile(ov, config, memoryUri, memoryPath, writeMode) {
8708
+ const args = withIdentity(config, [
8709
+ "write",
8710
+ memoryUri,
8711
+ "--from-file",
8712
+ memoryPath,
8713
+ "--mode",
8714
+ writeMode,
8715
+ "--wait",
8716
+ "--timeout",
8717
+ "120"
8718
+ ]);
8719
+ for (let attempt = 0; attempt < 4; attempt += 1) {
8720
+ console.log(`${attempt === 0 ? "Running" : "Retrying"}: ${formatShellCommand(ov, args)}`);
8721
+ const result = await runCommand(ov, args, { allowFailure: true });
8722
+ if (result.exitCode === 0) {
8723
+ if (result.stdout.trim()) {
8724
+ console.log(result.stdout.trim());
8797
8725
  }
8798
- continue;
8726
+ if (result.stderr.trim()) {
8727
+ console.error(result.stderr.trim());
8728
+ }
8729
+ return;
8799
8730
  }
8800
- if (globToRegExp(normalizedPattern).test(path) || globToRegExp(`**/${normalizedPattern}`).test(path)) {
8731
+ if (await vikingResourceExists2(ov, config, memoryUri)) {
8732
+ console.log("OpenViking accepted the memory but returned before the wait completed; waiting for indexing.");
8733
+ await waitForOpenVikingQueue(ov, config);
8734
+ return;
8735
+ }
8736
+ if (!isResourceBusy(result.stderr, result.stdout) || attempt === 3) {
8737
+ throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
8738
+ }
8739
+ await sleep(1e3 * (attempt + 1));
8740
+ }
8741
+ }
8742
+ async function waitForOpenVikingQueue(ov, config) {
8743
+ const result = await runCommand(ov, withIdentity(config, ["wait", "--timeout", "120"]), { allowFailure: true });
8744
+ if (result.stdout.trim()) {
8745
+ console.log(result.stdout.trim());
8746
+ }
8747
+ if (result.stderr.trim()) {
8748
+ console.error(result.stderr.trim());
8749
+ }
8750
+ }
8751
+ async function removeVikingResourceWithRetry(ov, config, uri) {
8752
+ const args = withIdentity(config, ["rm", uri]);
8753
+ for (let attempt = 0; attempt < 4; attempt += 1) {
8754
+ console.log(`${attempt === 0 ? "Running" : "Retrying"}: ${formatShellCommand(ov, args)}`);
8755
+ const result = await runCommand(ov, args, { allowFailure: true });
8756
+ if (result.exitCode === 0) {
8757
+ if (result.stdout.trim()) {
8758
+ console.log(result.stdout.trim());
8759
+ }
8760
+ if (result.stderr.trim()) {
8761
+ console.error(result.stderr.trim());
8762
+ }
8801
8763
  return true;
8802
8764
  }
8765
+ if (isResourceBusy(result.stderr, result.stdout) && attempt === 3) {
8766
+ return false;
8767
+ }
8768
+ if (!isResourceBusy(result.stderr, result.stdout)) {
8769
+ throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
8770
+ }
8771
+ await sleep(1e3 * (attempt + 1));
8803
8772
  }
8804
8773
  return false;
8805
8774
  }
8806
- function shouldRedactPath(relativePath) {
8807
- const path = toPosixPath(relativePath);
8808
- return path.endsWith(".mcp.json") || path.endsWith("config.toml") || path.includes("/settings") || path.includes("/settings.local");
8775
+ async function vikingResourceExists2(ov, config, uri) {
8776
+ const stat4 = await runCommand(ov, withIdentity(config, ["stat", uri]), { allowFailure: true });
8777
+ return stat4.exitCode === 0;
8809
8778
  }
8810
- function redactContent(relativePath, content) {
8811
- if (relativePath.endsWith(".json")) {
8812
- try {
8813
- const parsed = JSON.parse(content);
8814
- return `${JSON.stringify(redactJsonValue(parsed), null, 2)}
8815
- `;
8816
- } catch (_err) {
8817
- return redactText(content);
8779
+ async function ensureDurableMemoryDirectory(ov, config) {
8780
+ await ensureMemoryDirectory(ov, config, durableMemoryDirectoryUri(config));
8781
+ }
8782
+ async function ensureMemoryDirectory(ov, config, directoryUri) {
8783
+ for (const uri of vikingDirectoryChain(directoryUri)) {
8784
+ const statResult = await runCommand(ov, withIdentity(config, ["stat", uri]), { allowFailure: true });
8785
+ if (statResult.exitCode === 0) {
8786
+ continue;
8818
8787
  }
8788
+ await maybeRun(
8789
+ false,
8790
+ ov,
8791
+ withIdentity(config, ["mkdir", uri, "--description", "Threadnote lifecycle-aware local memories."])
8792
+ );
8819
8793
  }
8820
- return redactText(content);
8821
8794
  }
8822
- function redactJsonValue(value) {
8823
- if (Array.isArray(value)) {
8824
- return value.map((item) => redactJsonValue(item));
8825
- }
8826
- if (!isJsonObject(value)) {
8827
- return value;
8795
+ function durableMemoryDirectoryUri(config) {
8796
+ return `viking://user/${uriSegment(config.user)}/memories/events`;
8797
+ }
8798
+ function migratedDurableMemoryUri(config, hash) {
8799
+ return `${durableMemoryDirectoryUri(config)}/threadnote-migrated-${hash.slice(0, 16)}.md`;
8800
+ }
8801
+ async function hasLegacyLifecycleHandoffCandidates(config) {
8802
+ return (await legacyLifecycleHandoffCandidates(config, 1)).length > 0;
8803
+ }
8804
+ async function legacyLifecycleHandoffCandidates(config, limit) {
8805
+ const eventsRoot = (0, import_node_path5.join)(localUserMemoriesRoot(config), "events");
8806
+ let entries;
8807
+ try {
8808
+ entries = await (0, import_promises5.readdir)(eventsRoot, { withFileTypes: true });
8809
+ } catch (_err) {
8810
+ return [];
8828
8811
  }
8829
- const output2 = {};
8830
- for (const [key, nestedValue] of Object.entries(value)) {
8831
- output2[key] = isSensitiveKey(key) ? "[REDACTED]" : redactJsonValue(nestedValue);
8812
+ const candidates = [];
8813
+ for (const entry of entries) {
8814
+ if (!entry.isFile() || entry.name.startsWith(".") || !entry.name.endsWith(".md")) {
8815
+ continue;
8816
+ }
8817
+ const sourcePath = (0, import_node_path5.join)(eventsRoot, entry.name);
8818
+ const original = await readTextIfExists(sourcePath);
8819
+ if (!original || !isClearLegacyHandoffMemory(original) || sensitiveMemoryReason(original)) {
8820
+ continue;
8821
+ }
8822
+ const sourceUri = `${durableMemoryDirectoryUri(config)}/${entry.name}`;
8823
+ candidates.push({
8824
+ metadata: {
8825
+ archivedFrom: sourceUri,
8826
+ kind: "handoff",
8827
+ project: inferLegacyProject(original),
8828
+ sourceAgentClient: "threadnote",
8829
+ status: "archived",
8830
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
8831
+ },
8832
+ original,
8833
+ sourceUri
8834
+ });
8835
+ if (limit !== void 0 && candidates.length >= limit) {
8836
+ break;
8837
+ }
8832
8838
  }
8833
- return output2;
8839
+ return candidates;
8834
8840
  }
8835
- function isSensitiveKey(key) {
8836
- return /token|secret|password|credential|authorization|api[_-]?key|client[_-]?secret|bearer/i.test(key);
8841
+ function lifecycleMigrationUri(config, metadata, hash) {
8842
+ return `${memoryDirectoryUri(config, metadata)}/legacy-${hash.slice(0, 16)}.md`;
8837
8843
  }
8838
- function detectSecretMatches(content) {
8839
- const detectors = [
8840
- { label: "private-key", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
8841
- { label: "openai-key", regex: /sk-[A-Za-z0-9_-]{24,}/ },
8842
- { label: "github-token", regex: /gh[pousr]_[A-Za-z0-9_]{24,}/ },
8843
- { label: "slack-token", regex: /xox[abprs]-[A-Za-z0-9-]{24,}/ },
8844
- { label: "bearer-token", regex: /Bearer\s+[A-Za-z0-9._~+/=-]{24,}/i },
8845
- { label: "aws-access-key", regex: /AKIA[0-9A-Z]{16}/ }
8844
+ function exactMemoryScopes(config, includeArchived) {
8845
+ const userBase = `viking://user/${uriSegment(config.user)}/memories`;
8846
+ const scopes = [
8847
+ `${userBase}/preferences`,
8848
+ `${userBase}/durable/projects`,
8849
+ `${userBase}/handoffs/active`,
8850
+ `${userBase}/incidents/active`,
8851
+ `${userBase}/events`,
8852
+ `${userBase}/shared`,
8853
+ `viking://agent/${uriSegment(config.agentId)}/memories`,
8854
+ // Seeded project resources (READMEs, AGENTS.md, SKILL.md, docs/**) live
8855
+ // under viking://resources/repos/<project>. Include them so an exact-term
8856
+ // grep in a recall surfaces matches in seeded guidance, not only memories.
8857
+ "viking://resources/repos"
8846
8858
  ];
8847
- const matches = [];
8848
- for (const detector of detectors) {
8849
- if (detector.regex.test(content)) {
8850
- matches.push(detector.label);
8851
- }
8859
+ return includeArchived ? [...scopes, `${userBase}/durable/archived`, `${userBase}/handoffs/archived`, `${userBase}/incidents/archived`] : scopes;
8860
+ }
8861
+ function memoryUriFor(config, memory, metadata) {
8862
+ const filename = shouldUseStableMemoryUri(metadata) ? `${uriSegment(metadata.topic ?? "current")}.md` : `threadnote-${safeTimestamp()}-${sha256(memory).slice(0, 12)}.md`;
8863
+ return `${memoryDirectoryUri(config, metadata)}/${filename}`;
8864
+ }
8865
+ function memoryDirectoryUri(config, metadata) {
8866
+ const baseUri = `viking://user/${uriSegment(config.user)}/memories`;
8867
+ const projectSegment = uriSegment(metadata.project ?? "general");
8868
+ switch (metadata.kind) {
8869
+ case "preference":
8870
+ return metadata.status === "active" ? `${baseUri}/preferences` : `${baseUri}/preferences/${uriSegment(metadata.status)}`;
8871
+ case "handoff":
8872
+ return `${baseUri}/handoffs/${uriSegment(metadata.status)}/${projectSegment}`;
8873
+ case "incident":
8874
+ return `${baseUri}/incidents/${uriSegment(metadata.status)}/${projectSegment}`;
8875
+ case "smoke":
8876
+ return `${baseUri}/smoke/${uriSegment(metadata.status)}`;
8877
+ case "durable":
8878
+ return metadata.status === "active" ? `${baseUri}/durable/projects/${projectSegment}` : `${baseUri}/durable/${uriSegment(metadata.status)}/${projectSegment}`;
8852
8879
  }
8853
- return matches;
8854
8880
  }
8855
-
8856
- // src/share.ts
8857
- var import_promises8 = require("node:fs/promises");
8858
- var import_node_os4 = require("node:os");
8859
- var import_node_path9 = require("node:path");
8860
- var TEAMS_FILE_VERSION = 1;
8861
- var SHARED_SEGMENT = "shared";
8862
- var SHAREABLE_MEMORY_KIND_DIRS = ["durable"];
8863
- var DEFAULT_GIT_REMOTE_NAME = "origin";
8864
- var SCRUBBER_PATTERNS = [
8865
- // Credentials: never redactable. Blocking is the only safe response —
8866
- // automated redaction risks false negatives that leave material in git.
8867
- { name: "private key", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
8868
- { name: "API key (sk-...)", regex: /\bsk-[A-Za-z0-9_-]{16,}/ },
8869
- { name: "GitHub token", regex: /\bgh[pousr]_[A-Za-z0-9_]{16,}/ },
8870
- { name: "GitHub fine-grained PAT", regex: /\bgithub_pat_[A-Za-z0-9_]{20,}/ },
8871
- { name: "GitLab PAT", regex: /\bglpat-[A-Za-z0-9_-]{20,}/ },
8872
- { name: "bearer token", regex: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/i },
8873
- // Matches bare JWTs (three base64url segments). May surface a JWE token in
8874
- // legitimate docs; if that becomes noisy we can switch to warn-only.
8875
- { name: "JWT", regex: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
8876
- { name: "AWS access key", regex: /\bAKIA[0-9A-Z]{16}\b/ },
8877
- // Slack tokens: xoxa/xoxb/xoxc (configuration)/xoxd (legacy user cookie)/
8878
- // xoxe (refresh)/xoxp/xoxr/xoxs, with optional -N- segment for the workspace tier.
8879
- { name: "Slack token", regex: /\bxox[abcdeprs](?:-\d-)?[A-Za-z0-9._-]{10,}/i },
8880
- // Soft leaks: block by default (so the agent sees them and decides), but
8881
- // allow opt-in redaction so curated memories with incidental matches can
8882
- // ship without a manual rewrite. Local home paths are the recurring
8883
- // real-world leak; the regexes greedily consume the whole path segment
8884
- // (including subdirectories) up to whitespace or common closing punctuation
8885
- // so redaction collapses an entire path to a single placeholder rather than
8886
- // leaving the subpath visible.
8887
- { name: "macOS home path", placeholder: "<local-path>", regex: /\/Users\/[^\s)>"'`,]+/ },
8888
- { name: "linux home path", placeholder: "<local-path>", regex: /\b\/home\/[^\s)>"'`,]+/ }
8889
- ];
8890
- function applyScrubber(content, { redact }) {
8891
- let cleaned = content;
8892
- const redactions = [];
8893
- for (const pattern of SCRUBBER_PATTERNS) {
8894
- if (!pattern.regex.test(cleaned)) {
8895
- continue;
8896
- }
8897
- if (!pattern.placeholder || !redact) {
8898
- return { blocker: pattern.name, cleaned: content, redactions: [] };
8899
- }
8900
- const flags = pattern.regex.flags.includes("g") ? pattern.regex.flags : `${pattern.regex.flags}g`;
8901
- const globalRegex = new RegExp(pattern.regex.source, flags);
8902
- const matches = cleaned.match(globalRegex) ?? [];
8903
- cleaned = cleaned.replace(globalRegex, pattern.placeholder);
8904
- redactions.push({ count: matches.length, name: pattern.name });
8905
- }
8906
- return { cleaned, redactions };
8881
+ function shouldUseStableMemoryUri(metadata) {
8882
+ return metadata.status === "active" && metadata.topic !== void 0 && metadata.kind !== "smoke";
8907
8883
  }
8908
- async function runShareInit(config, remoteUrl, options) {
8909
- if (!remoteUrl.trim()) {
8910
- throw new Error("Provide a git remote URL for the shared memories repo.");
8884
+ async function memoryWriteMode(ov, config, memoryUri, metadata) {
8885
+ if (!shouldUseStableMemoryUri(metadata)) {
8886
+ return "create";
8911
8887
  }
8912
- const dryRun = options.dryRun === true;
8913
- const teamName = normalizeTeamName(options.team);
8914
- const teamsFile = await readTeamsFile(config);
8915
- if (teamsFile.teams[teamName]) {
8916
- throw new Error(
8917
- `Team "${teamName}" is already configured (remote ${teamsFile.teams[teamName].remote}). Remove it first with: threadnote share remove --team ${teamName}`
8918
- );
8888
+ return await vikingResourceExists2(ov, config, memoryUri) ? "replace" : "create";
8889
+ }
8890
+ function vikingDirectoryChain(directoryUri) {
8891
+ const prefix = "viking://";
8892
+ if (!directoryUri.startsWith(prefix)) {
8893
+ return [directoryUri];
8919
8894
  }
8920
- const worktree = teamWorktreePath(config, teamName);
8921
- const gitdir = teamGitdirPath(config, teamName);
8922
- await assertWorktreeUsable(worktree);
8923
- if (await exists(gitdir)) {
8924
- throw new Error(`Gitdir already exists at ${gitdir}; remove it or pick a different team name.`);
8895
+ const parts = directoryUri.slice(prefix.length).split("/").filter(Boolean);
8896
+ const startIndex = parts[0] === "user" && parts.length > 2 ? 3 : 1;
8897
+ const chain = [];
8898
+ for (let index = startIndex; index <= parts.length; index += 1) {
8899
+ chain.push(`${prefix}${parts.slice(0, index).join("/")}`);
8925
8900
  }
8926
- await ensureDirectory((0, import_node_path9.dirname)(worktree), dryRun);
8927
- await ensureDirectory((0, import_node_path9.dirname)(gitdir), dryRun);
8928
- const git = await requiredExecutable("git");
8929
- await maybeRun(dryRun, git, ["clone", `--separate-git-dir=${gitdir}`, "--", remoteUrl, worktree]);
8930
- const newConfig = {
8931
- addedAt: (/* @__PURE__ */ new Date()).toISOString(),
8932
- gitdir,
8933
- name: teamName,
8934
- remote: remoteUrl,
8935
- worktree
8936
- };
8937
- const updatedTeams = {
8938
- defaultTeam: shouldSetDefault(options, teamsFile) ? teamName : teamsFile.defaultTeam ?? teamName,
8939
- teams: { ...teamsFile.teams, [teamName]: newConfig },
8940
- version: TEAMS_FILE_VERSION
8901
+ return chain;
8902
+ }
8903
+ function formatMemoryDocument(title, metadata, body) {
8904
+ const header = [
8905
+ title,
8906
+ `kind: ${metadata.kind}`,
8907
+ `status: ${metadata.status}`,
8908
+ metadata.project ? `project: ${metadata.project}` : void 0,
8909
+ metadata.topic ? `topic: ${metadata.topic}` : void 0,
8910
+ `source_agent_client: ${metadata.sourceAgentClient}`,
8911
+ `timestamp: ${metadata.timestamp}`,
8912
+ metadata.supersedes ? `supersedes: ${metadata.supersedes}` : void 0,
8913
+ metadata.archivedFrom ? `archived_from: ${metadata.archivedFrom}` : void 0
8914
+ ].filter((line) => line !== void 0);
8915
+ return [...header, "", body.trim()].join("\n");
8916
+ }
8917
+ function inferMemoryMetadata(memory) {
8918
+ const header = memory.slice(0, Math.max(0, memory.indexOf("\n\n")) || memory.length);
8919
+ const firstLine2 = header.split("\n")[0]?.trim();
8920
+ const kind = parseOptionalMemoryKind(parseHeaderValue(header, "kind")) ?? (firstLine2 === "HANDOFF" ? "handoff" : void 0);
8921
+ const status = parseOptionalMemoryStatus(parseHeaderValue(header, "status"));
8922
+ const project = normalizeOptionalMetadata(parseHeaderValue(header, "project")) ?? normalizeOptionalMetadata(parseHeaderValue(header, "repo"));
8923
+ const topic = normalizeOptionalMetadata(parseHeaderValue(header, "topic")) ?? normalizeOptionalMetadata(parseHeaderValue(header, "task"));
8924
+ return {
8925
+ kind,
8926
+ project,
8927
+ sourceAgentClient: parseHeaderValue(header, "source_agent_client") ?? void 0,
8928
+ status,
8929
+ topic
8941
8930
  };
8942
- if (dryRun) {
8943
- console.log(`Would write teams file: ${teamsFilePath(config)}`);
8944
- console.log(`Would set ${teamName} as default? ${updatedTeams.defaultTeam === teamName}`);
8945
- } else {
8946
- await writeTeamsFile(config, updatedTeams);
8947
- console.log(`Configured shared team "${teamName}" -> ${portablePath(worktree)}`);
8931
+ }
8932
+ function parseHeaderValue(header, key) {
8933
+ const prefix = `${key}:`;
8934
+ return header.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length).trim();
8935
+ }
8936
+ function isClearLegacyHandoffMemory(memory) {
8937
+ if (/^kind:\s*/m.test(memory) || /^status:\s*/m.test(memory)) {
8938
+ return false;
8948
8939
  }
8949
- if (!dryRun) {
8950
- await ensureSharedGitignore(worktree, git, options.push !== false);
8951
- const ingested = await ingestWorktreeFiles(config, newConfig, "create");
8952
- console.log(`Ingested ${ingested} shared memory file(s) into OpenViking.`);
8940
+ const trimmed = memory.trim();
8941
+ if (trimmed.startsWith("HANDOFF\n")) {
8942
+ return true;
8943
+ }
8944
+ if (!trimmed.startsWith("MEMORY\n")) {
8945
+ return false;
8953
8946
  }
8947
+ return /^(?:#+\s*)?(?:final\s+)?handoff(?:\s+update)?\b/i.test(memoryBody(trimmed));
8954
8948
  }
8955
- var SHARED_GITIGNORE_PATTERNS = ["**/.abstract.md", "**/.overview.md"];
8956
- var SHARED_GITIGNORE_HEADER = "# Threadnote: ignore OpenViking-generated directory summaries.";
8957
- async function ensureSharedGitignore(worktree, git, push) {
8958
- const gitignorePath = (0, import_node_path9.join)(worktree, ".gitignore");
8959
- const existing = await readFileIfExists(gitignorePath) ?? "";
8960
- const lines = existing.split("\n").map((line) => line.trim());
8961
- const missingPatterns = SHARED_GITIGNORE_PATTERNS.filter((pattern) => !lines.includes(pattern));
8962
- if (missingPatterns.length === 0) {
8963
- return;
8949
+ function memoryBody(memory) {
8950
+ const separatorIndex = memory.indexOf("\n\n");
8951
+ return separatorIndex === -1 ? "" : memory.slice(separatorIndex + 2).trim();
8952
+ }
8953
+ function inferLegacyProject(memory) {
8954
+ const explicit = parseHeaderValue(memory, "project") ?? parseHeaderValue(memory, "repo") ?? parseHeaderValue(memory, "repo_path") ?? /\brepo(?:_path)?\s+([~/A-Za-z0-9_.:/-]+)/.exec(memory)?.[1];
8955
+ if (!explicit) {
8956
+ return "general";
8964
8957
  }
8965
- const hasHeader = lines.includes(SHARED_GITIGNORE_HEADER);
8966
- const segments = [];
8967
- if (existing.length > 0 && !existing.endsWith("\n")) {
8968
- segments.push("\n");
8958
+ const trimmed = explicit.trim().replace(/[`.,;]+$/g, "");
8959
+ return trimmed.includes("/") ? (0, import_node_path5.basename)(trimmed) : trimmed;
8960
+ }
8961
+ function parseOptionalMemoryKind(value) {
8962
+ if (!value) {
8963
+ return void 0;
8969
8964
  }
8970
- if (existing.length > 0) {
8971
- segments.push("\n");
8965
+ try {
8966
+ return parseMemoryKind(value);
8967
+ } catch (_err) {
8968
+ return void 0;
8972
8969
  }
8973
- if (!hasHeader) {
8974
- segments.push(SHARED_GITIGNORE_HEADER, "\n");
8970
+ }
8971
+ function parseOptionalMemoryStatus(value) {
8972
+ if (!value) {
8973
+ return void 0;
8975
8974
  }
8976
- segments.push(missingPatterns.join("\n"), "\n");
8977
- await (0, import_promises8.writeFile)(gitignorePath, `${existing}${segments.join("")}`, { encoding: "utf8" });
8978
- console.log(`Added ${missingPatterns.join(", ")} to ${portablePath(gitignorePath)}`);
8979
- await maybeRun(false, git, ["-C", worktree, "add", ".gitignore"]);
8980
- const commitResult = await runCommand(
8981
- git,
8982
- ["-C", worktree, "commit", "-m", "share: ignore OpenViking directory summaries"],
8983
- { allowFailure: true }
8984
- );
8985
- if (commitResult.exitCode !== 0) {
8986
- const detail = commitResult.stderr.trim() || commitResult.stdout.trim();
8987
- if (!/nothing to commit|no changes added/i.test(detail)) {
8988
- console.warn(
8989
- `.gitignore housekeeping commit was rejected (${detail || "unknown"}); it will be retried on the next share sync.`
8990
- );
8991
- return;
8975
+ try {
8976
+ return parseMemoryStatus(value);
8977
+ } catch (_err) {
8978
+ return void 0;
8979
+ }
8980
+ }
8981
+ function normalizeOptionalMetadata(value) {
8982
+ const trimmed = value?.trim();
8983
+ return trimmed ? trimmed : void 0;
8984
+ }
8985
+ async function legacySourceAccounts(config, options) {
8986
+ const explicitAccounts = options.sourceAccount?.filter((account) => account.trim().length > 0) ?? [];
8987
+ if (explicitAccounts.length > 0) {
8988
+ return uniqueStrings(explicitAccounts);
8989
+ }
8990
+ if (options.allAccounts === true) {
8991
+ const accounts = await childDirectoryNames(localVikingDataRoot(config));
8992
+ return accounts.filter((account) => !account.startsWith("_"));
8993
+ }
8994
+ return [config.account];
8995
+ }
8996
+ async function legacyMemoryCandidates(config, sourceAccounts) {
8997
+ const candidates = [];
8998
+ for (const sourceAccount of sourceAccounts) {
8999
+ const sessionRoot = (0, import_node_path5.join)(localVikingDataRoot(config), sourceAccount, "session");
9000
+ for (const sourceSession of await childDirectoryNames(sessionRoot)) {
9001
+ const historyRoot = (0, import_node_path5.join)(sessionRoot, sourceSession, "history");
9002
+ for (const sourceArchive of await childDirectoryNames(historyRoot)) {
9003
+ if (!sourceArchive.startsWith("archive_")) {
9004
+ continue;
9005
+ }
9006
+ const sourcePath = (0, import_node_path5.join)(historyRoot, sourceArchive, "messages.jsonl");
9007
+ for (const text of await legacyMemoryTexts(sourcePath)) {
9008
+ candidates.push({
9009
+ comparableHash: sha256(comparableMemoryText(text)),
9010
+ hash: sha256(text),
9011
+ sourceAccount,
9012
+ sourceArchive,
9013
+ sourceSession,
9014
+ text
9015
+ });
9016
+ }
9017
+ }
8992
9018
  }
8993
9019
  }
8994
- if (push) {
8995
- await maybeRun(false, git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
9020
+ return candidates.sort((left, right) => legacySourceLabel(left).localeCompare(legacySourceLabel(right)));
9021
+ }
9022
+ async function legacyMemoryTexts(sourcePath) {
9023
+ const raw = await readTextIfExists(sourcePath);
9024
+ if (!raw) {
9025
+ return [];
9026
+ }
9027
+ const memories = [];
9028
+ for (const line of raw.split("\n")) {
9029
+ const trimmedLine = line.trim();
9030
+ if (!trimmedLine) {
9031
+ continue;
9032
+ }
9033
+ try {
9034
+ const parsed = JSON.parse(trimmedLine);
9035
+ const text = legacyMessageText(parsed)?.trim();
9036
+ if (text && isLegacyThreadnoteMemory(text)) {
9037
+ memories.push(text);
9038
+ }
9039
+ } catch (_err) {
9040
+ continue;
9041
+ }
8996
9042
  }
9043
+ return memories;
8997
9044
  }
8998
- async function runShareStatus(config, options) {
8999
- const team = await resolveTeam(config, options.team);
9000
- const git = await requiredExecutable("git");
9001
- console.log(`Team: ${team.name}`);
9002
- console.log(`Remote: ${team.config.remote}`);
9003
- console.log(`Worktree: ${portablePath(team.config.worktree)}`);
9004
- console.log(`Gitdir: ${portablePath(team.config.gitdir)}`);
9005
- await maybeRun(options.dryRun === true, git, ["-C", team.config.worktree, "status", "--short", "--branch"]);
9006
- await maybeRun(options.dryRun === true, git, ["-C", team.config.worktree, "fetch", DEFAULT_GIT_REMOTE_NAME], {
9007
- allowFailure: true
9008
- });
9009
- const ahead = await gitOutput(team.config.worktree, ["rev-list", "--count", "@{u}..HEAD"], options.dryRun === true);
9010
- const behind = await gitOutput(team.config.worktree, ["rev-list", "--count", "HEAD..@{u}"], options.dryRun === true);
9011
- if (ahead !== void 0) {
9012
- console.log(`Ahead of upstream: ${ahead}`);
9045
+ function legacyMessageText(value) {
9046
+ if (!isJsonObject(value)) {
9047
+ return void 0;
9013
9048
  }
9014
- if (behind !== void 0) {
9015
- console.log(`Behind upstream: ${behind}`);
9049
+ if (typeof value.content === "string") {
9050
+ return value.content;
9051
+ }
9052
+ if (!Array.isArray(value.parts)) {
9053
+ return void 0;
9016
9054
  }
9055
+ const parts = value.parts.map((part) => isJsonObject(part) && part.type === "text" && typeof part.text === "string" ? part.text : void 0).filter((text) => text !== void 0);
9056
+ return parts.length > 0 ? parts.join("\n") : void 0;
9017
9057
  }
9018
- async function runShareSync(config, options) {
9019
- const team = await resolveTeam(config, options.team);
9020
- const dryRun = options.dryRun === true;
9021
- const git = await requiredExecutable("git");
9022
- const worktree = team.config.worktree;
9023
- if (!dryRun) {
9024
- await ensureSharedGitignore(worktree, git, false);
9058
+ function isLegacyThreadnoteMemory(text) {
9059
+ return text.startsWith("MEMORY\n") || text.startsWith("HANDOFF\n");
9060
+ }
9061
+ async function existingDurableMemoryHashes(config) {
9062
+ const hashes = /* @__PURE__ */ new Set();
9063
+ await collectDurableMemoryHashes(localVikingDataRoot(config), hashes);
9064
+ return hashes;
9065
+ }
9066
+ async function collectDurableMemoryHashes(root, hashes) {
9067
+ let entries;
9068
+ try {
9069
+ entries = await (0, import_promises5.readdir)(root, { withFileTypes: true });
9070
+ } catch (_err) {
9071
+ return;
9025
9072
  }
9026
- if (await hasUncommittedChanges(worktree)) {
9027
- if (options.autoCommit === false) {
9028
- throw new Error(
9029
- `Worktree ${worktree} has uncommitted changes. Commit them yourself or rerun without --no-auto-commit.`
9030
- );
9073
+ for (const entry of entries) {
9074
+ const path = (0, import_node_path5.join)(root, entry.name);
9075
+ if (entry.isDirectory()) {
9076
+ await collectDurableMemoryHashes(path, hashes);
9077
+ continue;
9078
+ }
9079
+ if (!entry.isFile() || entry.name.startsWith(".") || !entry.name.endsWith(".md") || !isDurableMemoryPath(path)) {
9080
+ continue;
9081
+ }
9082
+ const content = await readTextIfExists(path);
9083
+ if (content) {
9084
+ const trimmedContent = content.trim();
9085
+ hashes.add(sha256(trimmedContent));
9086
+ hashes.add(sha256(comparableMemoryText(trimmedContent)));
9031
9087
  }
9032
- const message = options.message ?? `share: sync ${(/* @__PURE__ */ new Date()).toISOString()}`;
9033
- await stageShareableChanges(dryRun, git, worktree);
9034
- await maybeRun(dryRun, git, ["-C", worktree, "commit", "-m", message], { allowFailure: true });
9035
9088
  }
9036
- const beforeRev = await gitOutput(worktree, ["rev-parse", "HEAD"], dryRun);
9037
- await maybeRun(dryRun, git, ["-C", worktree, "fetch", DEFAULT_GIT_REMOTE_NAME]);
9038
- const pullResult = dryRun ? void 0 : await runCommand(git, ["-C", worktree, "pull", "--rebase", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
9039
- if (dryRun) {
9040
- console.log(`Would run: ${formatShellCommand(git, ["-C", worktree, "pull", "--rebase", DEFAULT_GIT_REMOTE_NAME])}`);
9041
- } else if (pullResult && pullResult.exitCode !== 0) {
9042
- if (await exists((0, import_node_path9.join)(team.config.gitdir, "rebase-merge")) || await exists((0, import_node_path9.join)(team.config.gitdir, "rebase-apply"))) {
9043
- throw new Error(
9044
- `git pull --rebase reported conflicts in ${worktree}. The worktree is in a rebase-in-progress state.
9045
- Resolve the conflicts in-place, run \`git -C ${worktree} rebase --continue\` (or --abort), then re-run \`threadnote share sync\`.`
9046
- );
9089
+ }
9090
+ function isDurableMemoryPath(path) {
9091
+ return path.split(import_node_path5.sep).includes("memories");
9092
+ }
9093
+ async function childDirectoryNames(path) {
9094
+ let entries;
9095
+ try {
9096
+ entries = await (0, import_promises5.readdir)(path, { withFileTypes: true });
9097
+ } catch (_err) {
9098
+ return [];
9099
+ }
9100
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
9101
+ }
9102
+ async function readTextIfExists(path) {
9103
+ try {
9104
+ const pathStat = await (0, import_promises5.stat)(path);
9105
+ if (!pathStat.isFile()) {
9106
+ return void 0;
9047
9107
  }
9048
- throw new Error(
9049
- `git pull --rebase failed in ${worktree}: ${pullResult.stderr.trim() || pullResult.stdout.trim() || "unknown error"}`
9050
- );
9108
+ return await (0, import_promises5.readFile)(path, "utf8");
9109
+ } catch (_err) {
9110
+ return void 0;
9051
9111
  }
9052
- const afterRev = await gitOutput(worktree, ["rev-parse", "HEAD"], dryRun);
9053
- if (!dryRun && beforeRev && afterRev && beforeRev !== afterRev) {
9054
- const changes = await listChangedFiles(worktree, beforeRev, afterRev);
9055
- await applyChangesToOpenViking(config, team.config, changes);
9056
- console.log(`Reindexed ${changes.length} file change(s) into OpenViking.`);
9057
- } else if (!dryRun) {
9058
- console.log("No upstream changes to reindex.");
9112
+ }
9113
+ function sensitiveMemoryReason(text) {
9114
+ const patterns = [
9115
+ { name: "private key", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
9116
+ { name: "API key", regex: /\bsk-[A-Za-z0-9_-]{16,}/ },
9117
+ { name: "GitHub token", regex: /\bgh[pousr]_[A-Za-z0-9_]{16,}/ },
9118
+ { name: "bearer token", regex: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/i },
9119
+ { name: "AWS access key", regex: /\bAKIA[0-9A-Z]{16}\b/ }
9120
+ ];
9121
+ return patterns.find((pattern) => pattern.regex.test(text))?.name;
9122
+ }
9123
+ function comparableMemoryText(text) {
9124
+ const trimmed = text.trim();
9125
+ if (!trimmed.startsWith("MEMORY\n")) {
9126
+ return trimmed;
9059
9127
  }
9060
- if (options.push !== false) {
9061
- await maybeRun(dryRun, git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
9128
+ const separatorIndex = trimmed.indexOf("\n\n");
9129
+ return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 2).trim();
9130
+ }
9131
+ function legacySourceLabel(candidate) {
9132
+ return `${candidate.sourceAccount}/${candidate.sourceSession}/${candidate.sourceArchive}`;
9133
+ }
9134
+ function localVikingDataRoot(config) {
9135
+ return (0, import_node_path5.join)(config.agentContextHome, "data", "viking");
9136
+ }
9137
+ function localUserMemoriesRoot(config) {
9138
+ return (0, import_node_path5.join)(localVikingDataRoot(config), config.account, "user", uriSegment(config.user), "memories");
9139
+ }
9140
+ function uniqueStrings(values) {
9141
+ return [...new Set(values)].sort();
9142
+ }
9143
+ function isResourceBusy(stderr, stdout) {
9144
+ const output2 = `${stderr}
9145
+ ${stdout}`.toLowerCase();
9146
+ return output2.includes("resource is busy") || output2.includes("resource is being processed");
9147
+ }
9148
+ async function buildHandoff(options) {
9149
+ const repoRoot = await gitValue(["rev-parse", "--show-toplevel"]) ?? getInvocationCwd();
9150
+ const branch = await gitValue(["branch", "--show-current"], repoRoot) ?? "unknown";
9151
+ const status = await gitValue(["status", "--short"], repoRoot) ?? "";
9152
+ const diffStat = await gitValue(["diff", "--stat", "HEAD"], repoRoot) ?? "";
9153
+ const touchedFiles = await gitTouchedFiles(repoRoot);
9154
+ const repoName = (0, import_node_path5.basename)(repoRoot);
9155
+ const metadata = {
9156
+ kind: "handoff",
9157
+ project: normalizeOptionalMetadata(options.project) ?? repoName,
9158
+ sourceAgentClient: options.sourceAgentClient ?? "codex",
9159
+ status: "active",
9160
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9161
+ topic: normalizeOptionalMetadata(options.topic)
9162
+ };
9163
+ const bodyText = [
9164
+ `repo: ${repoName}`,
9165
+ `repo_path: ${repoRoot}`,
9166
+ `branch: ${branch || "unknown"}`,
9167
+ `task: ${options.task ?? "unspecified"}`,
9168
+ "",
9169
+ "files_touched:",
9170
+ formatBlock(touchedFiles, "- none"),
9171
+ "",
9172
+ "git_status:",
9173
+ formatBlock(status, "- clean"),
9174
+ "",
9175
+ "diff_stat:",
9176
+ formatBlock(diffStat, "- none"),
9177
+ "",
9178
+ "tests:",
9179
+ options.tests ?? "- not recorded",
9180
+ "",
9181
+ "blockers:",
9182
+ options.blockers ?? "- none recorded",
9183
+ "",
9184
+ "next_step:",
9185
+ options.nextStep ?? "- inspect the current repo state and continue from this handoff"
9186
+ ].join("\n");
9187
+ return { bodyText, metadata };
9188
+ }
9189
+ async function gitTouchedFiles(cwd) {
9190
+ const changedFiles = await gitValue(["diff", "--name-only", "HEAD"], cwd);
9191
+ const untrackedFiles = await gitValue(["ls-files", "--others", "--exclude-standard"], cwd);
9192
+ const files = /* @__PURE__ */ new Set();
9193
+ for (const value of [changedFiles, untrackedFiles]) {
9194
+ for (const line of (value ?? "").split("\n")) {
9195
+ const trimmed = line.trim();
9196
+ if (trimmed) {
9197
+ files.add(trimmed);
9198
+ }
9199
+ }
9062
9200
  }
9201
+ return [...files].sort().join("\n");
9063
9202
  }
9064
- async function stageShareableChanges(dryRun, git, worktree) {
9065
- const pathspecs = [":(top)README.md", ":(top).gitignore", ...SHAREABLE_MEMORY_KIND_DIRS.map((dir) => `:(top)${dir}`)];
9066
- await maybeRun(dryRun, git, ["-C", worktree, "add", "--", ...pathspecs], { allowFailure: true });
9203
+ function formatBlock(value, emptyValue) {
9204
+ const trimmed = value.trim();
9205
+ if (!trimmed) {
9206
+ return emptyValue;
9207
+ }
9208
+ return trimmed.split("\n").map((line) => `- ${line}`).join("\n");
9067
9209
  }
9068
- async function runSharePublish(config, sourceUri, options) {
9069
- assertVikingUri(sourceUri);
9070
- const team = await resolveTeam(config, options.team);
9071
- const dryRun = options.dryRun === true;
9072
- const preview = options.preview === true;
9073
- if (isInSharedNamespace(config, sourceUri)) {
9074
- throw new Error(`Memory ${sourceUri} is already in the shared namespace.`);
9210
+
9211
+ // src/update-check.ts
9212
+ var import_node_child_process2 = require("node:child_process");
9213
+ var import_promises6 = require("node:fs/promises");
9214
+ var import_node_path6 = require("node:path");
9215
+ var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
9216
+ var NPM_LATEST_URL = "https://registry.npmjs.org/threadnote/latest";
9217
+ var FETCH_TIMEOUT_MS = 3e3;
9218
+ async function checkForThreadnoteUpdate(args) {
9219
+ if (args.currentVersion === "unknown") {
9220
+ return void 0;
9075
9221
  }
9076
- const ov = await openVikingCliForMode(dryRun);
9077
- const rawContent = await readMemoryContent(config, ov, sourceUri, dryRun);
9078
- const stripped = stripPersonalProvenance(rawContent);
9079
- const scrub = applyScrubber(stripped, { redact: options.redact === true });
9080
- const targetUri = sharedUriFor(config, sourceUri, team.name);
9081
- if (preview) {
9082
- console.log(`PREVIEW source: ${sourceUri}`);
9083
- console.log(`PREVIEW destination: ${targetUri}`);
9084
- if (scrub.blocker) {
9085
- console.log(
9086
- `PREVIEW BLOCKED: ${scrub.blocker}. Strip the sensitive value or rerun with --redact for soft-leak patterns.`
9087
- );
9222
+ const cached = await readUpdateCache(args.cachePath);
9223
+ if (cached && isCacheFresh(cached)) {
9224
+ return compareVersions(args.currentVersion, cached.latestVersion);
9225
+ }
9226
+ const fresh = await fetchLatestVersion();
9227
+ if (fresh) {
9228
+ await writeUpdateCache(args.cachePath, {
9229
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
9230
+ latestVersion: fresh,
9231
+ version: 1
9232
+ });
9233
+ return compareVersions(args.currentVersion, fresh);
9234
+ }
9235
+ if (cached) {
9236
+ return compareVersions(args.currentVersion, cached.latestVersion);
9237
+ }
9238
+ return void 0;
9239
+ }
9240
+ function spawnDetachedAutoUpdate() {
9241
+ try {
9242
+ const entry = process.argv[1];
9243
+ if (typeof entry !== "string" || entry.length === 0) {
9088
9244
  return;
9089
9245
  }
9090
- for (const redaction of scrub.redactions) {
9091
- console.log(`PREVIEW redact: ${redaction.count}\xD7 ${redaction.name}`);
9092
- }
9093
- console.log("-----BEGIN PREVIEW-----");
9094
- console.log(scrub.cleaned);
9095
- console.log("-----END PREVIEW-----");
9096
- return;
9246
+ const child = (0, import_node_child_process2.spawn)(process.execPath, [entry, "update", "--yes"], {
9247
+ detached: true,
9248
+ stdio: "ignore"
9249
+ });
9250
+ child.unref();
9251
+ } catch {
9097
9252
  }
9098
- if (scrub.blocker) {
9099
- throw new Error(
9100
- `Refusing to publish ${sourceUri}: possible ${scrub.blocker}. Strip the sensitive value or pass --redact for soft-leak patterns.`
9101
- );
9253
+ }
9254
+ function compareVersions(currentVersion, latestVersion) {
9255
+ return {
9256
+ currentVersion,
9257
+ latestVersion,
9258
+ outdated: isNewerVersion(latestVersion, currentVersion)
9259
+ };
9260
+ }
9261
+ function isNewerVersion(candidate, baseline) {
9262
+ const candidateParts = parseVersion(candidate);
9263
+ const baselineParts = parseVersion(baseline);
9264
+ for (let index = 0; index < 3; index += 1) {
9265
+ if (candidateParts[index] !== baselineParts[index]) {
9266
+ return candidateParts[index] > baselineParts[index];
9267
+ }
9102
9268
  }
9103
- for (const redaction of scrub.redactions) {
9104
- console.log(`Redacted ${redaction.count}\xD7 ${redaction.name} before publish.`);
9269
+ return false;
9270
+ }
9271
+ function parseVersion(value) {
9272
+ const parts = value.split(".").map((part) => parseInt(part, 10));
9273
+ return [parts[0] || 0, parts[1] || 0, parts[2] || 0];
9274
+ }
9275
+ function isCacheFresh(cache) {
9276
+ const checkedAt = new Date(cache.checkedAt).getTime();
9277
+ return Number.isFinite(checkedAt) && Date.now() - checkedAt < CACHE_TTL_MS;
9278
+ }
9279
+ async function readUpdateCache(cachePath) {
9280
+ try {
9281
+ const raw = await (0, import_promises6.readFile)(cachePath, "utf8");
9282
+ const parsed = JSON.parse(raw);
9283
+ if (parsed.version !== 1 || typeof parsed.latestVersion !== "string" || typeof parsed.checkedAt !== "string") {
9284
+ return void 0;
9285
+ }
9286
+ return { checkedAt: parsed.checkedAt, latestVersion: parsed.latestVersion, version: 1 };
9287
+ } catch {
9288
+ return void 0;
9105
9289
  }
9106
- const content = scrub.cleaned;
9107
- if (!dryRun && await vikingResourceExists2(ov, config, targetUri)) {
9108
- throw new Error(
9109
- `Refusing to publish: ${targetUri} already exists in the shared namespace. Inspect it via threadnote read; if it should be replaced, forget the existing shared copy first.`
9110
- );
9290
+ }
9291
+ async function writeUpdateCache(cachePath, contents) {
9292
+ try {
9293
+ await (0, import_promises6.mkdir)((0, import_node_path6.dirname)(cachePath), { recursive: true });
9294
+ await (0, import_promises6.writeFile)(cachePath, `${JSON.stringify(contents)}
9295
+ `, { encoding: "utf8", mode: 384 });
9296
+ } catch {
9111
9297
  }
9112
- await ensureSharedDirectoryChain(config, ov, targetUri, dryRun);
9113
- await writeMemoryFile(config, ov, targetUri, content, "create", dryRun);
9114
- await removeWithRollback(config, ov, sourceUri, targetUri, team.config.worktree, dryRun, "publish");
9115
- const git = await requiredExecutable("git");
9116
- const worktree = team.config.worktree;
9117
- const relativePath = vikingUriToWorktreeRelative(config, targetUri, team.name);
9118
- const message = options.message ?? `share: publish ${relativePath}`;
9119
- await maybeRun(dryRun, git, ["-C", worktree, "add", "--", relativePath]);
9120
- await maybeRun(dryRun, git, ["-C", worktree, "commit", "-m", message], { allowFailure: true });
9121
- if (options.push !== false) {
9122
- const pushResult = dryRun ? void 0 : await runCommand(git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
9123
- if (dryRun) {
9124
- console.log(`Would run: ${formatShellCommand(git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME])}`);
9125
- } else if (pushResult && pushResult.exitCode !== 0) {
9126
- const detail = pushResult.stderr.trim() || pushResult.stdout.trim() || "unknown error";
9127
- throw new Error(
9128
- `Memory was committed locally but git push failed: ${detail}
9129
- Resolve the remote issue (auth, network, branch protection), then run: threadnote share sync`
9130
- );
9298
+ }
9299
+ async function fetchLatestVersion() {
9300
+ try {
9301
+ const response = await fetch(NPM_LATEST_URL, {
9302
+ headers: { accept: "application/json" },
9303
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
9304
+ });
9305
+ if (!response.ok) {
9306
+ return void 0;
9131
9307
  }
9308
+ const data = await response.json();
9309
+ return typeof data.version === "string" && data.version.length > 0 ? data.version : void 0;
9310
+ } catch {
9311
+ return void 0;
9132
9312
  }
9133
- console.log(`Published ${sourceUri} -> ${targetUri}`);
9134
9313
  }
9135
- async function runShareUnpublish(config, sourceUri, options) {
9136
- assertVikingUri(sourceUri);
9137
- const team = await resolveTeam(config, options.team);
9138
- const dryRun = options.dryRun === true;
9139
- if (!isInTeamNamespace(config, sourceUri, team.name)) {
9140
- throw new Error(`Memory ${sourceUri} is not in team "${team.name}" shared namespace.`);
9141
- }
9142
- const ov = await openVikingCliForMode(dryRun);
9143
- const content = await readMemoryContent(config, ov, sourceUri, dryRun);
9144
- const targetUri = personalUriFor(config, sourceUri, team.name);
9145
- if (!dryRun && await vikingResourceExists2(ov, config, targetUri)) {
9146
- throw new Error(
9147
- `Refusing to unpublish: a personal memory already exists at ${targetUri}. Move or forget it first, then retry.`
9148
- );
9314
+
9315
+ // src/version.ts
9316
+ var import_node_fs4 = require("node:fs");
9317
+ var import_node_path7 = require("node:path");
9318
+ var cachedVersion;
9319
+ function getThreadnoteVersion() {
9320
+ if (cachedVersion !== void 0) {
9321
+ return cachedVersion;
9149
9322
  }
9150
- await writeMemoryFile(config, ov, targetUri, content, "create", dryRun);
9151
- await removeWithRollback(config, ov, sourceUri, targetUri, team.config.worktree, dryRun, "unpublish");
9152
- const git = await requiredExecutable("git");
9153
- const worktree = team.config.worktree;
9154
- const relativePath = vikingUriToWorktreeRelative(config, sourceUri, team.name);
9155
- const message = options.message ?? `share: unpublish ${relativePath}`;
9156
- await maybeRun(dryRun, git, ["-C", worktree, "rm", relativePath], { allowFailure: true });
9157
- await maybeRun(dryRun, git, ["-C", worktree, "commit", "-m", message], { allowFailure: true });
9158
- if (options.push !== false) {
9159
- await maybeRun(dryRun, git, ["-C", worktree, "push", DEFAULT_GIT_REMOTE_NAME], { allowFailure: true });
9323
+ try {
9324
+ const packageJsonPath = (0, import_node_path7.join)(__dirname, "..", "package.json");
9325
+ const parsed = JSON.parse((0, import_node_fs4.readFileSync)(packageJsonPath, "utf8"));
9326
+ cachedVersion = typeof parsed.version === "string" && parsed.version.length > 0 ? parsed.version : "unknown";
9327
+ } catch {
9328
+ cachedVersion = "unknown";
9160
9329
  }
9161
- console.log(`Unpublished ${sourceUri} -> ${targetUri}`);
9330
+ return cachedVersion;
9162
9331
  }
9163
- async function runShareList(config, _options) {
9164
- const teams = await readTeamsFile(config);
9165
- const entries = Object.values(teams.teams);
9166
- if (entries.length === 0) {
9167
- console.log("No shared teams configured. Run: threadnote share init <remote-url>");
9168
- return;
9332
+
9333
+ // src/hooks.ts
9334
+ var MANAGED_HOOKS = [
9335
+ {
9336
+ event: "PreCompact",
9337
+ command: HOOK_PRE_COMPACT_COMMAND,
9338
+ description: "Auto-store a handoff snapshot before context compaction so the next turn can recall it."
9339
+ },
9340
+ {
9341
+ event: "SessionStart",
9342
+ command: HOOK_SESSION_START_COMMAND,
9343
+ description: "Pre-load the latest handoff for the current repo into the new session context."
9169
9344
  }
9170
- for (const team of entries) {
9171
- const marker = team.name === teams.defaultTeam ? " (default)" : "";
9172
- console.log(`- ${team.name}${marker}`);
9173
- console.log(` remote: ${team.remote}`);
9174
- console.log(` worktree: ${portablePath(team.worktree)}`);
9175
- console.log(` gitdir: ${portablePath(team.gitdir)}`);
9176
- console.log(` added: ${team.addedAt}`);
9345
+ ];
9346
+ async function runHooksInstall(config, agent, options) {
9347
+ const apply = options.apply === true && options.dryRun !== true;
9348
+ const remove = options.remove === true;
9349
+ switch (agent) {
9350
+ case "claude":
9351
+ await runClaudeHooksInstall({ apply, remove });
9352
+ return;
9353
+ case "codex":
9354
+ printCodexHooksNotice(remove);
9355
+ return;
9356
+ case "cursor":
9357
+ printNoHooksSupported("cursor", remove);
9358
+ return;
9359
+ case "copilot":
9360
+ printNoHooksSupported("copilot", remove);
9361
+ return;
9177
9362
  }
9178
9363
  }
9179
- async function runShareRemove(config, options) {
9180
- const team = await resolveTeam(config, options.team);
9181
- const dryRun = options.dryRun === true;
9182
- const teamsFile = await readTeamsFile(config);
9183
- const remaining = {};
9184
- for (const [name, value] of Object.entries(teamsFile.teams)) {
9185
- if (name !== team.name) {
9186
- remaining[name] = value;
9187
- }
9364
+ async function runClaudeHooksInstall(options) {
9365
+ const path = expandPath(CLAUDE_SETTINGS_PATH);
9366
+ const existingRaw = await exists(path) ? await (0, import_promises7.readFile)(path, "utf8") : "{}";
9367
+ const parsed = parseJsonConfigObject(existingRaw) ?? {};
9368
+ const next = options.remove ? withoutThreadnoteHooks(parsed) : withThreadnoteHooks(parsed);
9369
+ const before = JSON.stringify(parsed);
9370
+ const after = JSON.stringify(next);
9371
+ if (before === after) {
9372
+ console.log(`Claude hooks already ${options.remove ? "absent" : "managed"} in ${path}.`);
9373
+ return;
9188
9374
  }
9189
- const remainingNames = Object.keys(remaining);
9190
- const nextDefault = teamsFile.defaultTeam === team.name ? remainingNames[0] : teamsFile.defaultTeam;
9191
- const updated = { defaultTeam: nextDefault, teams: remaining, version: TEAMS_FILE_VERSION };
9192
- if (dryRun) {
9193
- console.log(`Would update teams file: ${teamsFilePath(config)}`);
9194
- } else {
9195
- await writeTeamsFile(config, updated);
9196
- console.log(`Removed team "${team.name}" from teams.json.`);
9375
+ console.log(`${options.apply ? "Updating" : "Would update"} ${path}:`);
9376
+ for (const entry of MANAGED_HOOKS) {
9377
+ console.log(` ${options.remove ? "-" : "+"} ${entry.event}: ${entry.command}`);
9197
9378
  }
9198
- if (options.keepFiles !== true) {
9199
- await removePath(team.config.worktree, "shared worktree", dryRun);
9200
- await removePath(team.config.gitdir, "shared gitdir", dryRun);
9201
- } else {
9202
- console.log(`Keeping files at ${portablePath(team.config.worktree)} and ${portablePath(team.config.gitdir)}`);
9379
+ if (!options.apply) {
9380
+ console.log("\nRe-run with --apply to actually modify the file.");
9381
+ return;
9203
9382
  }
9383
+ await (0, import_promises7.mkdir)((0, import_node_path8.dirname)(path), { recursive: true });
9384
+ const serialized = `${JSON.stringify(next, void 0, 2)}
9385
+ `;
9386
+ await (0, import_promises7.writeFile)(path, serialized, { encoding: "utf8", mode: 384 });
9387
+ await (0, import_promises7.chmod)(path, 384);
9388
+ console.log(`${options.remove ? "Removed" : "Installed"} threadnote-managed Claude hooks.`);
9204
9389
  }
9205
- function normalizeTeamName(input2) {
9206
- const candidate = (input2 ?? "default").trim();
9207
- if (!candidate) {
9208
- return "default";
9390
+ function withThreadnoteHooks(input2) {
9391
+ const hooks = ensureMutableObject(input2.hooks);
9392
+ for (const entry of MANAGED_HOOKS) {
9393
+ const list = ensureMutableArray(hooks[entry.event]).filter((item) => !isManagedThreadnoteEntry(item));
9394
+ list.push({
9395
+ [THREADNOTE_HOOK_MARKER]: THREADNOTE_HOOK_MARKER_VALUE,
9396
+ matcher: "",
9397
+ hooks: [{ type: "command", command: entry.command }]
9398
+ });
9399
+ hooks[entry.event] = list;
9209
9400
  }
9210
- if (!/^[a-z0-9][a-z0-9._-]*$/.test(candidate) || /^\.+$/.test(candidate)) {
9211
- throw new Error(
9212
- `Invalid team name "${input2}". Team names must start with a lowercase letter or digit and contain only [a-z0-9._-]. Single-dot or dot-only names are rejected so they don't collapse to the shared-root or parent directory.`
9213
- );
9401
+ return { ...input2, hooks };
9402
+ }
9403
+ function withoutThreadnoteHooks(input2) {
9404
+ if (!isJsonObject(input2.hooks)) {
9405
+ return input2;
9406
+ }
9407
+ const hooks = {};
9408
+ for (const [event, value] of Object.entries(input2.hooks)) {
9409
+ if (!Array.isArray(value)) {
9410
+ hooks[event] = value;
9411
+ continue;
9412
+ }
9413
+ const filtered = value.filter((item) => !isManagedThreadnoteEntry(item));
9414
+ if (filtered.length > 0) {
9415
+ hooks[event] = filtered;
9416
+ }
9214
9417
  }
9215
- return candidate;
9418
+ if (Object.keys(hooks).length === 0) {
9419
+ const next = { ...input2 };
9420
+ delete next.hooks;
9421
+ return next;
9422
+ }
9423
+ return { ...input2, hooks };
9216
9424
  }
9217
- function teamsFilePath(config) {
9218
- return (0, import_node_path9.join)(config.agentContextHome, "share", "teams.json");
9425
+ function isManagedThreadnoteEntry(value) {
9426
+ return isJsonObject(value) && value[THREADNOTE_HOOK_MARKER] === THREADNOTE_HOOK_MARKER_VALUE;
9219
9427
  }
9220
- function teamWorktreePath(config, team) {
9221
- return (0, import_node_path9.join)(
9222
- config.agentContextHome,
9223
- "data",
9224
- "viking",
9225
- config.account,
9226
- "user",
9227
- uriSegment(config.user),
9228
- "memories",
9229
- SHARED_SEGMENT,
9230
- team
9428
+ function ensureMutableObject(value) {
9429
+ return isJsonObject(value) ? { ...value } : {};
9430
+ }
9431
+ function ensureMutableArray(value) {
9432
+ return Array.isArray(value) ? [...value] : [];
9433
+ }
9434
+ function printCodexHooksNotice(remove) {
9435
+ if (remove) {
9436
+ console.log("Codex CLI does not expose a managed hook surface today, so there is nothing to remove.");
9437
+ return;
9438
+ }
9439
+ console.log(
9440
+ [
9441
+ "Codex CLI does not currently expose lifecycle hooks (no PreCompact or SessionStart analog).",
9442
+ "Threadnote already installs Codex user instructions at ~/.codex/AGENTS.md; that remains the active guidance surface.",
9443
+ "If a future Codex release adds hook events, threadnote will pick them up via `install-hooks codex`."
9444
+ ].join("\n")
9231
9445
  );
9232
9446
  }
9233
- function teamGitdirPath(config, team) {
9234
- return (0, import_node_path9.join)(config.agentContextHome, "share", "teams", `${team}.gitdir`);
9447
+ function printNoHooksSupported(agent, remove) {
9448
+ if (remove) {
9449
+ console.log(`${agent} does not expose a hook surface; nothing to remove.`);
9450
+ return;
9451
+ }
9452
+ console.log(
9453
+ [
9454
+ `${agent} does not expose agent-mode hooks today.`,
9455
+ "Threadnote already installs user-level instructions for this agent; that remains the active guidance surface.",
9456
+ "Hooks support will be added if the agent gains a hook surface upstream."
9457
+ ].join("\n")
9458
+ );
9235
9459
  }
9236
- async function readTeamsFile(config) {
9237
- const path = teamsFilePath(config);
9238
- const raw = await readFileIfExists(path);
9239
- if (!raw) {
9240
- return { teams: {}, version: TEAMS_FILE_VERSION };
9460
+ async function hasManagedClaudeHooks() {
9461
+ const path = expandPath(CLAUDE_SETTINGS_PATH);
9462
+ if (!await exists(path)) {
9463
+ return false;
9241
9464
  }
9465
+ const raw = await (0, import_promises7.readFile)(path, "utf8");
9242
9466
  const parsed = parseJsonConfigObject(raw);
9243
- if (!parsed) {
9244
- throw new Error(`Could not parse teams file ${path}`);
9245
- }
9246
- if (typeof parsed.version === "number" && parsed.version > TEAMS_FILE_VERSION) {
9247
- throw new Error(
9248
- `Teams file ${path} was written with version ${parsed.version}; this Threadnote binary understands up to version ${TEAMS_FILE_VERSION}. Upgrade Threadnote (\`threadnote update\`) before continuing.`
9249
- );
9467
+ if (!parsed || !isJsonObject(parsed.hooks)) {
9468
+ return false;
9250
9469
  }
9251
- const teams = {};
9252
- if (typeof parsed.teams === "object" && parsed.teams !== null && !Array.isArray(parsed.teams)) {
9253
- for (const [name, value] of Object.entries(parsed.teams)) {
9254
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
9255
- console.warn(`Skipping non-object team entry "${name}" in ${path}.`);
9256
- continue;
9257
- }
9258
- const entry = value;
9259
- if (typeof entry.remote !== "string" || entry.remote.length === 0) {
9260
- console.warn(`Skipping team entry "${name}" in ${path}: missing or empty "remote" field.`);
9261
- continue;
9262
- }
9263
- teams[name] = {
9264
- addedAt: typeof entry.addedAt === "string" ? entry.addedAt : (/* @__PURE__ */ new Date(0)).toISOString(),
9265
- gitdir: typeof entry.gitdir === "string" ? entry.gitdir : teamGitdirPath(config, name),
9266
- name,
9267
- remote: entry.remote,
9268
- worktree: typeof entry.worktree === "string" ? entry.worktree : teamWorktreePath(config, name)
9269
- };
9470
+ for (const value of Object.values(parsed.hooks)) {
9471
+ if (!Array.isArray(value)) {
9472
+ continue;
9473
+ }
9474
+ if (value.some((item) => isManagedThreadnoteEntry(item))) {
9475
+ return true;
9270
9476
  }
9271
9477
  }
9272
- const defaultTeam = typeof parsed.defaultTeam === "string" ? parsed.defaultTeam : void 0;
9273
- return { defaultTeam, teams, version: TEAMS_FILE_VERSION };
9274
- }
9275
- async function writeTeamsFile(config, contents) {
9276
- const path = teamsFilePath(config);
9277
- await (0, import_promises8.mkdir)((0, import_node_path9.dirname)(path), { recursive: true });
9278
- const serializable = {
9279
- defaultTeam: contents.defaultTeam,
9280
- teams: contents.teams,
9281
- version: contents.version
9282
- };
9283
- await (0, import_promises8.writeFile)(path, `${JSON.stringify(serializable, void 0, 2)}
9284
- `, { encoding: "utf8", mode: 384 });
9285
- }
9286
- async function resolveTeam(config, requested) {
9287
- const teamsFile = await readTeamsFile(config);
9288
- const entries = Object.entries(teamsFile.teams);
9289
- if (entries.length === 0) {
9290
- throw new Error("No shared teams configured. Run: threadnote share init <remote-url>");
9291
- }
9292
- const wantName = requested ? normalizeTeamName(requested) : teamsFile.defaultTeam ?? entries[0][0];
9293
- const found = teamsFile.teams[wantName];
9294
- if (!found) {
9295
- const known = entries.map(([name]) => name).join(", ");
9296
- throw new Error(`Team "${wantName}" is not configured. Known teams: ${known}`);
9297
- }
9298
- return { config: found, name: wantName };
9478
+ return false;
9299
9479
  }
9300
- function shouldSetDefault(options, existing) {
9301
- if (options.setDefault === true) {
9302
- return true;
9480
+ async function runPreCompactHook(config, options = {}) {
9481
+ try {
9482
+ const repoRoot = await gitValue(["rev-parse", "--show-toplevel"]);
9483
+ const project = repoRoot ? (0, import_node_path8.basename)(repoRoot) : "general";
9484
+ await runHandoff(config, {
9485
+ blockers: "- none recorded",
9486
+ dryRun: options.dryRun === true,
9487
+ nextStep: "Continue from this auto-snapshot. A manual `threadnote handoff` will produce a richer write-up if you have more context.",
9488
+ project,
9489
+ sourceAgentClient: "claude",
9490
+ task: "Auto-snapshot captured at Claude PreCompact (deterministic safety net before context compaction).",
9491
+ tests: "- not recorded (auto-snapshot)",
9492
+ topic: HOOK_AUTO_PRECOMPACT_TOPIC
9493
+ });
9494
+ } catch (err) {
9495
+ process.stderr.write(
9496
+ `threadnote pre-compact-hook: snapshot skipped (${err instanceof Error ? err.message : String(err)})
9497
+ `
9498
+ );
9303
9499
  }
9304
- return existing.defaultTeam === void 0;
9305
9500
  }
9306
- async function assertWorktreeUsable(worktree) {
9307
- if (!await exists(worktree)) {
9308
- return;
9309
- }
9310
- if (!await isDirectory(worktree)) {
9311
- throw new Error(`Cannot use ${worktree} as a worktree: not a directory.`);
9312
- }
9313
- const entries = await (0, import_promises8.readdir)(worktree);
9314
- if (entries.length > 0) {
9315
- const preview = entries.slice(0, 5).join(", ");
9316
- const suffix = entries.length > 5 ? `, +${entries.length - 5} more` : "";
9317
- throw new Error(
9318
- `Worktree ${worktree} is not empty (contains: ${preview}${suffix}). Move or remove its contents, then retry threadnote share init.`
9501
+ async function runSessionStartHook(config, options = {}) {
9502
+ try {
9503
+ const repoRoot = await gitValue(["rev-parse", "--show-toplevel"]);
9504
+ if (!repoRoot) {
9505
+ return;
9506
+ }
9507
+ const project = (0, import_node_path8.basename)(repoRoot);
9508
+ await emitUpdateBannerIfOutdated(config);
9509
+ process.stdout.write(`## Threadnote \u2014 latest context for ${project}
9510
+
9511
+ `);
9512
+ await runRecall(config, {
9513
+ dryRun: options.dryRun === true,
9514
+ inferScope: true,
9515
+ nodeLimit: "5",
9516
+ query: `${project} latest handoff durable feature memory`
9517
+ });
9518
+ } catch (err) {
9519
+ process.stderr.write(
9520
+ `threadnote session-start-hook: recall skipped (${err instanceof Error ? err.message : String(err)})
9521
+ `
9319
9522
  );
9320
9523
  }
9321
9524
  }
9322
- async function ingestWorktreeFiles(config, team, initialMode) {
9323
- const ov = await openVikingCliForMode(false);
9324
- const files = await walkMemoryFiles(team.worktree);
9325
- for (const file of files) {
9326
- const uri = workfileToVikingUri(config, team, file);
9327
- await ensureSharedDirectoryChain(config, ov, uri, false);
9328
- await ingestSingleFile(ov, config, uri, file, initialMode);
9525
+ async function emitUpdateBannerIfOutdated(config) {
9526
+ try {
9527
+ const result = await checkForThreadnoteUpdate({
9528
+ cachePath: (0, import_node_path8.join)(config.agentContextHome, ".update-state.json"),
9529
+ currentVersion: getThreadnoteVersion()
9530
+ });
9531
+ if (!result || !result.outdated) {
9532
+ return;
9533
+ }
9534
+ if (process.env.THREADNOTE_AUTO_UPDATE === "1") {
9535
+ process.stdout.write(
9536
+ `[threadnote] v${result.latestVersion} available (current v${result.currentVersion}). Auto-updating in the background; the new version takes effect next session.
9537
+
9538
+ `
9539
+ );
9540
+ spawnDetachedAutoUpdate();
9541
+ return;
9542
+ }
9543
+ process.stdout.write(
9544
+ `[threadnote] v${result.latestVersion} available (current v${result.currentVersion}). Run: threadnote update
9545
+
9546
+ `
9547
+ );
9548
+ } catch {
9329
9549
  }
9330
- return files.length;
9331
9550
  }
9332
- async function walkMemoryFiles(root) {
9333
- const out = [];
9334
- async function visit(path, depth) {
9335
- let entries;
9336
- try {
9337
- entries = await (0, import_promises8.readdir)(path, { withFileTypes: true });
9338
- } catch (err) {
9339
- console.warn(`Skipping ${path} during shared-tree walk: ${err instanceof Error ? err.message : String(err)}`);
9340
- return;
9551
+
9552
+ // src/seeding.ts
9553
+ var import_promises8 = require("node:fs/promises");
9554
+ var import_node_path9 = require("node:path");
9555
+ async function runSeed(config, options) {
9556
+ const manifest = await readSeedManifest(config.manifestPath);
9557
+ const ignorePatterns = await loadIgnorePatterns();
9558
+ const ov = await openVikingCliForMode(options.dryRun === true);
9559
+ const statePath = (0, import_node_path9.join)(config.agentContextHome, SEED_STATE_FILE);
9560
+ const state = options.force === true ? { files: {}, version: 1 } : await readSeedState(statePath);
9561
+ const projects = filterProjects(manifest.projects, options.only);
9562
+ let importedCount = 0;
9563
+ let skippedCount = 0;
9564
+ let unchangedCount = 0;
9565
+ for (const project of projects) {
9566
+ const projectRoot = expandPath(project.path);
9567
+ if (!await exists(projectRoot)) {
9568
+ console.log(`WARN project missing: ${project.name} (${projectRoot})`);
9569
+ continue;
9341
9570
  }
9342
- for (const entry of entries) {
9343
- if (entry.name === ".git") {
9344
- continue;
9345
- }
9346
- const full = (0, import_node_path9.join)(path, entry.name);
9347
- if (entry.isDirectory()) {
9348
- if (depth === 0 && !SHAREABLE_MEMORY_KIND_DIRS.includes(entry.name)) {
9349
- continue;
9350
- }
9351
- await visit(full, depth + 1);
9352
- continue;
9353
- }
9354
- if (!entry.isFile()) {
9355
- continue;
9356
- }
9357
- if (depth === 0) {
9571
+ const candidates = await collectSeedCandidates(project, projectRoot, ignorePatterns);
9572
+ for (const candidate of candidates) {
9573
+ const fileStat = await statSeedFile(candidate.filePath);
9574
+ const recorded = state.files[candidate.destinationUri];
9575
+ if (fileStat && recorded && recorded.mtimeMs === fileStat.mtimeMs && recorded.size === fileStat.size) {
9576
+ unchangedCount += 1;
9358
9577
  continue;
9359
9578
  }
9360
- if (!entry.name.endsWith(".md")) {
9579
+ const importPath = await prepareSeedFile(config, candidate, options.dryRun === true);
9580
+ if (!importPath) {
9581
+ skippedCount += 1;
9361
9582
  continue;
9362
9583
  }
9363
- out.push(full);
9584
+ const args = withIdentity(config, ["add-resource", importPath, "--to", candidate.destinationUri, "--wait"]);
9585
+ await maybeRun(options.dryRun === true, ov, args);
9586
+ importedCount += 1;
9587
+ if (fileStat && options.dryRun !== true) {
9588
+ state.files[candidate.destinationUri] = { mtimeMs: fileStat.mtimeMs, size: fileStat.size };
9589
+ }
9364
9590
  }
9365
9591
  }
9366
- await visit(root, 0);
9367
- return out;
9368
- }
9369
- function workfileToVikingUri(config, team, filePath) {
9370
- const rel = (0, import_node_path9.relative)(team.worktree, filePath).split(import_node_path9.sep).join("/");
9371
- return `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team.name}/${rel}`;
9372
- }
9373
- function isInSharedNamespace(config, uri) {
9374
- return uri.startsWith(`viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/`);
9375
- }
9376
- function isInTeamNamespace(config, uri, team) {
9377
- return uri.startsWith(`viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team}/`);
9378
- }
9379
- function sharedUriFor(config, personalUri, team) {
9380
- const prefix = `viking://user/${uriSegment(config.user)}/memories/`;
9381
- if (!personalUri.startsWith(prefix)) {
9382
- throw new Error(`Refusing to publish memory outside the current user namespace: ${personalUri}`);
9592
+ if (options.dryRun !== true) {
9593
+ await writeSeedState(statePath, state);
9383
9594
  }
9384
- const rest = personalUri.slice(prefix.length);
9385
- return `${prefix}${SHARED_SEGMENT}/${team}/${rest}`;
9595
+ console.log(
9596
+ `Seed complete: ${importedCount} candidate(s), ${unchangedCount} unchanged, ${skippedCount} skipped for safety.`
9597
+ );
9386
9598
  }
9387
- function personalUriFor(config, sharedUri, team) {
9388
- const prefix = `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team}/`;
9389
- if (!sharedUri.startsWith(prefix)) {
9390
- throw new Error(`Refusing to unpublish a URI outside team "${team}" shared namespace: ${sharedUri}`);
9599
+ function filterProjects(projects, only) {
9600
+ if (!only || only.length === 0) {
9601
+ return projects;
9391
9602
  }
9392
- const rest = sharedUri.slice(prefix.length);
9393
- return `viking://user/${uriSegment(config.user)}/memories/${rest}`;
9603
+ const known = new Set(projects.map((project) => project.name));
9604
+ const missing = only.filter((name) => !known.has(name));
9605
+ if (missing.length > 0) {
9606
+ const all = [...known].join(", ");
9607
+ throw new Error(`Unknown project(s) in --only: ${missing.join(", ")}. Manifest projects: ${all}`);
9608
+ }
9609
+ const want = new Set(only);
9610
+ return projects.filter((project) => want.has(project.name));
9394
9611
  }
9395
- function vikingUriToWorktreeRelative(config, uri, team) {
9396
- const prefix = `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/${team}/`;
9397
- if (!uri.startsWith(prefix)) {
9398
- throw new Error(`URI ${uri} is not inside team "${team}" shared subtree.`);
9612
+ async function statSeedFile(path) {
9613
+ try {
9614
+ const result = await (0, import_promises8.stat)(path);
9615
+ return { mtimeMs: result.mtimeMs, size: result.size };
9616
+ } catch (_err) {
9617
+ return void 0;
9399
9618
  }
9400
- return uri.slice(prefix.length);
9401
9619
  }
9402
- function stripPersonalProvenance(content) {
9403
- const lines = content.split("\n");
9404
- let headerEnd = lines.length;
9405
- for (let index = 0; index < lines.length; index += 1) {
9406
- if (lines[index].trim() === "") {
9407
- headerEnd = index;
9408
- break;
9620
+ async function readSeedState(path) {
9621
+ try {
9622
+ const raw = await (0, import_promises8.readFile)(path, "utf8");
9623
+ const parsed = JSON.parse(raw);
9624
+ if (parsed.version !== 1 || !isJsonObject(parsed.files)) {
9625
+ return { files: {}, version: 1 };
9409
9626
  }
9410
- }
9411
- const cleaned = [];
9412
- for (let index = 0; index < headerEnd; index += 1) {
9413
- if (/^(?:supersedes|archived_from):\s/.test(lines[index])) {
9414
- continue;
9627
+ const files = {};
9628
+ for (const [uri, entry] of Object.entries(parsed.files)) {
9629
+ if (isJsonObject(entry) && typeof entry.mtimeMs === "number" && typeof entry.size === "number") {
9630
+ files[uri] = { mtimeMs: entry.mtimeMs, size: entry.size };
9631
+ }
9415
9632
  }
9416
- cleaned.push(lines[index]);
9417
- }
9418
- for (let index = headerEnd; index < lines.length; index += 1) {
9419
- cleaned.push(lines[index]);
9633
+ return { files, version: 1 };
9634
+ } catch (_err) {
9635
+ return { files: {}, version: 1 };
9420
9636
  }
9421
- return cleaned.join("\n");
9422
9637
  }
9423
- async function readMemoryContent(config, ov, uri, dryRun) {
9424
- const args = withIdentity(config, ["read", uri]);
9425
- if (dryRun) {
9426
- console.log(`Would run: ${formatShellCommand(ov, args)}`);
9427
- return "<dry-run memory body>";
9428
- }
9429
- const result = await runCommand(ov, args);
9430
- if (!result.stdout.trim()) {
9431
- throw new Error(`Refusing to publish empty memory at ${uri}`);
9432
- }
9433
- return result.stdout;
9638
+ async function writeSeedState(path, state) {
9639
+ await ensureDirectory((0, import_node_path9.dirname)(path), false);
9640
+ await (0, import_promises8.writeFile)(path, `${JSON.stringify(state, void 0, 2)}
9641
+ `, { encoding: "utf8", mode: 384 });
9434
9642
  }
9435
- async function ensureSharedDirectoryChain(config, ov, memoryUri, dryRun) {
9436
- const directoryUri = parentUri(memoryUri);
9437
- for (const uri of sharedDirectoryChain(config, directoryUri)) {
9438
- const args = withIdentity(config, ["stat", uri]);
9439
- if (dryRun) {
9440
- console.log(`Would run: ${formatShellCommand(ov, args)}`);
9441
- continue;
9442
- }
9443
- const statResult = await runCommand(ov, args, { allowFailure: true });
9444
- if (statResult.exitCode === 0) {
9643
+ async function runInitManifest(config, options) {
9644
+ const manifestPath = expandPath(
9645
+ options.path ?? process.env.THREADNOTE_MANIFEST ?? (0, import_node_path9.join)(config.agentContextHome, USER_MANIFEST_NAME)
9646
+ );
9647
+ const repoInputs = options.repo && options.repo.length > 0 ? options.repo : [getInvocationCwd()];
9648
+ const existingManifest = options.replace === true || !await exists(manifestPath) ? void 0 : await readSeedManifest(manifestPath);
9649
+ const existingProjects = existingManifest?.projects ?? [];
9650
+ const projects = [...existingProjects];
9651
+ const seen = /* @__PURE__ */ new Set();
9652
+ for (const project of existingProjects) {
9653
+ seen.add(await projectIdentity(project.path));
9654
+ }
9655
+ for (const repoInput of repoInputs) {
9656
+ const repoRoot = await resolveRepoRoot(repoInput);
9657
+ const identity = await projectIdentity(repoRoot);
9658
+ if (seen.has(identity)) {
9659
+ console.log(`Already in manifest: ${repoRoot}`);
9445
9660
  continue;
9446
9661
  }
9447
- await maybeRun(false, ov, withIdentity(config, ["mkdir", uri, "--description", "Threadnote shared memories."]));
9662
+ seen.add(identity);
9663
+ projects.push(projectManifestForRepo(repoRoot, projects));
9448
9664
  }
9449
- }
9450
- function parentUri(uri) {
9451
- const lastSlash = uri.lastIndexOf("/");
9452
- return lastSlash === -1 ? uri : uri.slice(0, lastSlash);
9453
- }
9454
- function sharedDirectoryChain(config, directoryUri) {
9455
- const prefix = `viking://user/${uriSegment(config.user)}/memories/${SHARED_SEGMENT}/`;
9456
- if (!directoryUri.startsWith(prefix)) {
9457
- return [directoryUri];
9665
+ const outputManifest = {
9666
+ version: 1,
9667
+ projects: projects.map((project) => ({
9668
+ name: project.name,
9669
+ path: project.path,
9670
+ uri: project.uri,
9671
+ seed: [...project.seed]
9672
+ }))
9673
+ };
9674
+ if (existingManifest?.futureMonorepo) {
9675
+ const futureMonorepoKey = "future_monorepo";
9676
+ const pathCandidatesKey = "path_candidates";
9677
+ outputManifest[futureMonorepoKey] = {
9678
+ [pathCandidatesKey]: [...existingManifest.futureMonorepo.pathCandidates],
9679
+ uri: existingManifest.futureMonorepo.uri
9680
+ };
9458
9681
  }
9459
- const parts = directoryUri.slice(prefix.length).split("/").filter(Boolean);
9460
- const chain = [];
9461
- for (let index = 1; index <= parts.length; index += 1) {
9462
- chain.push(`${prefix}${parts.slice(0, index).join("/")}`);
9682
+ const output2 = jsYaml.dump(outputManifest, { lineWidth: 120, noRefs: true });
9683
+ if (options.dryRun === true) {
9684
+ console.log(`# Would write ${manifestPath}`);
9685
+ console.log(output2.trimEnd());
9686
+ return;
9463
9687
  }
9464
- return chain;
9688
+ await ensureDirectory((0, import_node_path9.dirname)(manifestPath), false);
9689
+ await (0, import_promises8.writeFile)(manifestPath, output2, { encoding: "utf8", mode: 384 });
9690
+ await (0, import_promises8.chmod)(manifestPath, 384);
9691
+ console.log(`Wrote manifest: ${manifestPath}`);
9692
+ console.log("Seed with:");
9693
+ console.log(" threadnote seed --dry-run");
9694
+ console.log(" threadnote seed");
9465
9695
  }
9466
- async function writeMemoryFile(config, ov, uri, content, initialMode, dryRun) {
9467
- if (dryRun) {
9468
- const args = withIdentity(config, [
9469
- "write",
9470
- uri,
9471
- "--from-file",
9472
- "<staged temp file>",
9473
- "--mode",
9474
- initialMode,
9475
- "--wait",
9476
- "--timeout",
9477
- "120"
9478
- ]);
9479
- console.log(`Would run: ${formatShellCommand(ov, args)}`);
9480
- return;
9696
+ async function runSeedSkills(config, options) {
9697
+ const ov = await openVikingCliForMode(options.dryRun === true);
9698
+ const skills = await collectSkillCandidates(config);
9699
+ const nativeMode = options.native === true;
9700
+ console.log(
9701
+ nativeMode ? "Skill seed mode: native OpenViking skills. This requires a working VLM config." : "Skill seed mode: resource catalog. Use --native only after configuring a working VLM provider."
9702
+ );
9703
+ for (const skill of skills) {
9704
+ console.log(`Skill ${skill.source}: ${skill.filePath}`);
9705
+ const args = nativeMode ? ["add-skill", skill.filePath, "--wait"] : ["add-resource", skill.filePath, "--to", skillResourceUri(skill), "--wait"];
9706
+ await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
9707
+ }
9708
+ console.log(`Skill seed complete: ${skills.length} unique skill(s).`);
9709
+ }
9710
+ async function resolveRepoRoot(repoInput) {
9711
+ const inputPath = expandPath(repoInput);
9712
+ if (!await isDirectory(inputPath)) {
9713
+ throw new Error(`Repo path is not a directory: ${inputPath}`);
9481
9714
  }
9482
- const stagingDir = await (0, import_promises8.mkdtemp)((0, import_node_path9.join)((0, import_node_os4.tmpdir)(), "threadnote-share-"));
9483
- const tempPath = (0, import_node_path9.join)(stagingDir, "body.txt");
9715
+ return await gitValue(["rev-parse", "--show-toplevel"], inputPath) ?? inputPath;
9716
+ }
9717
+ async function projectIdentity(path) {
9718
+ const expanded = expandPath(path);
9484
9719
  try {
9485
- await (0, import_promises8.writeFile)(tempPath, content, { encoding: "utf8", mode: 384 });
9486
- await writeOvFileWithRetry(config, ov, uri, tempPath, initialMode);
9487
- } finally {
9488
- await (0, import_promises8.rm)(stagingDir, { force: true, recursive: true });
9720
+ return await (0, import_promises8.realpath)(expanded);
9721
+ } catch (_err) {
9722
+ return expanded;
9489
9723
  }
9490
9724
  }
9491
- async function writeOvFileWithRetry(config, ov, uri, fromFile, initialMode) {
9492
- const maxAttempts = 4;
9493
- const existedBeforeWrite = await vikingResourceExists2(ov, config, uri);
9494
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
9495
- const existsNow = attempt === 0 ? existedBeforeWrite : await vikingResourceExists2(ov, config, uri);
9496
- const ourWriteLanded = existsNow && !existedBeforeWrite;
9497
- const mode = attempt === 0 ? initialMode : ourWriteLanded ? "replace" : initialMode;
9498
- const args = withIdentity(config, [
9499
- "write",
9500
- uri,
9501
- "--from-file",
9502
- fromFile,
9503
- "--mode",
9504
- mode,
9505
- "--wait",
9506
- "--timeout",
9507
- "120"
9508
- ]);
9509
- console.log(`${attempt === 0 ? "Running" : "Retrying"}: ${formatShellCommand(ov, args)}`);
9510
- const result = await runCommand(ov, args, { allowFailure: true });
9511
- if (result.exitCode === 0) {
9512
- if (result.stdout.trim()) {
9513
- console.log(result.stdout.trim());
9514
- }
9515
- if (result.stderr.trim()) {
9516
- console.error(result.stderr.trim());
9517
- }
9518
- return;
9519
- }
9520
- if (isTransientOvFailure(result.stderr, result.stdout) && await vikingResourceExists2(ov, config, uri) && !existedBeforeWrite) {
9521
- console.log("OpenViking accepted the write but returned an error before the wait completed; draining the queue.");
9522
- await waitForOvQueue(ov, config);
9523
- return;
9524
- }
9525
- if (!isTransientOvFailure(result.stderr, result.stdout) || attempt === maxAttempts - 1) {
9526
- throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
9725
+ function projectManifestForRepo(repoRoot, existingProjects) {
9726
+ const baseName = uriSegment((0, import_node_path9.basename)(repoRoot));
9727
+ const usedNames = new Set(existingProjects.map((project) => project.name));
9728
+ const usedUris = new Set(existingProjects.map((project) => project.uri));
9729
+ let name = baseName;
9730
+ let uri = `viking://resources/repos/${name}`;
9731
+ if (usedNames.has(name) || usedUris.has(uri)) {
9732
+ name = `${baseName}-${sha256(repoRoot).slice(0, 8)}`;
9733
+ uri = `viking://resources/repos/${name}`;
9734
+ }
9735
+ return {
9736
+ name,
9737
+ path: portablePath(repoRoot),
9738
+ seed: DEFAULT_SEED_PATTERNS,
9739
+ uri
9740
+ };
9741
+ }
9742
+ async function collectSeedCandidates(project, projectRoot, ignorePatterns) {
9743
+ const candidates = [];
9744
+ const seen = /* @__PURE__ */ new Set();
9745
+ for (const pattern of project.seed) {
9746
+ const files = await resolveProjectPattern(projectRoot, pattern);
9747
+ for (const filePath of files) {
9748
+ const relativePath = toPosixPath((0, import_node_path9.relative)(projectRoot, filePath));
9749
+ if (seen.has(relativePath) || matchesIgnore(relativePath, ignorePatterns)) {
9750
+ continue;
9751
+ }
9752
+ seen.add(relativePath);
9753
+ candidates.push({
9754
+ destinationUri: `${trimTrailingSlash(project.uri)}/${relativePath}`,
9755
+ filePath,
9756
+ projectName: project.name,
9757
+ relativePath
9758
+ });
9527
9759
  }
9528
- await sleep(1e3 * (attempt + 1));
9529
9760
  }
9761
+ return candidates;
9530
9762
  }
9531
- async function waitForOvQueue(ov, config) {
9532
- const result = await runCommand(ov, withIdentity(config, ["wait", "--timeout", "120"]), { allowFailure: true });
9533
- if (result.stdout.trim()) {
9534
- console.log(result.stdout.trim());
9763
+ async function resolveProjectPattern(projectRoot, pattern) {
9764
+ const normalizedPattern = toPosixPath(pattern);
9765
+ if (!hasGlob(normalizedPattern)) {
9766
+ const filePath = (0, import_node_path9.join)(projectRoot, normalizedPattern);
9767
+ return await isFile(filePath) ? [filePath] : [];
9535
9768
  }
9536
- if (result.stderr.trim()) {
9537
- console.error(result.stderr.trim());
9769
+ const globBase = getGlobBase(normalizedPattern);
9770
+ const basePath = (0, import_node_path9.join)(projectRoot, globBase);
9771
+ if (!await exists(basePath)) {
9772
+ return [];
9538
9773
  }
9774
+ const regex = globToRegExp(normalizedPattern);
9775
+ const files = await walkFiles(basePath);
9776
+ return files.filter((filePath) => regex.test(toPosixPath((0, import_node_path9.relative)(projectRoot, filePath))));
9539
9777
  }
9540
- function isTransientOvFailure(stderr, stdout) {
9541
- const output2 = `${stderr}
9542
- ${stdout}`.toLowerCase();
9543
- return output2.includes("resource is busy") || output2.includes("resource is being processed") || output2.includes("network error") || output2.includes("error sending request") || output2.includes("http request failed") || output2.includes("connection refused") || output2.includes("connection reset") || output2.includes("timed out");
9544
- }
9545
- async function ingestSingleFile(ov, config, uri, filePath, initialMode) {
9546
- const content = await (0, import_promises8.readFile)(filePath, "utf8");
9547
- await writeMemoryFile(config, ov, uri, content, initialMode, false);
9548
- }
9549
- async function removeWithRollback(config, ov, sourceUri, rollbackUri, worktree, dryRun, label) {
9550
- try {
9551
- await removeMemoryUri(config, ov, sourceUri, dryRun);
9552
- } catch (sourceErr) {
9553
- if (dryRun) {
9554
- throw sourceErr;
9555
- }
9556
- console.error(
9557
- `Source removal failed during ${label}; rolling back ${rollbackUri} so the system is back to the pre-${label} state.`
9778
+ async function prepareSeedFile(config, candidate, dryRun) {
9779
+ const content = await (0, import_promises8.readFile)(candidate.filePath, "utf8");
9780
+ const redactedContent = shouldRedactPath(candidate.relativePath) ? redactContent(candidate.relativePath, content) : content;
9781
+ const secretMatches = detectSecretMatches(redactedContent);
9782
+ if (secretMatches.length > 0) {
9783
+ console.log(
9784
+ `SKIP ${candidate.projectName}/${candidate.relativePath}: possible secret (${secretMatches.slice(0, MAX_SECRET_MATCHES_TO_PRINT).join(", ")})`
9558
9785
  );
9559
- try {
9560
- await removeMemoryUri(config, ov, rollbackUri, false);
9561
- } catch (rollbackErr) {
9562
- console.error(
9563
- `Rollback of ${rollbackUri} also failed. Manual cleanup needed via: threadnote forget ${rollbackUri}
9564
- Rollback error: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`
9565
- );
9566
- }
9567
- await bestEffortRemoveWorktreeFile(rollbackUri, worktree, label);
9568
- throw sourceErr;
9569
- }
9570
- }
9571
- async function bestEffortRemoveWorktreeFile(rollbackUri, worktree, label) {
9572
- if (label !== "publish") {
9573
- return;
9574
- }
9575
- const prefix = "viking://";
9576
- if (!rollbackUri.startsWith(prefix)) {
9577
- return;
9786
+ return void 0;
9578
9787
  }
9579
- const parts = rollbackUri.slice(prefix.length).split("/");
9580
- const sharedIndex = parts.indexOf("shared");
9581
- if (sharedIndex === -1 || sharedIndex + 2 >= parts.length) {
9582
- return;
9788
+ if (redactedContent === content) {
9789
+ return candidate.filePath;
9583
9790
  }
9584
- const relative3 = parts.slice(sharedIndex + 2).join("/");
9585
- if (!relative3) {
9586
- return;
9791
+ const redactedPath = (0, import_node_path9.join)(config.agentContextHome, "redacted", candidate.projectName, candidate.relativePath);
9792
+ if (dryRun) {
9793
+ console.log(`Would write redacted copy: ${redactedPath}`);
9794
+ return redactedPath;
9587
9795
  }
9588
- await (0, import_promises8.rm)((0, import_node_path9.join)(worktree, relative3), { force: true });
9796
+ await ensureDirectory((0, import_node_path9.dirname)(redactedPath), false);
9797
+ await (0, import_promises8.writeFile)(redactedPath, redactedContent, { encoding: "utf8", mode: 384 });
9798
+ await (0, import_promises8.chmod)(redactedPath, 384);
9799
+ return redactedPath;
9589
9800
  }
9590
- async function removeMemoryUri(config, ov, uri, dryRun) {
9591
- const args = withIdentity(config, ["rm", uri]);
9592
- if (dryRun) {
9593
- console.log(`Would run: ${formatShellCommand(ov, args)}`);
9594
- return;
9801
+ async function collectSkillCandidates(config) {
9802
+ const sources = [
9803
+ { pattern: "~/.codex/skills/**/SKILL.md", source: "codex-global" },
9804
+ { pattern: "~/.codex/plugins/cache/**/skills/**/SKILL.md", source: "codex-plugin-cache" },
9805
+ { pattern: "~/.claude/skills/**/SKILL.md", source: "claude-global" }
9806
+ ];
9807
+ try {
9808
+ const manifest = await readSeedManifest(config.manifestPath);
9809
+ for (const project of manifest.projects) {
9810
+ sources.push({
9811
+ pattern: `${project.path}/.claude/skills/**/SKILL.md`,
9812
+ source: `repo-local:${project.name}`
9813
+ });
9814
+ }
9815
+ } catch (err) {
9816
+ console.log(`WARN cannot read manifest for repo-local skill discovery: ${errorMessage(err)}`);
9595
9817
  }
9596
- const maxAttempts = 4;
9597
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
9598
- const result = await runCommand(ov, args, { allowFailure: true });
9599
- if (result.exitCode === 0) {
9600
- if (result.stdout.trim()) {
9601
- console.log(result.stdout.trim());
9818
+ const seenHashes = /* @__PURE__ */ new Set();
9819
+ const skills = [];
9820
+ for (const source of sources) {
9821
+ const files = await resolveAbsolutePattern(expandPath(source.pattern));
9822
+ for (const filePath of files) {
9823
+ const content = await (0, import_promises8.readFile)(filePath, "utf8");
9824
+ const matches = detectSecretMatches(content);
9825
+ if (matches.length > 0) {
9826
+ console.log(`SKIP skill with possible secret: ${filePath}`);
9827
+ continue;
9602
9828
  }
9603
- return;
9604
- }
9605
- if (!isTransientOvFailure(result.stderr, result.stdout) || attempt === maxAttempts - 1) {
9606
- throw new Error(`${formatShellCommand(ov, args)} failed: ${result.stderr || result.stdout}`);
9829
+ const hash = sha256(content);
9830
+ if (seenHashes.has(hash)) {
9831
+ continue;
9832
+ }
9833
+ seenHashes.add(hash);
9834
+ skills.push({ filePath, hash, source: source.source });
9607
9835
  }
9608
- await sleep(1e3 * (attempt + 1));
9609
9836
  }
9837
+ return skills;
9610
9838
  }
9611
- async function vikingResourceExists2(ov, config, uri) {
9612
- const result = await runCommand(ov, withIdentity(config, ["stat", uri]), { allowFailure: true });
9613
- return result.exitCode === 0;
9614
- }
9615
- async function hasUncommittedChanges(worktree) {
9616
- const result = await runCommand("git", ["-C", worktree, "status", "--porcelain"], { allowFailure: true });
9617
- return result.stdout.trim().length > 0;
9618
- }
9619
- async function gitOutput(worktree, args, dryRun) {
9620
- if (dryRun) {
9621
- return void 0;
9622
- }
9623
- const result = await runCommand("git", ["-C", worktree, ...args], { allowFailure: true });
9624
- if (result.exitCode !== 0) {
9625
- return void 0;
9839
+ async function resolveAbsolutePattern(pattern) {
9840
+ const normalizedPattern = toPosixPath(pattern);
9841
+ if (!hasGlob(normalizedPattern)) {
9842
+ return await isFile(normalizedPattern) ? [normalizedPattern] : [];
9626
9843
  }
9627
- return result.stdout.trim();
9628
- }
9629
- async function listChangedFiles(worktree, beforeRev, afterRev) {
9630
- const result = await runCommand("git", ["-C", worktree, "diff", "--name-status", "-z", `${beforeRev}..${afterRev}`], {
9631
- allowFailure: true
9632
- });
9633
- if (result.exitCode !== 0) {
9844
+ const globBase = getGlobBase(normalizedPattern);
9845
+ const basePath = globBase.startsWith("/") ? globBase : `/${globBase}`;
9846
+ if (!await exists(basePath)) {
9634
9847
  return [];
9635
9848
  }
9636
- const entries = result.stdout.split("\0").filter((part) => part.length > 0);
9637
- const changes = [];
9638
- for (let index = 0; index < entries.length; ) {
9639
- const raw = entries[index];
9640
- const head = raw.slice(0, 1);
9641
- if (head === "R" || head === "C") {
9642
- const oldRel = entries[index + 1];
9643
- const newRel = entries[index + 2];
9644
- if (oldRel && newRel) {
9645
- changes.push({ path: (0, import_node_path9.join)(worktree, oldRel), relativePath: oldRel, status: "removed" });
9646
- changes.push({ path: (0, import_node_path9.join)(worktree, newRel), relativePath: newRel, status: "added" });
9849
+ const regex = globToRegExp(normalizedPattern);
9850
+ const files = await walkFiles(basePath);
9851
+ return files.filter((filePath) => regex.test(toPosixPath(filePath)));
9852
+ }
9853
+ function skillResourceUri(skill) {
9854
+ return `viking://resources/agent-skills/${uriSegment(skill.source)}/${uriSegment((0, import_node_path9.basename)((0, import_node_path9.dirname)(skill.filePath)))}-${skill.hash.slice(0, 12)}.md`;
9855
+ }
9856
+ async function loadIgnorePatterns() {
9857
+ const raw = await (0, import_promises8.readFile)((0, import_node_path9.join)(toolRoot(), ".threadnoteignore"), "utf8");
9858
+ return raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
9859
+ }
9860
+ function matchesIgnore(relativePath, patterns) {
9861
+ const path = toPosixPath(relativePath);
9862
+ for (const pattern of patterns) {
9863
+ const normalizedPattern = toPosixPath(pattern);
9864
+ if (normalizedPattern.endsWith("/")) {
9865
+ const directory = normalizedPattern.slice(0, -1);
9866
+ if (path === directory || path.includes(`/${directory}/`) || path.startsWith(`${directory}/`)) {
9867
+ return true;
9647
9868
  }
9648
- index += 3;
9649
9869
  continue;
9650
9870
  }
9651
- const rel = entries[index + 1];
9652
- if (rel) {
9653
- const status = head === "A" ? "added" : head === "D" ? "removed" : "modified";
9654
- changes.push({ path: (0, import_node_path9.join)(worktree, rel), relativePath: rel, status });
9871
+ if (globToRegExp(normalizedPattern).test(path) || globToRegExp(`**/${normalizedPattern}`).test(path)) {
9872
+ return true;
9655
9873
  }
9656
- index += 2;
9657
9874
  }
9658
- return changes;
9875
+ return false;
9659
9876
  }
9660
- async function applyChangesToOpenViking(config, team, changes) {
9661
- const ov = await openVikingCliForMode(false);
9662
- for (const change of changes) {
9663
- if (!change.relativePath.endsWith(".md")) {
9664
- continue;
9665
- }
9666
- const firstSegment = change.relativePath.split("/")[0];
9667
- if (!SHAREABLE_MEMORY_KIND_DIRS.includes(firstSegment)) {
9668
- continue;
9669
- }
9670
- const uri = workfileToVikingUri(config, team, change.path);
9671
- if (change.status === "removed") {
9672
- await removeMemoryUri(config, ov, uri, false);
9673
- continue;
9674
- }
9675
- if (!await isFile(change.path)) {
9676
- continue;
9877
+ function shouldRedactPath(relativePath) {
9878
+ const path = toPosixPath(relativePath);
9879
+ return path.endsWith(".mcp.json") || path.endsWith("config.toml") || path.includes("/settings") || path.includes("/settings.local");
9880
+ }
9881
+ function redactContent(relativePath, content) {
9882
+ if (relativePath.endsWith(".json")) {
9883
+ try {
9884
+ const parsed = JSON.parse(content);
9885
+ return `${JSON.stringify(redactJsonValue(parsed), null, 2)}
9886
+ `;
9887
+ } catch (_err) {
9888
+ return redactText(content);
9677
9889
  }
9678
- const ovHasResource = await vikingResourceExists2(ov, config, uri);
9679
- if (ovHasResource) {
9680
- const reason = change.status === "modified" ? "overwriting local with upstream (local edits to the shared subtree are not preserved across sync)" : "aligning OV to upstream (resource pre-existed in OV, likely from an earlier local publish or sync)";
9681
- console.warn(`share sync: ${uri}: ${reason}.`);
9890
+ }
9891
+ return redactText(content);
9892
+ }
9893
+ function redactJsonValue(value) {
9894
+ if (Array.isArray(value)) {
9895
+ return value.map((item) => redactJsonValue(item));
9896
+ }
9897
+ if (!isJsonObject(value)) {
9898
+ return value;
9899
+ }
9900
+ const output2 = {};
9901
+ for (const [key, nestedValue] of Object.entries(value)) {
9902
+ output2[key] = isSensitiveKey(key) ? "[REDACTED]" : redactJsonValue(nestedValue);
9903
+ }
9904
+ return output2;
9905
+ }
9906
+ function isSensitiveKey(key) {
9907
+ return /token|secret|password|credential|authorization|api[_-]?key|client[_-]?secret|bearer/i.test(key);
9908
+ }
9909
+ function detectSecretMatches(content) {
9910
+ const detectors = [
9911
+ { label: "private-key", regex: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
9912
+ { label: "openai-key", regex: /sk-[A-Za-z0-9_-]{24,}/ },
9913
+ { label: "github-token", regex: /gh[pousr]_[A-Za-z0-9_]{24,}/ },
9914
+ { label: "slack-token", regex: /xox[abprs]-[A-Za-z0-9-]{24,}/ },
9915
+ { label: "bearer-token", regex: /Bearer\s+[A-Za-z0-9._~+/=-]{24,}/i },
9916
+ { label: "aws-access-key", regex: /AKIA[0-9A-Z]{16}/ }
9917
+ ];
9918
+ const matches = [];
9919
+ for (const detector of detectors) {
9920
+ if (detector.regex.test(content)) {
9921
+ matches.push(detector.label);
9682
9922
  }
9683
- await ensureSharedDirectoryChain(config, ov, uri, false);
9684
- const writeMode = ovHasResource ? "replace" : "create";
9685
- await ingestSingleFile(ov, config, uri, change.path, writeMode);
9686
9923
  }
9924
+ return matches;
9687
9925
  }
9688
9926
 
9689
9927
  // src/lifecycle.ts