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.
- package/README.md +7 -3
- package/dist/mcp_server.cjs +424 -27
- package/dist/threadnote.cjs +2351 -2113
- package/docs/agent-instructions.md +3 -2
- package/docs/index.html +10 -8
- package/docs/share.md +15 -2
- package/package.json +1 -1
package/dist/threadnote.cjs
CHANGED
|
@@ -3523,8 +3523,8 @@ var DEFAULT_SEED_PATTERNS = [
|
|
|
3523
3523
|
];
|
|
3524
3524
|
|
|
3525
3525
|
// src/hooks.ts
|
|
3526
|
-
var
|
|
3527
|
-
var
|
|
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
|
|
4491
|
-
var
|
|
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/
|
|
7234
|
-
|
|
7235
|
-
|
|
7236
|
-
|
|
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
|
-
|
|
7284
|
+
return { cleaned, redactions };
|
|
7239
7285
|
}
|
|
7240
|
-
|
|
7241
|
-
|
|
7242
|
-
|
|
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
|
-
|
|
7245
|
-
|
|
7246
|
-
|
|
7247
|
-
|
|
7248
|
-
|
|
7249
|
-
|
|
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
|
|
7252
|
-
|
|
7253
|
-
|
|
7254
|
-
|
|
7255
|
-
|
|
7256
|
-
|
|
7257
|
-
|
|
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
|
-
|
|
7260
|
-
|
|
7261
|
-
|
|
7262
|
-
|
|
7263
|
-
|
|
7264
|
-
|
|
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
|
-
|
|
7268
|
-
|
|
7269
|
-
|
|
7270
|
-
const
|
|
7271
|
-
|
|
7272
|
-
|
|
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
|
|
7276
|
-
const
|
|
7277
|
-
|
|
7278
|
-
|
|
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
|
-
|
|
7286
|
-
|
|
7287
|
-
|
|
7288
|
-
|
|
7289
|
-
|
|
7290
|
-
|
|
7291
|
-
|
|
7292
|
-
|
|
7293
|
-
|
|
7294
|
-
|
|
7295
|
-
|
|
7296
|
-
|
|
7297
|
-
|
|
7298
|
-
|
|
7299
|
-
|
|
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
|
-
|
|
7307
|
-
|
|
7308
|
-
|
|
7309
|
-
|
|
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
|
-
|
|
7313
|
-
if (
|
|
7314
|
-
|
|
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
|
-
|
|
7322
|
-
|
|
7323
|
-
await (0, import_promises4.rm)(migrationPath, { force: true });
|
|
7466
|
+
if (changes.length > 0) {
|
|
7467
|
+
pending.set(team, changes);
|
|
7324
7468
|
}
|
|
7325
7469
|
}
|
|
7326
|
-
|
|
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
|
|
7337
|
-
const
|
|
7338
|
-
|
|
7339
|
-
|
|
7340
|
-
|
|
7341
|
-
|
|
7342
|
-
|
|
7343
|
-
|
|
7344
|
-
|
|
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
|
-
|
|
7347
|
-
|
|
7348
|
-
|
|
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
|
-
|
|
7351
|
-
|
|
7352
|
-
|
|
7353
|
-
|
|
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
|
-
|
|
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
|
-
|
|
7393
|
-
const
|
|
7394
|
-
const
|
|
7395
|
-
|
|
7396
|
-
|
|
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
|
|
7411
|
-
|
|
7412
|
-
|
|
7413
|
-
|
|
7414
|
-
|
|
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
|
|
7423
|
-
|
|
7424
|
-
|
|
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
|
-
|
|
7427
|
-
Also searching seeded resources: ${projectResourceUri}`);
|
|
7428
|
-
await maybeRun(options.dryRun === true, ov, withIdentity(config, args));
|
|
7549
|
+
return statuses;
|
|
7429
7550
|
}
|
|
7430
|
-
async function
|
|
7431
|
-
|
|
7432
|
-
const
|
|
7433
|
-
const
|
|
7434
|
-
|
|
7435
|
-
|
|
7436
|
-
|
|
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
|
-
|
|
7441
|
-
|
|
7442
|
-
|
|
7443
|
-
|
|
7444
|
-
|
|
7445
|
-
|
|
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
|
-
|
|
7448
|
-
|
|
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
|
-
|
|
7451
|
-
|
|
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.
|
|
7454
|
-
|
|
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
|
|
7469
|
-
|
|
7470
|
-
const
|
|
7471
|
-
const
|
|
7472
|
-
const
|
|
7473
|
-
if (
|
|
7474
|
-
|
|
7475
|
-
|
|
7476
|
-
|
|
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 (
|
|
7493
|
-
|
|
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
|
|
7496
|
-
|
|
7497
|
-
|
|
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
|
-
|
|
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
|
|
7526
|
-
|
|
7527
|
-
|
|
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
|
|
7531
|
-
const
|
|
7532
|
-
|
|
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
|
|
7537
|
-
|
|
7538
|
-
|
|
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(
|
|
7541
|
-
await
|
|
7542
|
-
|
|
7543
|
-
|
|
7544
|
-
|
|
7545
|
-
)
|
|
7546
|
-
}
|
|
7547
|
-
|
|
7548
|
-
|
|
7549
|
-
|
|
7550
|
-
|
|
7551
|
-
|
|
7552
|
-
|
|
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
|
-
|
|
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
|
-
|
|
7579
|
-
|
|
7580
|
-
}
|
|
7581
|
-
|
|
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
|
|
7586
|
-
|
|
7587
|
-
|
|
7588
|
-
const
|
|
7589
|
-
|
|
7590
|
-
|
|
7591
|
-
|
|
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 (
|
|
7619
|
-
await (
|
|
7620
|
-
await
|
|
7621
|
-
|
|
7622
|
-
|
|
7623
|
-
|
|
7624
|
-
|
|
7625
|
-
|
|
7626
|
-
|
|
7627
|
-
|
|
7628
|
-
|
|
7629
|
-
|
|
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
|
|
7637
|
-
|
|
7638
|
-
|
|
7639
|
-
|
|
7640
|
-
|
|
7641
|
-
|
|
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
|
-
|
|
7672
|
-
const
|
|
7673
|
-
if (
|
|
7674
|
-
|
|
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
|
-
|
|
7677
|
-
|
|
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
|
|
7681
|
-
const
|
|
7682
|
-
|
|
7683
|
-
|
|
7684
|
-
|
|
7685
|
-
|
|
7686
|
-
|
|
7687
|
-
|
|
7688
|
-
|
|
7689
|
-
|
|
7690
|
-
|
|
7691
|
-
|
|
7692
|
-
|
|
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
|
|
7712
|
-
|
|
7713
|
-
|
|
7714
|
-
|
|
7715
|
-
|
|
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
|
-
|
|
7718
|
-
|
|
7719
|
-
|
|
7720
|
-
|
|
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
|
|
7725
|
-
|
|
7726
|
-
|
|
7727
|
-
|
|
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
|
-
|
|
7742
|
-
|
|
7743
|
-
|
|
7744
|
-
|
|
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
|
|
7793
|
+
return candidate;
|
|
7769
7794
|
}
|
|
7770
|
-
function
|
|
7771
|
-
return
|
|
7795
|
+
function teamsFilePath(config) {
|
|
7796
|
+
return (0, import_node_path4.join)(config.agentContextHome, "share", "teams.json");
|
|
7772
7797
|
}
|
|
7773
|
-
function
|
|
7774
|
-
|
|
7775
|
-
|
|
7776
|
-
|
|
7777
|
-
|
|
7778
|
-
|
|
7779
|
-
|
|
7780
|
-
|
|
7781
|
-
|
|
7782
|
-
|
|
7783
|
-
|
|
7784
|
-
|
|
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
|
|
7791
|
-
|
|
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
|
|
7795
|
-
const
|
|
7796
|
-
const
|
|
7797
|
-
|
|
7798
|
-
|
|
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
|
-
|
|
7811
|
-
|
|
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
|
-
|
|
7818
|
-
|
|
7819
|
-
|
|
7820
|
-
|
|
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
|
|
7825
|
-
|
|
7826
|
-
|
|
7827
|
-
|
|
7828
|
-
|
|
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
|
-
|
|
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
|
|
7847
|
-
const
|
|
7848
|
-
|
|
7849
|
-
const
|
|
7850
|
-
|
|
7851
|
-
|
|
7852
|
-
|
|
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
|
|
7862
|
-
const
|
|
7863
|
-
|
|
7864
|
-
|
|
7865
|
-
|
|
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
|
-
|
|
7874
|
-
|
|
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
|
|
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
|
|
7883
|
-
|
|
7884
|
-
|
|
7885
|
-
return "general";
|
|
7878
|
+
function shouldSetDefault(options, existing) {
|
|
7879
|
+
if (options.setDefault === true) {
|
|
7880
|
+
return true;
|
|
7886
7881
|
}
|
|
7887
|
-
|
|
7888
|
-
return trimmed.includes("/") ? (0, import_node_path4.basename)(trimmed) : trimmed;
|
|
7882
|
+
return existing.defaultTeam === void 0;
|
|
7889
7883
|
}
|
|
7890
|
-
function
|
|
7891
|
-
if (!
|
|
7892
|
-
return
|
|
7884
|
+
async function assertWorktreeUsable(worktree) {
|
|
7885
|
+
if (!await exists(worktree)) {
|
|
7886
|
+
return;
|
|
7893
7887
|
}
|
|
7894
|
-
|
|
7895
|
-
|
|
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
|
-
|
|
7901
|
-
|
|
7902
|
-
|
|
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
|
|
7915
|
-
const
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
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
|
|
7908
|
+
return files.length;
|
|
7924
7909
|
}
|
|
7925
|
-
async function
|
|
7926
|
-
const
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
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
|
-
|
|
7936
|
-
|
|
7937
|
-
|
|
7938
|
-
|
|
7939
|
-
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
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
|
-
|
|
7944
|
+
await visit(root, 0);
|
|
7945
|
+
return out;
|
|
7950
7946
|
}
|
|
7951
|
-
|
|
7952
|
-
const
|
|
7953
|
-
|
|
7954
|
-
|
|
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
|
|
7957
|
-
|
|
7958
|
-
|
|
7959
|
-
|
|
7960
|
-
|
|
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
|
-
|
|
7963
|
-
|
|
7964
|
-
|
|
7965
|
-
|
|
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
|
-
|
|
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
|
-
|
|
7979
|
-
|
|
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
|
-
|
|
7982
|
-
|
|
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
|
-
|
|
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
|
|
7996
|
-
|
|
7997
|
-
|
|
7998
|
-
|
|
7999
|
-
|
|
8000
|
-
|
|
8001
|
-
|
|
8002
|
-
|
|
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
|
-
|
|
8023
|
+
const statResult = await runCommand(ov, args, { allowFailure: true });
|
|
8024
|
+
if (statResult.exitCode === 0) {
|
|
8009
8025
|
continue;
|
|
8010
8026
|
}
|
|
8011
|
-
|
|
8012
|
-
|
|
8013
|
-
|
|
8014
|
-
|
|
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
|
|
8020
|
-
|
|
8034
|
+
function parentUri(uri) {
|
|
8035
|
+
const lastSlash = uri.lastIndexOf("/");
|
|
8036
|
+
return lastSlash === -1 ? uri : uri.slice(0, lastSlash);
|
|
8021
8037
|
}
|
|
8022
|
-
|
|
8023
|
-
|
|
8024
|
-
|
|
8025
|
-
|
|
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
|
-
|
|
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
|
|
8032
|
-
|
|
8033
|
-
const
|
|
8034
|
-
|
|
8035
|
-
|
|
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
|
|
8038
|
-
} catch (_err) {
|
|
8039
|
-
return void 0;
|
|
8066
|
+
return;
|
|
8040
8067
|
}
|
|
8041
|
-
|
|
8042
|
-
|
|
8043
|
-
|
|
8044
|
-
{
|
|
8045
|
-
|
|
8046
|
-
|
|
8047
|
-
{
|
|
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
|
|
8073
|
-
const
|
|
8074
|
-
|
|
8075
|
-
|
|
8076
|
-
|
|
8077
|
-
|
|
8078
|
-
|
|
8079
|
-
|
|
8080
|
-
|
|
8081
|
-
|
|
8082
|
-
|
|
8083
|
-
|
|
8084
|
-
|
|
8085
|
-
|
|
8086
|
-
|
|
8087
|
-
|
|
8088
|
-
|
|
8089
|
-
|
|
8090
|
-
|
|
8091
|
-
|
|
8092
|
-
|
|
8093
|
-
|
|
8094
|
-
|
|
8095
|
-
|
|
8096
|
-
|
|
8097
|
-
|
|
8098
|
-
|
|
8099
|
-
|
|
8100
|
-
|
|
8101
|
-
|
|
8102
|
-
|
|
8103
|
-
|
|
8104
|
-
|
|
8105
|
-
|
|
8106
|
-
|
|
8107
|
-
|
|
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
|
|
8133
|
-
const
|
|
8134
|
-
if (
|
|
8135
|
-
|
|
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
|
-
|
|
8141
|
-
|
|
8142
|
-
|
|
8143
|
-
|
|
8144
|
-
|
|
8145
|
-
|
|
8146
|
-
|
|
8147
|
-
|
|
8148
|
-
|
|
8149
|
-
|
|
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
|
-
|
|
8152
|
-
|
|
8153
|
-
|
|
8162
|
+
}
|
|
8163
|
+
async function bestEffortRemoveWorktreeFile(rollbackUri, worktree, label) {
|
|
8164
|
+
if (label !== "publish") {
|
|
8165
|
+
return;
|
|
8154
8166
|
}
|
|
8155
|
-
const
|
|
8156
|
-
if (
|
|
8157
|
-
|
|
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
|
-
|
|
8165
|
-
|
|
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
|
-
|
|
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
|
|
8170
|
-
|
|
8171
|
-
|
|
8172
|
-
if (
|
|
8173
|
-
|
|
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
|
-
|
|
8176
|
-
detached: true,
|
|
8177
|
-
stdio: "ignore"
|
|
8178
|
-
});
|
|
8179
|
-
child.unref();
|
|
8180
|
-
} catch {
|
|
8188
|
+
return;
|
|
8181
8189
|
}
|
|
8182
|
-
|
|
8183
|
-
|
|
8184
|
-
|
|
8185
|
-
|
|
8186
|
-
|
|
8187
|
-
|
|
8188
|
-
|
|
8189
|
-
|
|
8190
|
-
|
|
8191
|
-
|
|
8192
|
-
|
|
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
|
|
8201
|
-
const
|
|
8202
|
-
return
|
|
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
|
|
8205
|
-
const
|
|
8206
|
-
return
|
|
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
|
|
8209
|
-
|
|
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
|
-
|
|
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
|
-
|
|
8245
|
-
|
|
8246
|
-
|
|
8247
|
-
|
|
8248
|
-
|
|
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
|
-
|
|
8253
|
-
|
|
8254
|
-
|
|
8255
|
-
|
|
8256
|
-
|
|
8257
|
-
|
|
8258
|
-
|
|
8259
|
-
|
|
8260
|
-
|
|
8261
|
-
|
|
8262
|
-
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8266
|
-
|
|
8267
|
-
|
|
8268
|
-
|
|
8269
|
-
|
|
8270
|
-
|
|
8271
|
-
|
|
8272
|
-
|
|
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
|
|
8252
|
+
return changes;
|
|
8331
8253
|
}
|
|
8332
|
-
function
|
|
8333
|
-
|
|
8334
|
-
|
|
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
|
|
8343
|
-
if (
|
|
8344
|
-
|
|
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
|
-
|
|
8361
|
-
|
|
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
|
|
8364
|
-
if (
|
|
8365
|
-
|
|
8366
|
-
return;
|
|
8292
|
+
function parseMemoryStatus(value) {
|
|
8293
|
+
if (["active", "archived", "superseded"].includes(value)) {
|
|
8294
|
+
return value;
|
|
8367
8295
|
}
|
|
8368
|
-
|
|
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
|
|
8377
|
-
|
|
8378
|
-
|
|
8379
|
-
|
|
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
|
-
|
|
8382
|
-
|
|
8383
|
-
|
|
8384
|
-
|
|
8385
|
-
|
|
8386
|
-
|
|
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
|
|
8390
|
-
const
|
|
8391
|
-
|
|
8392
|
-
|
|
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
|
|
8395
|
-
const
|
|
8396
|
-
|
|
8397
|
-
|
|
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
|
-
|
|
8400
|
-
|
|
8401
|
-
|
|
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
|
-
|
|
8404
|
-
|
|
8373
|
+
} finally {
|
|
8374
|
+
if (!dryRun) {
|
|
8375
|
+
await (0, import_promises5.rm)(migrationPath, { force: true });
|
|
8405
8376
|
}
|
|
8406
8377
|
}
|
|
8407
|
-
|
|
8408
|
-
|
|
8409
|
-
|
|
8410
|
-
|
|
8411
|
-
|
|
8412
|
-
|
|
8413
|
-
|
|
8414
|
-
|
|
8415
|
-
|
|
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
|
-
|
|
8482
|
-
|
|
8483
|
-
|
|
8484
|
-
|
|
8485
|
-
const
|
|
8486
|
-
|
|
8487
|
-
|
|
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
|
-
|
|
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
|
-
|
|
8503
|
-
|
|
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
|
|
8514
|
-
|
|
8515
|
-
|
|
8516
|
-
|
|
8517
|
-
|
|
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
|
-
|
|
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
|
|
8529
|
-
if (
|
|
8530
|
-
|
|
8444
|
+
async function runRecall(config, options) {
|
|
8445
|
+
if (options.dryRun !== true) {
|
|
8446
|
+
await syncSharedReposAndLog(config);
|
|
8531
8447
|
}
|
|
8532
|
-
const
|
|
8533
|
-
const
|
|
8534
|
-
|
|
8535
|
-
|
|
8536
|
-
|
|
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
|
-
|
|
8539
|
-
|
|
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
|
|
8542
|
-
|
|
8543
|
-
|
|
8544
|
-
|
|
8545
|
-
|
|
8546
|
-
|
|
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
|
|
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
|
|
8552
|
-
|
|
8553
|
-
|
|
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
|
|
8557
|
-
|
|
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
|
-
|
|
8563
|
-
|
|
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
|
|
8568
|
-
|
|
8569
|
-
await (
|
|
8570
|
-
|
|
8571
|
-
|
|
8572
|
-
|
|
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
|
-
|
|
8585
|
-
|
|
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
|
-
|
|
8595
|
-
|
|
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
|
-
|
|
8612
|
-
|
|
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
|
|
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
|
|
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
|
|
8628
|
-
const
|
|
8629
|
-
|
|
8630
|
-
|
|
8631
|
-
|
|
8632
|
-
|
|
8633
|
-
|
|
8634
|
-
|
|
8635
|
-
|
|
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
|
-
|
|
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
|
-
|
|
8645
|
-
|
|
8646
|
-
|
|
8647
|
-
|
|
8648
|
-
|
|
8649
|
-
|
|
8650
|
-
|
|
8651
|
-
|
|
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
|
|
8655
|
-
|
|
8656
|
-
const
|
|
8657
|
-
|
|
8658
|
-
|
|
8659
|
-
|
|
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
|
-
|
|
8665
|
-
|
|
8666
|
-
|
|
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
|
|
8693
|
-
const
|
|
8694
|
-
|
|
8695
|
-
|
|
8696
|
-
|
|
8697
|
-
|
|
8698
|
-
|
|
8699
|
-
|
|
8700
|
-
|
|
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
|
|
8704
|
-
|
|
8705
|
-
|
|
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
|
|
8708
|
-
|
|
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
|
-
|
|
8718
|
-
|
|
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
|
|
8731
|
-
const
|
|
8732
|
-
|
|
8733
|
-
|
|
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
|
|
8748
|
-
const
|
|
8749
|
-
for (const
|
|
8750
|
-
const
|
|
8751
|
-
|
|
8752
|
-
|
|
8753
|
-
|
|
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
|
|
8759
|
-
|
|
8760
|
-
|
|
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
|
-
|
|
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
|
-
|
|
8779
|
-
|
|
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
|
|
8786
|
-
|
|
8787
|
-
|
|
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
|
|
8790
|
-
const
|
|
8791
|
-
|
|
8792
|
-
|
|
8793
|
-
|
|
8794
|
-
|
|
8795
|
-
|
|
8796
|
-
|
|
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
|
-
|
|
8726
|
+
if (result.stderr.trim()) {
|
|
8727
|
+
console.error(result.stderr.trim());
|
|
8728
|
+
}
|
|
8729
|
+
return;
|
|
8799
8730
|
}
|
|
8800
|
-
if (
|
|
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
|
|
8807
|
-
const
|
|
8808
|
-
return
|
|
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
|
|
8811
|
-
|
|
8812
|
-
|
|
8813
|
-
|
|
8814
|
-
|
|
8815
|
-
|
|
8816
|
-
|
|
8817
|
-
|
|
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
|
|
8823
|
-
|
|
8824
|
-
|
|
8825
|
-
|
|
8826
|
-
|
|
8827
|
-
|
|
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
|
|
8830
|
-
for (const
|
|
8831
|
-
|
|
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
|
|
8839
|
+
return candidates;
|
|
8834
8840
|
}
|
|
8835
|
-
function
|
|
8836
|
-
return /
|
|
8841
|
+
function lifecycleMigrationUri(config, metadata, hash) {
|
|
8842
|
+
return `${memoryDirectoryUri(config, metadata)}/legacy-${hash.slice(0, 16)}.md`;
|
|
8837
8843
|
}
|
|
8838
|
-
function
|
|
8839
|
-
const
|
|
8840
|
-
|
|
8841
|
-
{
|
|
8842
|
-
{
|
|
8843
|
-
{
|
|
8844
|
-
{
|
|
8845
|
-
{
|
|
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
|
-
|
|
8848
|
-
|
|
8849
|
-
|
|
8850
|
-
|
|
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
|
-
|
|
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
|
|
8909
|
-
if (!
|
|
8910
|
-
|
|
8884
|
+
async function memoryWriteMode(ov, config, memoryUri, metadata) {
|
|
8885
|
+
if (!shouldUseStableMemoryUri(metadata)) {
|
|
8886
|
+
return "create";
|
|
8911
8887
|
}
|
|
8912
|
-
|
|
8913
|
-
|
|
8914
|
-
|
|
8915
|
-
|
|
8916
|
-
|
|
8917
|
-
|
|
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
|
|
8921
|
-
const
|
|
8922
|
-
|
|
8923
|
-
|
|
8924
|
-
|
|
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
|
-
|
|
8927
|
-
|
|
8928
|
-
|
|
8929
|
-
|
|
8930
|
-
|
|
8931
|
-
|
|
8932
|
-
|
|
8933
|
-
|
|
8934
|
-
|
|
8935
|
-
|
|
8936
|
-
|
|
8937
|
-
|
|
8938
|
-
|
|
8939
|
-
|
|
8940
|
-
|
|
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
|
-
|
|
8943
|
-
|
|
8944
|
-
|
|
8945
|
-
|
|
8946
|
-
|
|
8947
|
-
|
|
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
|
-
|
|
8950
|
-
|
|
8951
|
-
|
|
8952
|
-
|
|
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
|
-
|
|
8956
|
-
|
|
8957
|
-
|
|
8958
|
-
|
|
8959
|
-
|
|
8960
|
-
const
|
|
8961
|
-
|
|
8962
|
-
|
|
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
|
|
8966
|
-
|
|
8967
|
-
|
|
8968
|
-
|
|
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
|
-
|
|
8971
|
-
|
|
8965
|
+
try {
|
|
8966
|
+
return parseMemoryKind(value);
|
|
8967
|
+
} catch (_err) {
|
|
8968
|
+
return void 0;
|
|
8972
8969
|
}
|
|
8973
|
-
|
|
8974
|
-
|
|
8970
|
+
}
|
|
8971
|
+
function parseOptionalMemoryStatus(value) {
|
|
8972
|
+
if (!value) {
|
|
8973
|
+
return void 0;
|
|
8975
8974
|
}
|
|
8976
|
-
|
|
8977
|
-
|
|
8978
|
-
|
|
8979
|
-
|
|
8980
|
-
|
|
8981
|
-
|
|
8982
|
-
|
|
8983
|
-
|
|
8984
|
-
|
|
8985
|
-
|
|
8986
|
-
|
|
8987
|
-
|
|
8988
|
-
|
|
8989
|
-
|
|
8990
|
-
|
|
8991
|
-
|
|
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
|
-
|
|
8995
|
-
|
|
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
|
-
|
|
8999
|
-
|
|
9000
|
-
|
|
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 (
|
|
9015
|
-
|
|
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
|
-
|
|
9019
|
-
|
|
9020
|
-
|
|
9021
|
-
|
|
9022
|
-
const
|
|
9023
|
-
|
|
9024
|
-
|
|
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
|
-
|
|
9027
|
-
|
|
9028
|
-
|
|
9029
|
-
|
|
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
|
-
|
|
9037
|
-
|
|
9038
|
-
|
|
9039
|
-
|
|
9040
|
-
|
|
9041
|
-
|
|
9042
|
-
|
|
9043
|
-
|
|
9044
|
-
|
|
9045
|
-
|
|
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
|
-
|
|
9049
|
-
|
|
9050
|
-
|
|
9108
|
+
return await (0, import_promises5.readFile)(path, "utf8");
|
|
9109
|
+
} catch (_err) {
|
|
9110
|
+
return void 0;
|
|
9051
9111
|
}
|
|
9052
|
-
|
|
9053
|
-
|
|
9054
|
-
|
|
9055
|
-
|
|
9056
|
-
|
|
9057
|
-
|
|
9058
|
-
|
|
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
|
-
|
|
9061
|
-
|
|
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
|
-
|
|
9065
|
-
const
|
|
9066
|
-
|
|
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
|
-
|
|
9069
|
-
|
|
9070
|
-
|
|
9071
|
-
|
|
9072
|
-
|
|
9073
|
-
|
|
9074
|
-
|
|
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
|
|
9077
|
-
|
|
9078
|
-
|
|
9079
|
-
|
|
9080
|
-
const
|
|
9081
|
-
if (
|
|
9082
|
-
|
|
9083
|
-
|
|
9084
|
-
|
|
9085
|
-
|
|
9086
|
-
|
|
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
|
-
|
|
9091
|
-
|
|
9092
|
-
|
|
9093
|
-
|
|
9094
|
-
|
|
9095
|
-
|
|
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
|
-
|
|
9099
|
-
|
|
9100
|
-
|
|
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
|
-
|
|
9104
|
-
|
|
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
|
-
|
|
9107
|
-
|
|
9108
|
-
|
|
9109
|
-
|
|
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
|
-
|
|
9113
|
-
|
|
9114
|
-
|
|
9115
|
-
|
|
9116
|
-
|
|
9117
|
-
|
|
9118
|
-
|
|
9119
|
-
|
|
9120
|
-
|
|
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
|
-
|
|
9136
|
-
|
|
9137
|
-
|
|
9138
|
-
|
|
9139
|
-
|
|
9140
|
-
|
|
9141
|
-
|
|
9142
|
-
|
|
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
|
-
|
|
9151
|
-
|
|
9152
|
-
|
|
9153
|
-
|
|
9154
|
-
|
|
9155
|
-
|
|
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
|
-
|
|
9330
|
+
return cachedVersion;
|
|
9162
9331
|
}
|
|
9163
|
-
|
|
9164
|
-
|
|
9165
|
-
|
|
9166
|
-
|
|
9167
|
-
|
|
9168
|
-
|
|
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
|
-
|
|
9171
|
-
|
|
9172
|
-
|
|
9173
|
-
|
|
9174
|
-
|
|
9175
|
-
|
|
9176
|
-
|
|
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
|
|
9180
|
-
const
|
|
9181
|
-
const
|
|
9182
|
-
const
|
|
9183
|
-
const
|
|
9184
|
-
|
|
9185
|
-
|
|
9186
|
-
|
|
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
|
-
|
|
9190
|
-
const
|
|
9191
|
-
|
|
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.
|
|
9199
|
-
|
|
9200
|
-
|
|
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
|
|
9206
|
-
const
|
|
9207
|
-
|
|
9208
|
-
|
|
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
|
-
|
|
9211
|
-
|
|
9212
|
-
|
|
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
|
-
|
|
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
|
|
9218
|
-
return (
|
|
9425
|
+
function isManagedThreadnoteEntry(value) {
|
|
9426
|
+
return isJsonObject(value) && value[THREADNOTE_HOOK_MARKER] === THREADNOTE_HOOK_MARKER_VALUE;
|
|
9219
9427
|
}
|
|
9220
|
-
function
|
|
9221
|
-
return (
|
|
9222
|
-
|
|
9223
|
-
|
|
9224
|
-
|
|
9225
|
-
|
|
9226
|
-
|
|
9227
|
-
|
|
9228
|
-
"
|
|
9229
|
-
|
|
9230
|
-
|
|
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
|
|
9234
|
-
|
|
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
|
|
9237
|
-
const path =
|
|
9238
|
-
|
|
9239
|
-
|
|
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
|
-
|
|
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
|
|
9252
|
-
|
|
9253
|
-
|
|
9254
|
-
|
|
9255
|
-
|
|
9256
|
-
|
|
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
|
-
|
|
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
|
|
9301
|
-
|
|
9302
|
-
|
|
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
|
|
9307
|
-
|
|
9308
|
-
|
|
9309
|
-
|
|
9310
|
-
|
|
9311
|
-
|
|
9312
|
-
|
|
9313
|
-
|
|
9314
|
-
|
|
9315
|
-
|
|
9316
|
-
|
|
9317
|
-
|
|
9318
|
-
|
|
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
|
|
9323
|
-
|
|
9324
|
-
|
|
9325
|
-
|
|
9326
|
-
|
|
9327
|
-
|
|
9328
|
-
|
|
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
|
-
|
|
9333
|
-
|
|
9334
|
-
|
|
9335
|
-
|
|
9336
|
-
|
|
9337
|
-
|
|
9338
|
-
|
|
9339
|
-
|
|
9340
|
-
|
|
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
|
-
|
|
9343
|
-
|
|
9344
|
-
|
|
9345
|
-
|
|
9346
|
-
|
|
9347
|
-
|
|
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
|
-
|
|
9579
|
+
const importPath = await prepareSeedFile(config, candidate, options.dryRun === true);
|
|
9580
|
+
if (!importPath) {
|
|
9581
|
+
skippedCount += 1;
|
|
9361
9582
|
continue;
|
|
9362
9583
|
}
|
|
9363
|
-
|
|
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
|
-
|
|
9367
|
-
|
|
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
|
-
|
|
9385
|
-
|
|
9595
|
+
console.log(
|
|
9596
|
+
`Seed complete: ${importedCount} candidate(s), ${unchangedCount} unchanged, ${skippedCount} skipped for safety.`
|
|
9597
|
+
);
|
|
9386
9598
|
}
|
|
9387
|
-
function
|
|
9388
|
-
|
|
9389
|
-
|
|
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
|
|
9393
|
-
|
|
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
|
|
9396
|
-
|
|
9397
|
-
|
|
9398
|
-
|
|
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
|
|
9403
|
-
|
|
9404
|
-
|
|
9405
|
-
|
|
9406
|
-
if (
|
|
9407
|
-
|
|
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
|
-
|
|
9412
|
-
|
|
9413
|
-
|
|
9414
|
-
|
|
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
|
-
|
|
9417
|
-
}
|
|
9418
|
-
|
|
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
|
|
9424
|
-
|
|
9425
|
-
|
|
9426
|
-
|
|
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
|
|
9436
|
-
const
|
|
9437
|
-
|
|
9438
|
-
|
|
9439
|
-
|
|
9440
|
-
|
|
9441
|
-
|
|
9442
|
-
|
|
9443
|
-
|
|
9444
|
-
|
|
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
|
-
|
|
9662
|
+
seen.add(identity);
|
|
9663
|
+
projects.push(projectManifestForRepo(repoRoot, projects));
|
|
9448
9664
|
}
|
|
9449
|
-
|
|
9450
|
-
|
|
9451
|
-
|
|
9452
|
-
|
|
9453
|
-
|
|
9454
|
-
|
|
9455
|
-
|
|
9456
|
-
|
|
9457
|
-
|
|
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
|
|
9460
|
-
|
|
9461
|
-
|
|
9462
|
-
|
|
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
|
-
|
|
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
|
|
9467
|
-
|
|
9468
|
-
|
|
9469
|
-
|
|
9470
|
-
|
|
9471
|
-
|
|
9472
|
-
|
|
9473
|
-
|
|
9474
|
-
|
|
9475
|
-
|
|
9476
|
-
|
|
9477
|
-
|
|
9478
|
-
|
|
9479
|
-
|
|
9480
|
-
|
|
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
|
-
|
|
9483
|
-
|
|
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.
|
|
9486
|
-
|
|
9487
|
-
|
|
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
|
-
|
|
9492
|
-
const
|
|
9493
|
-
const
|
|
9494
|
-
|
|
9495
|
-
|
|
9496
|
-
|
|
9497
|
-
|
|
9498
|
-
|
|
9499
|
-
|
|
9500
|
-
|
|
9501
|
-
|
|
9502
|
-
|
|
9503
|
-
|
|
9504
|
-
|
|
9505
|
-
|
|
9506
|
-
|
|
9507
|
-
|
|
9508
|
-
|
|
9509
|
-
|
|
9510
|
-
|
|
9511
|
-
|
|
9512
|
-
|
|
9513
|
-
|
|
9514
|
-
|
|
9515
|
-
if (
|
|
9516
|
-
|
|
9517
|
-
}
|
|
9518
|
-
|
|
9519
|
-
|
|
9520
|
-
|
|
9521
|
-
|
|
9522
|
-
|
|
9523
|
-
|
|
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
|
|
9532
|
-
const
|
|
9533
|
-
if (
|
|
9534
|
-
|
|
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
|
-
|
|
9537
|
-
|
|
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
|
|
9541
|
-
const
|
|
9542
|
-
|
|
9543
|
-
|
|
9544
|
-
|
|
9545
|
-
|
|
9546
|
-
|
|
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
|
-
|
|
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
|
-
|
|
9580
|
-
|
|
9581
|
-
if (sharedIndex === -1 || sharedIndex + 2 >= parts.length) {
|
|
9582
|
-
return;
|
|
9788
|
+
if (redactedContent === content) {
|
|
9789
|
+
return candidate.filePath;
|
|
9583
9790
|
}
|
|
9584
|
-
const
|
|
9585
|
-
if (
|
|
9586
|
-
|
|
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 (
|
|
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
|
|
9591
|
-
const
|
|
9592
|
-
|
|
9593
|
-
|
|
9594
|
-
|
|
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
|
|
9597
|
-
|
|
9598
|
-
|
|
9599
|
-
|
|
9600
|
-
|
|
9601
|
-
|
|
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
|
-
|
|
9604
|
-
|
|
9605
|
-
|
|
9606
|
-
|
|
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
|
|
9612
|
-
const
|
|
9613
|
-
|
|
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
|
-
|
|
9628
|
-
}
|
|
9629
|
-
|
|
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
|
|
9637
|
-
const
|
|
9638
|
-
|
|
9639
|
-
|
|
9640
|
-
|
|
9641
|
-
|
|
9642
|
-
|
|
9643
|
-
|
|
9644
|
-
|
|
9645
|
-
|
|
9646
|
-
|
|
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
|
-
|
|
9652
|
-
|
|
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
|
|
9875
|
+
return false;
|
|
9659
9876
|
}
|
|
9660
|
-
|
|
9661
|
-
const
|
|
9662
|
-
|
|
9663
|
-
|
|
9664
|
-
|
|
9665
|
-
|
|
9666
|
-
|
|
9667
|
-
|
|
9668
|
-
|
|
9669
|
-
|
|
9670
|
-
|
|
9671
|
-
|
|
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
|
-
|
|
9679
|
-
|
|
9680
|
-
|
|
9681
|
-
|
|
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
|