pantheon-cli 0.1.1 → 0.2.1

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.
Files changed (2) hide show
  1. package/dist/pantheon.mjs +397 -49
  2. package/package.json +1 -1
package/dist/pantheon.mjs CHANGED
@@ -21275,7 +21275,7 @@ import { homedir as homedir2 } from "node:os";
21275
21275
  import { basename as basename2, join as join2, resolve } from "node:path";
21276
21276
 
21277
21277
  // ../core/src/transcripts.ts
21278
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
21278
+ import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
21279
21279
  import { homedir } from "node:os";
21280
21280
  import { basename, join } from "node:path";
21281
21281
  var MAX_SCAN = 60;
@@ -21591,13 +21591,43 @@ function discoverLocalSessions(opts = {}) {
21591
21591
  function readLocalSession(session) {
21592
21592
  return readers[session.source](session.path);
21593
21593
  }
21594
+ var HINT_TAIL_BYTES = 256 * 1024;
21595
+ function tail(path, bytes = HINT_TAIL_BYTES) {
21596
+ try {
21597
+ const size = statSync(path).size;
21598
+ const length = Math.min(size, bytes);
21599
+ if (!length) return "";
21600
+ const fd = openSync(path, "r");
21601
+ try {
21602
+ const buf = Buffer.alloc(length);
21603
+ readSync(fd, buf, 0, length, size - length);
21604
+ return buf.toString("utf8");
21605
+ } finally {
21606
+ closeSync(fd);
21607
+ }
21608
+ } catch {
21609
+ return "";
21610
+ }
21611
+ }
21612
+ function preferNamed(candidates, hint3) {
21613
+ const needle = hint3?.trim().toLowerCase();
21614
+ if (!needle || needle.length < 3 || candidates.length < 2) return candidates;
21615
+ const named = new Set(
21616
+ candidates.filter((session) => tail(session.path).toLowerCase().includes(needle))
21617
+ );
21618
+ if (!named.size || named.size === candidates.length) return candidates;
21619
+ return [...candidates.filter((s) => named.has(s)), ...candidates.filter((s) => !named.has(s))];
21620
+ }
21594
21621
  function captureLocalTranscript(opts = {}) {
21595
21622
  const { sessionKey, minTurns = 2 } = opts;
21596
21623
  const cwd = opts.cwd || process.cwd();
21597
21624
  const scoped = discoverLocalSessions({ cwd, source: opts.source });
21598
21625
  const candidates = sessionKey ? discoverLocalSessions({ source: opts.source }).filter(
21599
21626
  (item) => item.key === sessionKey || item.key.endsWith(sessionKey)
21600
- ) : scoped.length ? scoped : discoverLocalSessions({ source: opts.source });
21627
+ ) : preferNamed(
21628
+ scoped.length ? scoped : discoverLocalSessions({ source: opts.source }),
21629
+ opts.hint
21630
+ );
21601
21631
  for (const session of candidates.slice(0, MAX_SCAN)) {
21602
21632
  const turns = readLocalSession(session);
21603
21633
  if (turns.length >= minTurns) return { session, turns };
@@ -21764,6 +21794,110 @@ function collectDiskArtifacts(turns) {
21764
21794
  }
21765
21795
  return found;
21766
21796
  }
21797
+ var WRITE_TOOL = /write|edit|patch|notebook|replace|create|save/i;
21798
+ var PATH_KEYS = [
21799
+ "path",
21800
+ "file_path",
21801
+ "filePath",
21802
+ "target_file",
21803
+ "target_notebook",
21804
+ "notebook_path",
21805
+ "absolute_path"
21806
+ ];
21807
+ function pathsFromPatch(input) {
21808
+ const body = typeof input === "string" ? input : input && typeof input === "object" ? String(input.input ?? input.patch ?? "") : "";
21809
+ if (!body.includes("***")) return [];
21810
+ const found = [];
21811
+ for (const match of body.matchAll(/^\*\*\*\s+(?:Add|Update|Move to) File:\s*(.+)$/gm)) {
21812
+ const path = match[1].trim();
21813
+ if (path) found.push(path);
21814
+ }
21815
+ return found;
21816
+ }
21817
+ var SKIP_PATH = /(^|\/)(node_modules|\.git|\.next|dist|build|out|coverage|\.turbo)(\/|$)|\.(lock|log)$|lock\.(json|yaml)$/;
21818
+ var MAX_WRITTEN_FILE = 512 * 1024;
21819
+ var MAX_WRITTEN_TOTAL = 8 * 1024 * 1024;
21820
+ var MAX_WRITTEN_COUNT = 200;
21821
+ function pathFromInput(input) {
21822
+ if (!input || typeof input !== "object") return null;
21823
+ const record2 = input;
21824
+ for (const key of PATH_KEYS) {
21825
+ const value = record2[key];
21826
+ if (typeof value === "string" && value.trim()) return value.trim();
21827
+ }
21828
+ return null;
21829
+ }
21830
+ function flatName(path, base) {
21831
+ const relative = path.startsWith(base) ? path.slice(base.length) : path;
21832
+ return relative.replace(/^[./]+/, "").replace(/[^a-zA-Z0-9._/-]/g, "_").replace(/\//g, "_");
21833
+ }
21834
+ function readArtifactFile(path, base) {
21835
+ const stat = statSync2(path);
21836
+ if (!stat.isFile() || stat.size === 0 || stat.size > MAX_WRITTEN_FILE) return null;
21837
+ const buf = readFileSync2(path);
21838
+ const binary = buf.includes(0);
21839
+ return {
21840
+ name: flatName(path, base),
21841
+ content: binary ? buf.toString("base64") : buf.toString("utf8"),
21842
+ encoding: binary ? "base64" : "utf8",
21843
+ bytes: stat.size
21844
+ };
21845
+ }
21846
+ function collectWrittenArtifacts(turns, cwd = process.cwd()) {
21847
+ const base = cwd.endsWith("/") ? cwd : `${cwd}/`;
21848
+ const latest = /* @__PURE__ */ new Set();
21849
+ const add = (path) => {
21850
+ const full = path.startsWith("/") ? path : join2(base, path);
21851
+ if (!SKIP_PATH.test(full)) latest.add(full);
21852
+ };
21853
+ for (const turn of turns) {
21854
+ for (const call of turn.toolCalls ?? []) {
21855
+ if (!WRITE_TOOL.test(call.name || "")) continue;
21856
+ const path = pathFromInput(call.input);
21857
+ if (path) add(path);
21858
+ for (const patched of pathsFromPatch(call.input)) add(patched);
21859
+ }
21860
+ }
21861
+ const found = [];
21862
+ let total = 0;
21863
+ for (const path of latest) {
21864
+ if (found.length >= MAX_WRITTEN_COUNT || total >= MAX_WRITTEN_TOTAL) break;
21865
+ try {
21866
+ if (!existsSync2(path)) continue;
21867
+ const file = readArtifactFile(path, base);
21868
+ if (!file) continue;
21869
+ total += file.bytes;
21870
+ found.push({ name: file.name, content: file.content, encoding: file.encoding });
21871
+ } catch {
21872
+ }
21873
+ }
21874
+ return found;
21875
+ }
21876
+ function collectAttachedArtifacts(turns, cwd = process.cwd()) {
21877
+ const base = cwd.endsWith("/") ? cwd : `${cwd}/`;
21878
+ const paths = /* @__PURE__ */ new Set();
21879
+ for (const turn of turns) {
21880
+ if (turn.role !== "user") continue;
21881
+ for (const match of (turn.text || "").matchAll(/(?:^|[\s"'`(@])(\/[\w./@ -]*\/[\w.@-]+\.[a-zA-Z0-9]{1,16})/g)) {
21882
+ const path = match[1].trim();
21883
+ if (!SKIP_PATH.test(path)) paths.add(path);
21884
+ }
21885
+ }
21886
+ const found = [];
21887
+ let total = 0;
21888
+ for (const path of paths) {
21889
+ if (found.length >= 40 || total >= MAX_WRITTEN_TOTAL) break;
21890
+ try {
21891
+ if (!existsSync2(path)) continue;
21892
+ const file = readArtifactFile(path, base);
21893
+ if (!file) continue;
21894
+ total += file.bytes;
21895
+ found.push({ name: file.name, content: file.content, encoding: file.encoding });
21896
+ } catch {
21897
+ }
21898
+ }
21899
+ return found;
21900
+ }
21767
21901
  function missingGeneratedFiles(turns, artifacts = []) {
21768
21902
  const mentioned = mentionedDocuments(turns).map((doc) => doc.name);
21769
21903
  if (!mentioned.length) return null;
@@ -21774,12 +21908,38 @@ function missingGeneratedFiles(turns, artifacts = []) {
21774
21908
  }
21775
21909
  var PACKET_TURNS = 14;
21776
21910
  var PACKET_TURN_CHARS = 400;
21777
- function distill(space, source, turns, summary, artifacts, sessionId) {
21911
+ function sessionLine(session, current) {
21912
+ const detail = [session.source, session.updatedAt && `updated ${session.updatedAt}`].filter(Boolean).join(", ");
21913
+ return `- ${session.id} \u2014 ${session.turns} turns${detail ? ` (${detail})` : ""}${current ? " \u2190 this packet" : ""}`;
21914
+ }
21915
+ function fullHistory(slug, turns, sessionId, sessions) {
21916
+ const total = sessions.reduce((sum, session) => sum + session.turns, 0) || turns;
21917
+ const archive = `spaces/${slug}/sessions/${sessionId}/transcript.jsonl`;
21918
+ const lines = [
21919
+ "## Full history",
21920
+ `This session is archived verbatim \u2014 ${turns} turns including tool calls.`,
21921
+ `Archive: ${archive}`
21922
+ ];
21923
+ if (sessions.length > 1) {
21924
+ lines.push(
21925
+ "",
21926
+ `This space holds ${total} turns across ${sessions.length} sessions. This packet covers one of them, so it is not the whole story.`,
21927
+ ...sessions.map((session) => sessionLine(session, session.id === sessionId))
21928
+ );
21929
+ }
21930
+ lines.push(
21931
+ "",
21932
+ `Search the whole space before deciding something is missing: pantheon_search (space: ${slug}, query: "<topic>") \u2014 it reads tool calls as well as messages.`,
21933
+ `Then pantheon_get_turns (space, session_id, from, to) for a range, or pantheon_get_session for one session end to end.`
21934
+ );
21935
+ return lines;
21936
+ }
21937
+ function distill(input) {
21938
+ const { space, source, turns, summary, artifacts, sessionId, sessions } = input;
21778
21939
  const spoken = turns.filter((turn) => turn.text.trim());
21779
21940
  const last = spoken.slice(-PACKET_TURNS);
21780
21941
  const toolCalls = turns.reduce((total, turn) => total + (turn.toolCalls?.length || 0), 0);
21781
21942
  const span = [turns.find((turn) => turn.ts)?.ts, [...turns].reverse().find((turn) => turn.ts)?.ts].filter(Boolean).join(" \u2192 ");
21782
- const archive = sessionId ? `spaces/${slugify(space)}/sessions/${sessionId}/transcript.jsonl` : `spaces/${slugify(space)}/sessions/`;
21783
21943
  const lines = [
21784
21944
  `# Handoff: ${space}`,
21785
21945
  `Source: ${source || "unknown"} \xB7 ${turns.length} turns \xB7 ${toolCalls} tool calls \xB7 ${nowIso()}`,
@@ -21796,10 +21956,7 @@ function distill(space, source, turns, summary, artifacts, sessionId) {
21796
21956
  (turn) => `- [${turn.id}] ${turn.role}: ${turn.text.replace(/\s+/g, " ").slice(0, PACKET_TURN_CHARS)}`
21797
21957
  ),
21798
21958
  "",
21799
- "## Full history",
21800
- `The complete conversation is archived verbatim \u2014 ${turns.length} turns including tool calls.`,
21801
- `Archive: ${archive}`,
21802
- sessionId ? `Read it with pantheon_get_session (space: ${slugify(space)}, session_id: ${sessionId}), a range with pantheon_get_turns, or find a moment with pantheon_search.` : "Read it with pantheon_get_session, pantheon_get_turns, or pantheon_search.",
21959
+ ...fullHistory(slugify(space), turns.length, sessionId, sessions),
21803
21960
  ""
21804
21961
  ];
21805
21962
  return `${lines.filter((line) => line !== null).join("\n")}
@@ -21929,7 +22086,11 @@ function resolveTranscript(input) {
21929
22086
  "Transcript is empty and capture is disabled. Send the real turns, or drop capture:false to archive this chat from local history."
21930
22087
  );
21931
22088
  }
21932
- const captured = captureLocalTranscript({ cwd: input.cwd, sessionKey: input.sessionKey });
22089
+ const captured = captureLocalTranscript({
22090
+ cwd: input.cwd,
22091
+ sessionKey: input.sessionKey,
22092
+ hint: input.space
22093
+ });
21933
22094
  if (!captured?.turns.length) {
21934
22095
  throw new Error(
21935
22096
  "No local conversation history found for this workspace. Pass cwd for the project folder, or send the transcript explicitly with every user and assistant turn verbatim."
@@ -21937,6 +22098,10 @@ function resolveTranscript(input) {
21937
22098
  }
21938
22099
  return { turns: captured.turns, captured };
21939
22100
  }
22101
+ function lastSpoken(turns) {
22102
+ const last = [...turns].reverse().find((turn) => turn.role === "user" && turn.text.trim());
22103
+ return last ? last.text.replace(/\s+/g, " ").trim().slice(0, 160) : null;
22104
+ }
21940
22105
  function writeHandoff(home, input) {
21941
22106
  requireSpaceName(input.space);
21942
22107
  const { slug, root } = ensureSpace(home, input.space);
@@ -21945,10 +22110,13 @@ function writeHandoff(home, input) {
21945
22110
  const thin = transcriptLooksThin(turns);
21946
22111
  if (thin) throw new Error(thin);
21947
22112
  }
22113
+ const cwd = input.cwd || process.cwd();
21948
22114
  const artifacts = mergeArtifacts(
21949
22115
  input.artifacts,
21950
22116
  extractFencedArtifacts(turns),
21951
- collectDiskArtifacts(turns)
22117
+ collectDiskArtifacts(turns),
22118
+ captured ? collectWrittenArtifacts(turns, cwd) : void 0,
22119
+ captured ? collectAttachedArtifacts(turns, cwd) : void 0
21952
22120
  );
21953
22121
  if (!captured) {
21954
22122
  const missing = missingGeneratedFiles(turns, artifacts);
@@ -21957,14 +22125,15 @@ function writeHandoff(home, input) {
21957
22125
  const source = input.source || captured?.session.source;
21958
22126
  const sessionId = captured ? captured.session.key : input.append ? latestSessionId(root) || void 0 : void 0;
21959
22127
  const session = writeSession(root, source, turns, artifacts, sessionId);
21960
- const packet = distill(
21961
- input.space,
22128
+ const packet = distill({
22129
+ space: input.space,
21962
22130
  source,
21963
- session.turns,
21964
- input.summary,
21965
- session.artifacts,
21966
- session.sessionId
21967
- );
22131
+ turns: session.turns,
22132
+ summary: input.summary,
22133
+ artifacts: session.artifacts,
22134
+ sessionId: session.sessionId,
22135
+ sessions: sessionSummaries(root)
22136
+ });
21968
22137
  writeFileSync(join2(root, "handoff.md"), packet);
21969
22138
  writeFileSync(join2(root, "handoffs", `${stamp()}.md`), packet);
21970
22139
  if (input.facts?.length) {
@@ -21979,6 +22148,8 @@ function writeHandoff(home, input) {
21979
22148
  added: session.added,
21980
22149
  alreadyArchived: session.existing,
21981
22150
  capturedFrom: captured ? captured.session.source : null,
22151
+ // So a human can tell at a glance that the right conversation was read.
22152
+ lastMessage: lastSpoken(session.turns),
21982
22153
  artifacts: session.artifacts,
21983
22154
  truncated: Boolean(input.truncated),
21984
22155
  append: Boolean(input.append)
@@ -22028,6 +22199,53 @@ function sessionDirs(root) {
22028
22199
  };
22029
22200
  }).sort((a, b) => b.mtime - a.mtime);
22030
22201
  }
22202
+ function metaField(raw, key) {
22203
+ return raw.match(new RegExp(`^${key}:\\s*(.+)$`, "m"))?.[1]?.trim() || void 0;
22204
+ }
22205
+ function countLines(path) {
22206
+ const raw = readText(path);
22207
+ return raw.trim() ? raw.split("\n").filter((line) => line.trim()).length : 0;
22208
+ }
22209
+ function sessionSummaries(root) {
22210
+ return sessionDirs(root).map((session) => {
22211
+ const meta = readText(join2(session.dir, "meta.yaml"));
22212
+ const source = metaField(meta, "source");
22213
+ return {
22214
+ id: session.id,
22215
+ source: source && source !== "unknown" ? source : void 0,
22216
+ // meta.yaml is rewritten on every handoff, but a half-written or
22217
+ // hand-edited archive should still report an honest count.
22218
+ turns: Number(metaField(meta, "turns")) || countLines(join2(session.dir, "transcript.jsonl")),
22219
+ createdAt: metaField(meta, "created_at"),
22220
+ updatedAt: metaField(meta, "updated_at")
22221
+ };
22222
+ });
22223
+ }
22224
+ var STORY_PACKETS = 8;
22225
+ var STORY_CHARS = 6e3;
22226
+ function packetBody(markdown) {
22227
+ const after = markdown.split("## Packet")[1];
22228
+ return after ? after.split(/\n## /)[0].trim() : "";
22229
+ }
22230
+ function unstamp(name) {
22231
+ return name.replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/, "T$1:$2:$3.$4Z");
22232
+ }
22233
+ function readStory(root) {
22234
+ const dir = join2(root, "handoffs");
22235
+ if (!existsSync2(dir)) return [];
22236
+ const files2 = readdirSync2(dir).filter((name) => name.endsWith(".md")).sort();
22237
+ const prior = files2.slice(0, -1).slice(-STORY_PACKETS);
22238
+ const out = [];
22239
+ let budget = STORY_CHARS;
22240
+ for (const name of [...prior].reverse()) {
22241
+ if (budget <= 0) break;
22242
+ const packet = packetBody(readText(join2(dir, name)));
22243
+ if (!packet) continue;
22244
+ out.push({ at: unstamp(name.replace(/\.md$/, "")), packet: packet.slice(0, budget) });
22245
+ budget -= packet.length;
22246
+ }
22247
+ return out.reverse();
22248
+ }
22031
22249
  function listSpaceArtifacts(root) {
22032
22250
  const out = [];
22033
22251
  for (const session of sessionDirs(root)) {
@@ -22041,16 +22259,42 @@ function listSpaceArtifacts(root) {
22041
22259
  }
22042
22260
  return out;
22043
22261
  }
22262
+ function resumeNote(sessions, turns, story) {
22263
+ if (!sessions.length) {
22264
+ return "Nothing archived in this space yet. Ask the human what they were working on rather than guessing.";
22265
+ }
22266
+ const parts = [
22267
+ `handoff.md is a packet, not the conversation: this space holds ${turns} turns across ${sessions.length} session${sessions.length === 1 ? "" : "s"}, all archived verbatim with tool calls.`
22268
+ ];
22269
+ if (sessions.length > 1) {
22270
+ parts.push(
22271
+ "The packet was written by whichever session ended last, so it does not describe the others. Every id in sessions works with pantheon_get_session and pantheon_get_turns."
22272
+ );
22273
+ }
22274
+ if (story) {
22275
+ parts.push(`story holds ${story} earlier packet${story === 1 ? "" : "s"}, oldest first.`);
22276
+ }
22277
+ parts.push(
22278
+ 'Before telling the human you lack context, run pantheon_search (query: "<topic>", context: 2) \u2014 it searches tool calls as well as messages, across every session.'
22279
+ );
22280
+ return parts.join(" ");
22281
+ }
22044
22282
  function readResume(home, space) {
22045
22283
  requireSpaceName(space);
22046
22284
  const { slug, root } = ensureSpace(home, space);
22047
- const artifacts = listSpaceArtifacts(root);
22285
+ const sessions = sessionSummaries(root);
22286
+ const turns = sessions.reduce((sum, session) => sum + session.turns, 0);
22287
+ const story = readStory(root);
22048
22288
  return {
22049
22289
  space: slug,
22050
22290
  handoff: readText(join2(root, "handoff.md")).trim() || "(empty handoff)",
22051
22291
  memory: readText(join2(root, "memory.md")).trim() || "(no durable memory yet)",
22052
- sessionId: sessionDirs(root)[0]?.id ?? null,
22053
- artifacts
22292
+ sessionId: sessions[0]?.id ?? null,
22293
+ sessions,
22294
+ turns,
22295
+ story,
22296
+ artifacts: listSpaceArtifacts(root),
22297
+ note: resumeNote(sessions, turns, story.length)
22054
22298
  };
22055
22299
  }
22056
22300
  function packetPreview(markdown) {
@@ -22076,27 +22320,70 @@ function listSpaces(home) {
22076
22320
  };
22077
22321
  }).sort((a, b) => (b.updatedAt || "").localeCompare(a.updatedAt || ""));
22078
22322
  }
22079
- function searchSpace(home, space, query) {
22323
+ var SEARCH_LIMIT = 20;
22324
+ var SEARCH_MAX = 50;
22325
+ var CONTEXT_MAX = 5;
22326
+ var EXCERPT_CHARS = 280;
22327
+ var CONTEXT_CHARS = 400;
22328
+ function excerptAround(haystack, needle, width = EXCERPT_CHARS) {
22329
+ const flat = haystack.replace(/\s+/g, " ").trim();
22330
+ const at = flat.toLowerCase().indexOf(needle);
22331
+ if (at < 0) return flat.slice(0, width);
22332
+ const start = Math.max(0, at - Math.floor(width / 3));
22333
+ const end = Math.min(flat.length, start + width);
22334
+ return `${start > 0 ? "\u2026" : ""}${flat.slice(start, end)}${end < flat.length ? "\u2026" : ""}`;
22335
+ }
22336
+ function toolHaystack(call) {
22337
+ const input = typeof call.input === "string" ? call.input : JSON.stringify(call.input ?? "");
22338
+ return [call.name, input, call.output ?? ""].filter(Boolean).join(" ");
22339
+ }
22340
+ function slimTurn(turn) {
22341
+ return {
22342
+ id: turn.id,
22343
+ role: turn.role,
22344
+ text: (turn.text || "").replace(/\s+/g, " ").slice(0, CONTEXT_CHARS),
22345
+ ts: turn.ts,
22346
+ toolCalls: turn.toolCalls?.map((call) => ({ name: call.name }))
22347
+ };
22348
+ }
22349
+ function matchTurn(turn, needle) {
22350
+ if (turn.text?.toLowerCase().includes(needle)) {
22351
+ return { matchedIn: "text", excerpt: excerptAround(turn.text, needle) };
22352
+ }
22353
+ for (const call of turn.toolCalls ?? []) {
22354
+ const haystack = toolHaystack(call);
22355
+ if (!haystack.toLowerCase().includes(needle)) continue;
22356
+ return {
22357
+ matchedIn: "tool",
22358
+ tool: call.name,
22359
+ excerpt: excerptAround(haystack, needle)
22360
+ };
22361
+ }
22362
+ return null;
22363
+ }
22364
+ function searchSpace(home, space, query, options = {}) {
22080
22365
  const { root } = ensureSpace(home, space);
22081
- const sessions = join2(root, "sessions");
22082
- if (!existsSync2(sessions)) return [];
22083
- const needle = query.toLowerCase();
22366
+ const needle = query.trim().toLowerCase();
22367
+ if (!needle) return [];
22368
+ const limit = Math.min(Math.max(options.limit ?? SEARCH_LIMIT, 1), SEARCH_MAX);
22369
+ const context = Math.min(Math.max(options.context ?? 0, 0), CONTEXT_MAX);
22084
22370
  const hits = [];
22085
- for (const session of readdirSync2(sessions, { withFileTypes: true })) {
22086
- if (!session.isDirectory()) continue;
22087
- const file = join2(sessions, session.name, "transcript.jsonl");
22088
- if (!existsSync2(file)) continue;
22089
- for (const line of readFileSync2(file, "utf8").split("\n")) {
22090
- if (!line.trim()) continue;
22091
- const turn = JSON.parse(line);
22092
- if (!turn.text?.toLowerCase().includes(needle)) continue;
22371
+ for (const session of sessionDirs(root)) {
22372
+ const turns = readSessionTurns(session.dir);
22373
+ for (let index = 0; index < turns.length; index += 1) {
22374
+ const turn = turns[index];
22375
+ const match = matchTurn(turn, needle);
22376
+ if (!match) continue;
22093
22377
  hits.push({
22094
- sessionId: session.name,
22378
+ sessionId: session.id,
22095
22379
  turnId: turn.id,
22096
22380
  role: turn.role,
22097
- excerpt: turn.text.replace(/\s+/g, " ").slice(0, 280)
22381
+ ...match,
22382
+ ...context ? {
22383
+ context: turns.slice(Math.max(0, index - context), index + context + 1).map(slimTurn)
22384
+ } : {}
22098
22385
  });
22099
- if (hits.length >= 20) return hits;
22386
+ if (hits.length >= limit) return hits;
22100
22387
  }
22101
22388
  }
22102
22389
  return hits;
@@ -22139,6 +22426,7 @@ Grounding \u2014 never break these:
22139
22426
  - If pantheon_* tools are missing or fail, say "Pantheon MCP is not connected" and stop. Do not guess.
22140
22427
  - /pantheon-spaces \u2192 call pantheon_list_spaces, then show only those slugs.
22141
22428
  - Files you generated (PDFs, letters, CVs, spreadsheets) must go in artifacts as base64. Handoff is rejected if the chat names a .pdf and you omit it.
22429
+ - After resume, the packet is a summary of the session that ended last \u2014 not the space. Before you tell the human something was not carried over, call pantheon_search (it reads tool calls too) and pantheon_get_turns on any id from the sessions list.
22142
22430
  `;
22143
22431
  var GUIDE = `pantheon \u2014 agent conscience
22144
22432
 
@@ -22170,6 +22458,13 @@ Tutorial
22170
22458
  4. Continue later: /pantheon-resume <space> \u2192 pantheon_resume
22171
22459
  If they omit <space>, still call pantheon_resume. It lists the vault so they can pick.
22172
22460
  Handoff commits and pushes. Resume pulls first. Do not run pantheon sync.
22461
+ 5. Dig past the packet. Resume returns a summary of the last session plus
22462
+ sessions (every archived conversation and its turn count) and story
22463
+ (what earlier handoffs said). The detail is all still there:
22464
+ pantheon_search find a moment anywhere in the space, tool calls included
22465
+ pantheon_get_turns read around it
22466
+ pantheon_get_session read one conversation end to end
22467
+ Missing context is nearly always unsearched, not unsaved.
22173
22468
 
22174
22469
  Terminal (this CLI)
22175
22470
  connect <code> bind this machine to the private GitHub vault
@@ -22185,12 +22480,13 @@ Terminal (this CLI)
22185
22480
  MCP tools \u2014 always the pantheon_ prefix
22186
22481
  pantheon_help this same guide
22187
22482
  pantheon_list_spaces list consciences
22188
- pantheon_resume pull vault, then load latest handoff.md + memory.md
22483
+ pantheon_resume pull vault, then load the packet, memory, story,
22484
+ session list, and artifact names
22189
22485
  pantheon_handoff archive this chat from local history, commit and push
22190
22486
  pantheon_local_sessions list recorded chats capture can see (Cursor/Codex/Claude)
22191
22487
  pantheon_park archive without rewriting the packet, then push
22192
22488
  pantheon_remember add one durable fact, then push
22193
- pantheon_search search the full dump
22489
+ pantheon_search search every session \u2014 messages and tool calls
22194
22490
  pantheon_get_turns fetch a turn range
22195
22491
  pantheon_get_session fetch a stored transcript
22196
22492
  pantheon_get_artifact fetch a stored file
@@ -22527,7 +22823,7 @@ ${GUIDE}` }]
22527
22823
  registerTool(
22528
22824
  server,
22529
22825
  "pantheon_resume",
22530
- "Pull the vault, then load the latest Pantheon handoff packet, durable memory, and stored artifact names. Trigger: /pantheon-resume <space>. If the space name is missing or empty, this tool lists live spaces \u2014 show that list and ask which conscience. If artifacts are listed, fetch needed files with pantheon_get_artifact. Never call a generic resume tool for this. Do not run pantheon sync.",
22826
+ "Pull the vault, then load a Pantheon conscience: the latest handoff packet, durable memory, packets from earlier handoffs (story), every archived session with its turn count (sessions), and stored artifact names. Trigger: /pantheon-resume <space>. If the space name is missing or empty, this tool lists live spaces \u2014 show that list and ask which conscience. The packet is a summary of the session that ended last, not the space: when the human asks about anything it does not cover, call pantheon_search before saying you lack context, and read detail with pantheon_get_turns or pantheon_get_session using any id from sessions. Fetch files with pantheon_get_artifact. Never call a generic resume tool for this. Do not run pantheon sync.",
22531
22827
  { space: external_exports.string().optional() },
22532
22828
  async ({ space }) => safe(async () => {
22533
22829
  const sync2 = await vault.pull(home);
@@ -22588,7 +22884,12 @@ ${GUIDE}` }]
22588
22884
  ok: sync2.ok !== false,
22589
22885
  ...written,
22590
22886
  sync: sync2,
22591
- note: sync2.ok === false ? `Saved locally (${written.turns} turns) but the push failed: ${sync2.error || "unknown error"}. Tell the human it is not yet in GitHub.` : `Archived ${written.turns} turns${written.added !== written.turns ? ` (${written.added} new)` : ""} from ${written.capturedFrom || "the supplied transcript"}.`
22887
+ note: sync2.ok === false ? `Saved locally (${written.turns} turns) but the push failed: ${sync2.error || "unknown error"}. Tell the human it is not yet in GitHub.` : [
22888
+ `Archived ${written.turns} turns${written.added !== written.turns ? ` (${written.added} new)` : ""} from ${written.capturedFrom || "the supplied transcript"}.`,
22889
+ // Capture reads a chat off disk, so name what it read: if a
22890
+ // second conversation was open, this is where that shows.
22891
+ written.lastMessage ? `Last human message in the captured chat: "${written.lastMessage}" \u2014 if that is not this conversation, re-run with sessionKey from pantheon_local_sessions.` : null
22892
+ ].filter(Boolean).join(" ")
22592
22893
  };
22593
22894
  })
22594
22895
  );
@@ -22646,9 +22947,20 @@ ${GUIDE}` }]
22646
22947
  registerTool(
22647
22948
  server,
22648
22949
  "pantheon_search",
22649
- "Search the full Pantheon dump for a space. Returns session and turn pointers.",
22650
- { space: external_exports.string(), query: external_exports.string() },
22651
- async ({ space, query }) => safe(() => ({ hits: searchSpace(home, space, query) }))
22950
+ "Search every archived session in a Pantheon space \u2014 messages and tool calls, including file paths only ever named by a write tool. Use this before telling the human you lack context: the resume packet summarises one session, this reads the whole space. Returns session_id and turn_id pointers to widen with pantheon_get_turns.",
22951
+ {
22952
+ space: external_exports.string(),
22953
+ query: external_exports.string(),
22954
+ context: external_exports.number().optional().describe("Turns of surrounding conversation to return with each hit (0-5). Use 2 to read a moment without a second call."),
22955
+ limit: external_exports.number().optional().describe("Maximum hits (default 20, max 50).")
22956
+ },
22957
+ async ({ space, query, context, limit }) => safe(() => {
22958
+ const hits = searchSpace(home, space, query, { context, limit });
22959
+ return {
22960
+ hits,
22961
+ note: hits.length ? "Each hit names its session. Widen with pantheon_get_turns (space, session_id, from, to) or read the session end to end with pantheon_get_session." : "No match. Try a different word, or list what exists with pantheon_resume \u2014 its sessions array names every archived conversation in this space."
22962
+ };
22963
+ })
22652
22964
  );
22653
22965
  registerTool(
22654
22966
  server,
@@ -22723,7 +23035,7 @@ import { hostname as hostname2 } from "node:os";
22723
23035
 
22724
23036
  // src/connect.ts
22725
23037
  import { execFileSync as execFileSync2 } from "node:child_process";
22726
- import { existsSync as existsSync6, mkdirSync as mkdirSync5 } from "node:fs";
23038
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, renameSync } from "node:fs";
22727
23039
  import { join as join6 } from "node:path";
22728
23040
 
22729
23041
  // src/mcp-install.ts
@@ -23109,15 +23421,12 @@ async function connect(opts) {
23109
23421
  const helper = credentialHelperCommand();
23110
23422
  const quiet = { stdio: ["ignore", "pipe", "pipe"] };
23111
23423
  const fresh = !existsSync6(join6(home, ".git"));
23424
+ let archived = "";
23112
23425
  if (fresh) {
23113
23426
  process.stdout.write(" Cloning the vault\u2026\n");
23114
23427
  execFileSync2("git", ["-c", `credential.helper=${helper}`, "clone", body.cloneUrl, home], quiet);
23115
23428
  } else {
23116
- execFileSync2(
23117
- "git",
23118
- ["-c", `credential.helper=${helper}`, "-C", home, "pull", "--ff-only"],
23119
- quiet
23120
- );
23429
+ archived = syncVault2(home, body.cloneUrl, helper, quiet);
23121
23430
  }
23122
23431
  execFileSync2("git", ["-C", home, "config", "credential.helper", helper], quiet);
23123
23432
  execFileSync2("git", ["-C", home, "config", "user.name", "Pantheon"], quiet);
@@ -23138,7 +23447,8 @@ async function connect(opts) {
23138
23447
  field("Connected", body.account),
23139
23448
  field("Install", String(body.installationId)),
23140
23449
  field("Repo", `${body.repo} (private)`),
23141
- field("Vault", `${home}${fresh ? " (cloned)" : " (updated)"}`)
23450
+ field("Vault", `${home}${vaultNote(fresh, archived)}`),
23451
+ ...archived ? [field("Set aside", `${archived} \u2014 spaces from the old repo`)] : []
23142
23452
  ].join("\n"),
23143
23453
  failure ? field("MCP", `failed \u2014 ${failure}`) : block("Configured", written),
23144
23454
  block("Skipped", skipped),
@@ -23146,6 +23456,44 @@ async function connect(opts) {
23146
23456
  )
23147
23457
  );
23148
23458
  }
23459
+ function syncVault2(home, cloneUrl, helper, quiet) {
23460
+ const git2 = (...args) => execFileSync2("git", ["-c", `credential.helper=${helper}`, "-C", home, ...args], quiet);
23461
+ try {
23462
+ git2("pull", "--ff-only");
23463
+ return "";
23464
+ } catch (error2) {
23465
+ if (!existsSync6(join6(home, ".git"))) throw error2;
23466
+ }
23467
+ if (sharesHistory(home)) {
23468
+ process.stdout.write(" Merging work from another machine\u2026\n");
23469
+ git2("pull", "--no-rebase", "--no-edit");
23470
+ return "";
23471
+ }
23472
+ const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
23473
+ const archive = `${home}-${stamp2}`;
23474
+ process.stdout.write(" Vault belongs to a deleted repo; setting it aside\u2026\n");
23475
+ renameSync(home, archive);
23476
+ execFileSync2("git", ["-c", `credential.helper=${helper}`, "clone", cloneUrl, home], quiet);
23477
+ return archive;
23478
+ }
23479
+ function sharesHistory(home) {
23480
+ try {
23481
+ const upstream = execFileSync2("git", ["-C", home, "rev-parse", "@{u}"], {
23482
+ stdio: ["ignore", "pipe", "pipe"],
23483
+ encoding: "utf8"
23484
+ }).trim();
23485
+ execFileSync2("git", ["-C", home, "merge-base", "HEAD", upstream], {
23486
+ stdio: ["ignore", "pipe", "pipe"]
23487
+ });
23488
+ return true;
23489
+ } catch {
23490
+ return false;
23491
+ }
23492
+ }
23493
+ function vaultNote(fresh, archived) {
23494
+ if (archived) return " (re-cloned)";
23495
+ return fresh ? " (cloned)" : " (updated)";
23496
+ }
23149
23497
  function credentialHelperCommand() {
23150
23498
  return "!pantheon git-credential";
23151
23499
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pantheon-cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Carry agent conscience between AI coding agents. Hand off a conversation in one agent, resume it in another.",
5
5
  "license": "MIT",
6
6
  "type": "module",