@hcflabs/pi-session-recall 5.2.9 → 5.4.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 CHANGED
@@ -57,7 +57,11 @@ Start pattern mining with:
57
57
  }
58
58
  ```
59
59
 
60
- Repository scope selects exact and descendant `cwd` values before applying the limit. It excludes the current session file. Use `scope:"all"` across repositories, including when inventory is unavailable.
60
+ Repository scope selects sessions whose stored `cwd` is the scope root or below it, before it applies the limit. It excludes the current session file. The tool compares the real paths of both, so a symlink does not hide a session.
61
+
62
+ Inside a Git repository, the scope root is the Git root. Outside Git, for example in a parent directory that holds many repositories, the scope root is the real path of the current directory. The result then has `scope.gitRoot:null` and `inventory.available:false` with `reason:"not-a-git-repository"`. `scope.root` always names the directory that the tool used. It is `null` for `scope:"all"`.
63
+
64
+ Use `scope:"all"` to sample sessions from every directory.
61
65
 
62
66
  The TUI shows the last five visual lines and earlier-line count. Press the tool expand key (`Ctrl+O` by default) for the full bounded response; the model always receives it.
63
67
 
@@ -135,7 +139,7 @@ Files over 32 MiB are neither indexed nor retrieved. Discovery cannot find new o
135
139
 
136
140
  Preparation runs one sync pass. Backlog or incomplete walks limit the sample and set `sync.complete:false`. Total sync failure is a tool error. Preparation rejects `query`, session cursors, or `window`; `scope` requires the preparation operation.
137
141
 
138
- Repository scope fails outside Git or when inventory fails. All scope returns its corpus with `inventory.available:false` for nonzero Git-root lookup (`reason:"not-a-git-repository"`) or later inventory failure (`reason:"inventory-failed"`).
142
+ Both scopes return their corpus with `inventory.available:false` when the current directory is not in a Git repository (`reason:"not-a-git-repository"`). Repository scope fails when inventory fails inside a Git repository. All scope returns its corpus with `inventory.available:false` and `reason:"inventory-failed"` in that case.
139
143
 
140
144
  | Limit | Maximum |
141
145
  | --- | --- |
@@ -460,7 +460,9 @@ function unavailableInventory(
460
460
  };
461
461
  }
462
462
 
463
- /** Return bounded discovery hints from the Git index and Pi's effective skill registry. */
463
+ /** Return bounded discovery hints from the Git index and Pi's effective skill registry.
464
+ * Outside a Git repository, both modes return the unavailable inventory.
465
+ * After the Git root is known, "required" mode throws on a failure and "optional" mode returns the unavailable inventory. */
464
466
  export async function inventoryRepository(
465
467
  pi: InventoryPi,
466
468
  ctx: InventoryContext,
@@ -469,10 +471,7 @@ export async function inventoryRepository(
469
471
  throwIfAborted(ctx.signal);
470
472
  const gitRoot = await resolveGitRoot(ctx);
471
473
  throwIfAborted(ctx.signal);
472
- if (!gitRoot) {
473
- if (mode === "optional") return unavailableInventory(REPOSITORY_UNAVAILABLE_REASON);
474
- throw new Error("Repository inventory requires a Git repository.");
475
- }
474
+ if (!gitRoot) return unavailableInventory(REPOSITORY_UNAVAILABLE_REASON);
476
475
 
477
476
  try {
478
477
  const index = parseIndex((await runGit(gitRoot, ["--no-replace-objects", "ls-files", "--stage", "-z"], ctx.signal, INDEX_STDOUT_BYTES)).stdout);
@@ -853,11 +853,51 @@ export function searchIndex(
853
853
 
854
854
  export interface PreparationRowOptions {
855
855
  limit: number;
856
- /** Canonical repository root. Omit to sample all indexed sessions. */
856
+ /** Repository root, or any directory. A session matches when its stored
857
+ * cwd is this directory or below it. Both sides are compared after symlink
858
+ * resolution. Omit to sample all indexed sessions. */
857
859
  repositoryRoot?: string;
858
860
  currentSessionPath?: string;
859
861
  }
860
862
 
863
+ /** Resolve symlinks in the deepest existing ancestor of an absolute path and
864
+ * keep the rest as written. A stored cwd can name a directory that no longer
865
+ * exists. Return `undefined` for a relative path. */
866
+ function canonicalizePath(value: string): string | undefined {
867
+ if (!path.isAbsolute(value)) return undefined;
868
+ let existing = path.resolve(value);
869
+ const rest: string[] = [];
870
+ for (;;) {
871
+ try {
872
+ return path.join(fs.realpathSync(existing), ...rest);
873
+ } catch {
874
+ const parent = path.dirname(existing);
875
+ if (parent === existing) return undefined;
876
+ rest.unshift(path.basename(existing));
877
+ existing = parent;
878
+ }
879
+ }
880
+ }
881
+
882
+ function isSameOrBelow(candidate: string, root: string): boolean {
883
+ const prefix = root.endsWith(path.sep) ? root : root + path.sep;
884
+ return candidate === root || candidate.startsWith(prefix);
885
+ }
886
+
887
+ /** List the stored session cwds that are the root or below it. SQL cannot
888
+ * resolve symlinks, so this check runs on each distinct cwd. */
889
+ function cwdsInScope(db: DatabaseSync, root: string): string[] {
890
+ const canonicalRoot = canonicalizePath(root);
891
+ const stored = db.prepare("SELECT DISTINCT cwd FROM sessions WHERE cwd IS NOT NULL").all() as { cwd: string }[];
892
+ return stored
893
+ .map((row) => row.cwd)
894
+ .filter((cwd) => {
895
+ if (isSameOrBelow(cwd, root)) return true;
896
+ const canonicalCwd = canonicalRoot === undefined ? undefined : canonicalizePath(cwd);
897
+ return canonicalCwd !== undefined && isSameOrBelow(canonicalCwd, canonicalRoot!);
898
+ });
899
+ }
900
+
861
901
  /** Select deterministic, repository-scoped pattern-miner candidates from the
862
902
  * existing index. Scope, current-session exclusion, and one-hop lineage
863
903
  * collapse all happen before the sample limit. */
@@ -865,21 +905,18 @@ export function getPreparationRows(
865
905
  dbPath: string,
866
906
  opts: PreparationRowOptions,
867
907
  ): PreparationSessionRow[] {
868
- const clauses: string[] = [];
869
- const params: string[] = [];
870
- if (opts.repositoryRoot !== undefined) {
871
- const prefix = opts.repositoryRoot.endsWith(path.sep)
872
- ? opts.repositoryRoot
873
- : opts.repositoryRoot + path.sep;
874
- clauses.push("(s.cwd = ? OR substr(s.cwd, 1, length(?)) = ?)");
875
- params.push(opts.repositoryRoot, prefix, prefix);
876
- }
877
- if (opts.currentSessionPath !== undefined) {
878
- clauses.push("s.path <> ?");
879
- params.push(opts.currentSessionPath);
880
- }
881
- const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
882
908
  return withDb(dbPath, (db) => {
909
+ const clauses: string[] = [];
910
+ const params: string[] = [];
911
+ if (opts.repositoryRoot !== undefined) {
912
+ clauses.push("s.cwd IN (SELECT value FROM json_each(?))");
913
+ params.push(JSON.stringify(cwdsInScope(db, opts.repositoryRoot)));
914
+ }
915
+ if (opts.currentSessionPath !== undefined) {
916
+ clauses.push("s.path <> ?");
917
+ params.push(opts.currentSessionPath);
918
+ }
919
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
883
920
  const rows = db.prepare(`
884
921
  WITH eligible AS (
885
922
  SELECT s.path, s.cwd, s.name, s.started_at, s.preview,
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * pi-session-recall entry point: tool registration and mode dispatch.
3
3
  */
4
- import { getAgentDir, keyHint, truncateToVisualLines } from "@earendil-works/pi-coding-agent";
4
+ import { getAgentDir, truncateToVisualLines } from "@earendil-works/pi-coding-agent";
5
5
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
6
  import { StringEnum } from "@earendil-works/pi-ai";
7
7
  import { extensionConfigDir } from "@hcflabs/pi-config-store";
@@ -194,6 +194,7 @@ function buildPreparationResult(
194
194
  kind: "repository" | "all",
195
195
  requestedLimit: number,
196
196
  gitRoot: string | undefined,
197
+ root: string | undefined,
197
198
  syncResult: ReturnType<typeof syncSessions>,
198
199
  rows: PreparationSessionRow[],
199
200
  repositoryInventory: RepositoryInventory,
@@ -211,7 +212,7 @@ function buildPreparationResult(
211
212
  contentTruncated: boolean,
212
213
  ) => ({
213
214
  mode: "prepare-pattern-miner",
214
- scope: { kind, gitRoot: gitRoot ?? null, requestedLimit, sampledCount: preparedSessions.length },
215
+ scope: { kind, gitRoot: gitRoot ?? null, root: root ?? null, requestedLimit, sampledCount: preparedSessions.length },
215
216
  sync,
216
217
  sessions: preparedSessions,
217
218
  inventory,
@@ -302,6 +303,7 @@ const OUTPUT_SCHEMA = Type.Union([
302
303
  scope: Type.Object({
303
304
  kind: StringEnum(["repository", "all"] as const),
304
305
  gitRoot: Nullable(Type.String()),
306
+ root: Nullable(Type.String()),
305
307
  requestedLimit: Type.Number(),
306
308
  sampledCount: Type.Number(),
307
309
  }),
@@ -351,6 +353,7 @@ const OUTPUT_SCHEMA = Type.Union([
351
353
  const DESCRIPTION = `Search past Pi sessions locally with FTS5; returns indexed metadata and snippets.
352
354
 
353
355
  - \`operation: "prepare-pattern-miner"\` + \`scope\`: prepare one bounded corpus and repository inventory.
356
+ \`repository\` samples sessions in the Git root. Outside Git, it samples sessions in the current directory and below, and the inventory is unavailable. \`scope.root\` names the directory used. \`all\` samples every session.
354
357
  - \`query\`: discover matches. Prefer distinctive identifiers or uncommon terms; multi-word queries are AND. Use \`OR\`/\`NOT\` for Boolean queries and quotes only when exact wording is known.
355
358
  - \`sessionId\` + \`aroundMessageId\`: scroll ±\`window\`; retain \`branchTip\` across forks.
356
359
  - \`sessionId\` alone: read; no args: browse recent sessions.
@@ -395,7 +398,7 @@ export default function (pi: ExtensionAPI): void {
395
398
  }, { additionalProperties: false }),
396
399
  outputSchema: OUTPUT_SCHEMA,
397
400
  annotations: { readOnlyHint: true, openWorldHint: false },
398
- renderResult(result, { expanded }, theme) {
401
+ renderResult(result, { expanded }, theme, context) {
399
402
  const output = result.content.find((part) => part.type === "text")?.text ?? "";
400
403
  const styledOutput = theme.fg("toolOutput", output);
401
404
  if (expanded) return new Text(`\n${styledOutput}`, 0, 0);
@@ -410,7 +413,7 @@ export default function (pi: ExtensionAPI): void {
410
413
  cachedLines = ["", ...preview.visualLines];
411
414
  } else {
412
415
  const hint = theme.fg("muted", `... (${preview.skippedCount} earlier lines,`) +
413
- ` ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
416
+ ` ${context.keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
414
417
  cachedLines = ["", truncateToWidth(hint, width, "..."), ...preview.visualLines];
415
418
  }
416
419
  cachedWidth = width;
@@ -443,14 +446,16 @@ export default function (pi: ExtensionAPI): void {
443
446
  { cwd: ctx.cwd, signal },
444
447
  params.scope === "repository" ? "required" : "optional",
445
448
  );
449
+ // Repository scope uses the Git root. Outside Git it uses the real path of cwd.
450
+ const root = params.scope === "repository" ? inventory.gitRoot ?? realpathSync(ctx.cwd) : undefined;
446
451
  const sync = syncSessions(sessionsDir(), dbPath());
447
452
  const currentSessionPath = ctx.sessionManager.getSessionFile() ?? undefined;
448
453
  const rows = getPreparationRows(dbPath(), {
449
454
  limit,
450
- ...(params.scope === "repository" ? { repositoryRoot: inventory.gitRoot! } : {}),
455
+ ...(root === undefined ? {} : { repositoryRoot: root }),
451
456
  currentSessionPath,
452
457
  });
453
- return textResult(buildPreparationResult(params.scope, limit, inventory.gitRoot, sync, rows, inventory));
458
+ return textResult(buildPreparationResult(params.scope, limit, inventory.gitRoot, root, sync, rows, inventory));
454
459
  }
455
460
 
456
461
  let sessionId = params.sessionId?.trim() || undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hcflabs/pi-session-recall",
3
- "version": "5.2.9",
3
+ "version": "5.4.0",
4
4
  "description": "Local FTS5 search over past Pi sessions plus a skill for turning recurring work into deterministic automation.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -27,9 +27,9 @@
27
27
  "pack:check": "npm pack --dry-run"
28
28
  },
29
29
  "peerDependencies": {
30
- "@earendil-works/pi-ai": "^1.3.0",
31
- "@earendil-works/pi-coding-agent": "^1.3.0",
32
- "@earendil-works/pi-tui": "^1.3.0",
30
+ "@earendil-works/pi-ai": "^1.6.0",
31
+ "@earendil-works/pi-coding-agent": "^1.6.0",
32
+ "@earendil-works/pi-tui": "^1.6.0",
33
33
  "typebox": "^1.3.15"
34
34
  },
35
35
  "repository": {
@@ -55,8 +55,8 @@
55
55
  "@hcflabs/pi-config-store": "^4.0.0"
56
56
  },
57
57
  "devDependencies": {
58
- "@earendil-works/pi-ai": "1.3.0",
59
- "@earendil-works/pi-coding-agent": "1.3.0",
60
- "@earendil-works/pi-tui": "1.3.0"
58
+ "@earendil-works/pi-ai": "1.6.0",
59
+ "@earendil-works/pi-coding-agent": "1.6.0",
60
+ "@earendil-works/pi-tui": "1.6.0"
61
61
  }
62
62
  }