pi-goosedump 0.12.14 → 0.12.16

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 (3) hide show
  1. package/README.md +13 -7
  2. package/dist/index.ts +441 -194
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -23,8 +23,8 @@ report that they are unavailable.
23
23
  2. **Recall:** lexical and entity matches come first. Cosine-similar BGE vectors
24
24
  fill the remaining slots. There is no separate vector database.
25
25
 
26
- The extension queues remembering after its own successful compactions. Learning
27
- runs in the background and does not delay compaction.
26
+ Explicit `goose_remember` requests and learning after successful compactions are
27
+ queued in the background, so model extraction and embedding do not block Pi.
28
28
 
29
29
  ## Tools
30
30
 
@@ -32,8 +32,8 @@ runs in the background and does not delay compaction.
32
32
  entry IDs.
33
33
  - **`goose_get`** expands entry IDs returned by `goose_search` or `goose_grep`.
34
34
  - **`goose_grep`** filters session messages with a glob pattern.
35
- - **`goose_remember`** learns durable memory from a session. It defaults to the
36
- current Pi session.
35
+ - **`goose_remember`** queues durable memory learning from a session. It defaults
36
+ to the current Pi session and returns before extraction and embedding finish.
37
37
  - **`goose_recall`** recalls typed memories with source provenance. It searches
38
38
  active memories in the current project by default; `history` includes
39
39
  superseded statements and `allProjects` searches every project.
@@ -97,9 +97,13 @@ compaction. Each completed model response counts as one turn, including response
97
97
  that call tools. The countdown is restored when a session resumes and appears in
98
98
  the footer with a status dot (green when >25% turns remain, yellow when ≤25%, red
99
99
  when ≤12.5%) followed by a hexadecimal countdown. `● GD:0A` means ten turns
100
- remain, `● GD:00` is ready to compact, and `● GD:--` is disabled. If zero is
101
- reached during a tool loop, the extension waits for the agent run to settle and
102
- then compacts. A failed compaction leaves the counter armed at zero.
100
+ remain, `● GD:00` is ready to compact, and `● GD:--` is disabled. The footer
101
+ adds `queued` while compaction is waiting for the active agent run to settle and
102
+ `compacting` while the summary is being built. Pi remains the sole scheduler for
103
+ its normal context threshold. Whichever limit is reached first compacts once,
104
+ and every successful compaction resets the countdown. A failed or cancelled
105
+ compaction leaves the counter armed at zero and is not retried in the same
106
+ settlement.
103
107
 
104
108
  `summaryMaxTokens` is an integer from 512 to 65536 (default 4096). The effective
105
109
  summary budget is the lower of this value and 80% of Pi's `compaction.reserveTokens`,
@@ -111,6 +115,8 @@ global setting.
111
115
  The extension uses `goosedump session compact` for manual, scheduled, and automatic
112
116
  compaction. It preserves the previous summary, summarizes only the new range, and
113
117
  passes the effective token budget. `keep:N` leaves the last N user turns verbatim.
118
+ Tool requests are queued until Pi is idle; if Pi reaches its context threshold
119
+ first, the queued request is coalesced into that compaction.
114
120
 
115
121
  After success, memory learning is queued in the background. A learning failure
116
122
  keeps the summary and displays a warning. Custom instructions use Pi's normal
package/dist/index.ts CHANGED
@@ -27,9 +27,7 @@ import { dirname, join } from "node:path";
27
27
  import {
28
28
  Input,
29
29
  Key,
30
- SettingsList,
31
30
  decodeKittyPrintable,
32
- getKeybindings,
33
31
  matchesKey,
34
32
  truncateToWidth,
35
33
  visibleWidth,
@@ -66,9 +64,6 @@ function isTurnsBeforeCompact(value) {
66
64
  function isSummaryMaxTokens(value) {
67
65
  return typeof value === "number" && Number.isSafeInteger(value) && value >= SUMMARY_MAX_TOKENS_MIN && value <= SUMMARY_MAX_TOKENS_MAX;
68
66
  }
69
- function isGoosedumpSettingValue(key, value) {
70
- return key === "turnsBeforeCompact" ? isTurnsBeforeCompact(value) : isSummaryMaxTokens(value);
71
- }
72
67
  function piAgentDir() {
73
68
  return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
74
69
  }
@@ -81,6 +76,10 @@ function projectSettingsPath(cwd) {
81
76
  function isRecord(value) {
82
77
  return typeof value === "object" && value !== null && !Array.isArray(value);
83
78
  }
79
+ function projectSettingsTrusted(ctx) {
80
+ const trustContext = ctx;
81
+ return trustContext.isProjectTrusted?.() ?? true;
82
+ }
84
83
  function readJsonObject(path) {
85
84
  if (!existsSync(path))
86
85
  return {};
@@ -148,15 +147,19 @@ function validateGoosedumpSettings(path) {
148
147
  throw new Error(`${path}: goosedump.summaryMaxTokens must be an integer from ` + `${SUMMARY_MAX_TOKENS_MIN} to ${SUMMARY_MAX_TOKENS_MAX}`);
149
148
  }
150
149
  }
151
- function resolveGoosedumpSettings(cwd) {
150
+ function resolveGoosedumpSettings(cwd, includeProject) {
152
151
  return {
153
152
  ...DEFAULT_GOOSEDUMP_SETTINGS,
154
153
  ...readGoosedumpSettingsFrom(globalSettingsPath()),
155
- ...readGoosedumpSettingsFrom(projectSettingsPath(cwd))
154
+ ...includeProject ? readGoosedumpSettingsFrom(projectSettingsPath(cwd)) : {}
156
155
  };
157
156
  }
158
157
  function notifyInvalidSettings(ctx) {
159
- for (const path of [globalSettingsPath(), projectSettingsPath(ctx.cwd)]) {
158
+ const paths = [
159
+ globalSettingsPath(),
160
+ ...projectSettingsTrusted(ctx) ? [projectSettingsPath(ctx.cwd)] : []
161
+ ];
162
+ for (const path of paths) {
160
163
  try {
161
164
  validateGoosedumpSettings(path);
162
165
  } catch (error) {
@@ -400,8 +403,9 @@ var GOOSEDUMP_UNAVAILABLE_MESSAGE = "goosedump is not available. Install with: n
400
403
  function goosedumpUnavailableResult() {
401
404
  return textResult(GOOSEDUMP_UNAVAILABLE_MESSAGE);
402
405
  }
403
- function compactStartedMessage(keep) {
404
- return keep !== null ? `Compacting with goosedump; keeping the last ${keep} user turn${keep === 1 ? "" : "s"}.` : "Compacting with goosedump up to Pi's token-based cut.";
406
+ function compactStartedMessage(keep, queued = false) {
407
+ const action = queued ? "Compaction queued with goosedump" : "Compacting with goosedump";
408
+ return keep !== null ? `${action}; keeping the last ${keep} user turn${keep === 1 ? "" : "s"}.` : `${action} up to Pi's token-based cut.`;
405
409
  }
406
410
  function runGoosedumpAsync(args, signal, executablePath = resolveNativeGoosedumpBinary()) {
407
411
  return new Promise((resolve, reject) => {
@@ -593,8 +597,9 @@ function isCompletedAssistant(message) {
593
597
  return message.role === "assistant" && message.stopReason !== "error" && message.stopReason !== "aborted";
594
598
  }
595
599
  var SUMMARIZABLE_ENTRY_TYPES = new Set(["message", "custom_message", "branch_summary"]);
596
- function piKeepRecentTokens(cwd) {
597
- for (const path of [projectSettingsPath(cwd), globalSettingsPath()]) {
600
+ function piKeepRecentTokens(cwd, includeProject) {
601
+ const paths = includeProject ? [projectSettingsPath(cwd), globalSettingsPath()] : [globalSettingsPath()];
602
+ for (const path of paths) {
598
603
  const compaction = readJsonObject(path).compaction;
599
604
  if (isRecord(compaction) && typeof compaction.keepRecentTokens === "number") {
600
605
  return compaction.keepRecentTokens;
@@ -602,8 +607,9 @@ function piKeepRecentTokens(cwd) {
602
607
  }
603
608
  return DEFAULT_COMPACTION_SETTINGS.keepRecentTokens;
604
609
  }
605
- function piReserveTokens(cwd) {
606
- for (const path of [projectSettingsPath(cwd), globalSettingsPath()]) {
610
+ function piReserveTokens(cwd, includeProject) {
611
+ const paths = includeProject ? [projectSettingsPath(cwd), globalSettingsPath()] : [globalSettingsPath()];
612
+ for (const path of paths) {
607
613
  const compaction = readJsonObject(path).compaction;
608
614
  if (isRecord(compaction) && typeof compaction.reserveTokens === "number") {
609
615
  return compaction.reserveTokens;
@@ -611,9 +617,9 @@ function piReserveTokens(cwd) {
611
617
  }
612
618
  return DEFAULT_COMPACTION_SETTINGS.reserveTokens;
613
619
  }
614
- function effectiveSummaryMaxTokens(cwd) {
615
- const configured = resolveGoosedumpSettings(cwd).summaryMaxTokens;
616
- const reserveTokens = piReserveTokens(cwd);
620
+ function effectiveSummaryMaxTokens(cwd, includeProject) {
621
+ const configured = resolveGoosedumpSettings(cwd, includeProject).summaryMaxTokens;
622
+ const reserveTokens = piReserveTokens(cwd, includeProject);
617
623
  if (reserveTokens <= 0)
618
624
  return configured;
619
625
  return Math.max(1, Math.min(configured, Math.floor(reserveTokens * 0.8)));
@@ -625,7 +631,7 @@ function hasCompactableHistory(ctx) {
625
631
  if (branch[branch.length - 1].type === "compaction")
626
632
  return false;
627
633
  const boundaryStart = activeHistoryStartIndex(branch);
628
- const cut = findCutPoint(branch, boundaryStart, branch.length, piKeepRecentTokens(ctx.cwd));
634
+ const cut = findCutPoint(branch, boundaryStart, branch.length, piKeepRecentTokens(ctx.cwd, projectSettingsTrusted(ctx)));
629
635
  if (!branch[cut.firstKeptEntryIndex]?.id)
630
636
  return false;
631
637
  const historyEnd = cut.isSplitTurn ? cut.turnStartIndex : cut.firstKeptEntryIndex;
@@ -782,8 +788,7 @@ class NumberInputSubmenu {
782
788
  this.hint = getSettingsListTheme().hint;
783
789
  }
784
790
  handleInput(data) {
785
- const kb = getKeybindings();
786
- if (kb.matches(data, "tui.select.confirm") || data === `
791
+ if (matchesKey(data, Key.enter) || matchesKey(data, Key.return) || data === `
787
792
  `) {
788
793
  const value = this.input.getValue();
789
794
  if (value === "") {
@@ -805,7 +810,7 @@ class NumberInputSubmenu {
805
810
  this.onSubmitValue(parsed);
806
811
  return;
807
812
  }
808
- if (kb.matches(data, "tui.select.cancel")) {
813
+ if (matchesKey(data, Key.escape)) {
809
814
  this.onCancelEdit();
810
815
  return;
811
816
  }
@@ -836,109 +841,190 @@ function makeRow(content, innerW, border) {
836
841
  async function runSettingsEditor(ctx) {
837
842
  const OVERLAY_WIDTH = 84;
838
843
  const location = ctx.cwd;
844
+ const projectTrusted = projectSettingsTrusted(ctx);
845
+ const specs = [
846
+ {
847
+ key: "turnsBeforeCompact",
848
+ description: "LLM turns before compaction; 0 disables.",
849
+ min: TURNS_BEFORE_COMPACT_MIN,
850
+ max: TURNS_BEFORE_COMPACT_MAX
851
+ },
852
+ {
853
+ key: "summaryMaxTokens",
854
+ description: "Maximum estimated tokens in each summary.",
855
+ min: SUMMARY_MAX_TOKENS_MIN,
856
+ max: SUMMARY_MAX_TOKENS_MAX
857
+ }
858
+ ];
859
+ const helpRows = [
860
+ ["Tab", "Next tab"],
861
+ ["Shift+Tab / S", "Switch scope in Settings"],
862
+ ["↑ / ↓", "Select setting"],
863
+ ["Enter", "Edit setting or submit value"],
864
+ ["Esc", "Cancel edit or close"],
865
+ ["Ctrl+C", "Close"],
866
+ ["Empty + Enter", "Use the Global value in Project scope"]
867
+ ];
839
868
  await ctx.ui.custom((tui, theme, _kb, done) => {
840
- let settingsList;
841
- function settingLabel(scope, key) {
842
- const scopeLabel = scope === "global" ? "Global" : "Project";
869
+ let tab = "settings";
870
+ let scope = projectTrusted ? "project" : "global";
871
+ let selectedSetting = 0;
872
+ let editor;
873
+ let globalSettings = { ...DEFAULT_GOOSEDUMP_SETTINGS };
874
+ let projectSettings = {};
875
+ function settingLabel(editScope, key) {
876
+ const scopeLabel = editScope === "global" ? "Global" : "Project";
843
877
  return `${scopeLabel} ${key}`;
844
878
  }
845
- function buildSettingItems() {
846
- const global = readScopedGoosedumpSettings(location, "global");
847
- const projectPath = projectSettingsPath(location);
848
- const projectRaw = readJsonObjectStrict(projectPath).goosedump;
849
- const project = isRecord(projectRaw) ? projectRaw : {};
850
- const specs = [
851
- {
852
- key: "turnsBeforeCompact",
853
- description: "LLM turns before compaction; 0 disables.",
854
- min: TURNS_BEFORE_COMPACT_MIN,
855
- max: TURNS_BEFORE_COMPACT_MAX
856
- },
857
- {
858
- key: "summaryMaxTokens",
859
- description: "Maximum estimated tokens in each summary.",
860
- min: SUMMARY_MAX_TOKENS_MIN,
861
- max: SUMMARY_MAX_TOKENS_MAX
862
- }
863
- ];
864
- return ["global", "project"].flatMap((scope) => specs.map(({ key, description, min, max }) => {
865
- const projectValue = isGoosedumpSettingValue(key, project[key]) ? project[key] : undefined;
866
- return {
867
- id: `${scope}:${key}`,
868
- label: settingLabel(scope, key),
869
- description: scope === "project" ? `${description} Empty inherits Global.` : description,
870
- currentValue: String(scope === "project" ? projectValue ?? "" : global[key]),
871
- submenu: (currentValue, subDone) => new NumberInputSubmenu(settingLabel(scope, key), currentValue === "" ? null : Number(currentValue), (value) => subDone(String(value)), () => subDone(), {
872
- min,
873
- max,
874
- onClear: scope === "project" ? () => subDone("") : undefined,
875
- onInvalid: (message) => ctx.ui.notify(message, "error")
876
- })
877
- };
878
- }));
879
+ function reloadSettings() {
880
+ globalSettings = readScopedGoosedumpSettings(location, "global");
881
+ projectSettings = {};
882
+ if (!projectTrusted)
883
+ return;
884
+ const projectRaw = readJsonObjectStrict(projectSettingsPath(location)).goosedump;
885
+ if (!isRecord(projectRaw))
886
+ return;
887
+ if (isTurnsBeforeCompact(projectRaw.turnsBeforeCompact)) {
888
+ projectSettings.turnsBeforeCompact = projectRaw.turnsBeforeCompact;
889
+ }
890
+ if (isSummaryMaxTokens(projectRaw.summaryMaxTokens)) {
891
+ projectSettings.summaryMaxTokens = projectRaw.summaryMaxTokens;
892
+ }
879
893
  }
880
- function rebuildSettingsList() {
881
- settingsList = new SettingsList(buildSettingItems(), 10, getSettingsListTheme(), (id, newValue) => {
882
- const [scope, key] = id.split(":");
883
- if (scope === "project" && newValue === "") {
884
- try {
885
- clearScopedGoosedumpSetting(location, scope, key);
886
- settingsList.updateValue(id, "");
887
- ctx.ui.notify(`${settingLabel(scope, key)} inherits Global`, "info");
888
- tui.requestRender();
889
- } catch (error) {
890
- const message = error instanceof Error ? error.message : String(error);
891
- ctx.ui.notify(`goosedump settings error: ${message}`, "error");
892
- }
893
- return;
894
- }
895
- const parsed = Number(newValue);
896
- if (!isGoosedumpSettingValue(key, parsed))
897
- return;
894
+ function finishEdit() {
895
+ editor = undefined;
896
+ reloadSettings();
897
+ tui.requestRender();
898
+ }
899
+ function reportSettingsError(error) {
900
+ const message = error instanceof Error ? error.message : String(error);
901
+ ctx.ui.notify(`goosedump settings error: ${message}`, "error");
902
+ }
903
+ function openEditor() {
904
+ const spec = specs[selectedSetting];
905
+ if (!spec)
906
+ return;
907
+ const editScope = scope;
908
+ const currentValue = editScope === "global" ? globalSettings[spec.key] : projectSettings[spec.key] ?? null;
909
+ editor = new NumberInputSubmenu(settingLabel(editScope, spec.key), currentValue, (value) => {
898
910
  try {
899
- writeScopedGoosedumpSetting(location, scope, key, parsed);
900
- settingsList.updateValue(id, newValue);
901
- ctx.ui.notify(`${settingLabel(scope, key)} = ${key === "turnsBeforeCompact" ? formatCompactSetting(parsed) : parsed}`, "info");
902
- tui.requestRender();
911
+ writeScopedGoosedumpSetting(location, editScope, spec.key, value);
912
+ ctx.ui.notify(`${settingLabel(editScope, spec.key)} = ${spec.key === "turnsBeforeCompact" ? formatCompactSetting(value) : value}`, "info");
913
+ finishEdit();
903
914
  } catch (error) {
904
- const message = error instanceof Error ? error.message : String(error);
905
- ctx.ui.notify(`goosedump settings error: ${message}`, "error");
915
+ reportSettingsError(error);
906
916
  }
907
- tui.requestRender();
908
917
  }, () => {
909
- done(undefined);
918
+ editor = undefined;
919
+ tui.requestRender();
920
+ }, {
921
+ min: spec.min,
922
+ max: spec.max,
923
+ onClear: editScope === "project" ? () => {
924
+ try {
925
+ clearScopedGoosedumpSetting(location, editScope, spec.key);
926
+ ctx.ui.notify(`${settingLabel(editScope, spec.key)} inherits Global`, "info");
927
+ finishEdit();
928
+ } catch (error) {
929
+ reportSettingsError(error);
930
+ }
931
+ } : undefined,
932
+ onInvalid: (message) => ctx.ui.notify(message, "error")
910
933
  });
911
934
  }
912
- rebuildSettingsList();
935
+ reloadSettings();
913
936
  return {
914
937
  render(width) {
915
- const innerW = width - 4;
938
+ const innerW = Math.max(1, width - 4);
916
939
  const border = theme.fg("border", "│");
917
- const borderFg = (s) => theme.fg("border", s);
918
- const accent = (s) => theme.fg("accent", s);
919
- const dim = (s) => theme.fg("dim", s);
920
- const lines = [];
940
+ const borderFg = (text2) => theme.fg("border", text2);
941
+ const accent = (text2) => theme.fg("accent", text2);
942
+ const dim = (text2) => theme.fg("dim", text2);
943
+ const text = (value) => theme.fg("text", value);
944
+ const pad = (value, cellWidth) => {
945
+ const clipped = truncateToWidth(value, cellWidth);
946
+ return `${clipped}${" ".repeat(Math.max(0, cellWidth - visibleWidth(clipped)))}`;
947
+ };
948
+ const tabLabel = (label, active) => active ? accent(theme.bold(`[${label}]`)) : theme.fg("muted", label);
949
+ const tabs = `${tabLabel("Settings", tab === "settings")} ${tabLabel("Help", tab === "help")}${dim(` · Scope: ${scope === "project" ? "Project" : "Global"}`)}`;
950
+ const content = [tabs, ""];
951
+ if (editor) {
952
+ content.push(...editor.render(innerW));
953
+ } else if (tab === "help") {
954
+ const shortcutWidth = Math.max(visibleWidth("Shortcut"), ...helpRows.map(([shortcut]) => visibleWidth(shortcut)));
955
+ const descriptionWidth = Math.max(1, innerW - shortcutWidth - 4);
956
+ content.push(dim(` ${pad("Shortcut", shortcutWidth)} Description`), ...helpRows.map(([shortcut, description]) => ` ${accent(pad(shortcut, shortcutWidth))} ${text(truncateToWidth(description, descriptionWidth))}`));
957
+ } else {
958
+ for (const [index, spec] of specs.entries()) {
959
+ const selected = index === selectedSetting;
960
+ const inherited = scope === "project" && projectSettings[spec.key] === undefined;
961
+ const value = scope === "global" ? globalSettings[spec.key] : projectSettings[spec.key] ?? globalSettings[spec.key];
962
+ const valueText = `[ ${value} ]`;
963
+ const renderedValue = inherited ? dim(valueText) : selected ? accent(valueText) : text(valueText);
964
+ const cursor = selected ? accent("›") : " ";
965
+ content.push(`${cursor} ${renderedValue} ${text(spec.key)}`);
966
+ }
967
+ const selectedSpec = specs[selectedSetting];
968
+ if (selectedSpec) {
969
+ const inherited = scope === "project" && projectSettings[selectedSpec.key] === undefined;
970
+ content.push("", dim(inherited ? `${selectedSpec.description} Using the Global value.` : selectedSpec.description));
971
+ }
972
+ const effective = resolveGoosedumpSettings(location, projectTrusted);
973
+ content.push("", dim(`Effective: turns=${formatCompactSetting(effective.turnsBeforeCompact)} · summary=${effectiveSummaryMaxTokens(location, projectTrusted)} tokens`));
974
+ }
921
975
  const title = accent(" Goosedump Settings ");
922
976
  const topFill = borderFg("─".repeat(Math.max(0, width - 4 - visibleWidth(title))));
923
- lines.push(`${borderFg("╭─")}${title}${topFill}${borderFg("─╮")}`);
924
- for (const line of settingsList.render(innerW))
925
- lines.push(makeRow(line, innerW, border));
926
- lines.push(makeRow("", innerW, border));
927
- const effective = resolveGoosedumpSettings(location);
928
- lines.push(makeRow(dim(`Effective: turns=${formatCompactSetting(effective.turnsBeforeCompact)} · summary=${effectiveSummaryMaxTokens(location)} tokens`), innerW, border));
929
- lines.push(makeRow(dim("↑↓ select enter/space edit esc close"), innerW, border));
930
- lines.push(`${borderFg("╰")}${borderFg("─".repeat(width - 2))}${borderFg("╯")}`);
931
- return lines;
977
+ return [
978
+ `${borderFg("╭─")}${title}${topFill}${borderFg("─╮")}`,
979
+ ...content.map((line) => makeRow(line, innerW, border)),
980
+ `${borderFg("╰")}${borderFg("─".repeat(Math.max(0, width - 2)))}${borderFg("╯")}`
981
+ ];
932
982
  },
933
983
  handleInput(data) {
934
- if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
984
+ if (matchesKey(data, Key.ctrl("c"))) {
985
+ done(undefined);
986
+ return;
987
+ }
988
+ if (editor) {
989
+ editor.handleInput(data);
990
+ tui.requestRender();
991
+ return;
992
+ }
993
+ if (matchesKey(data, Key.tab)) {
994
+ tab = tab === "settings" ? "help" : "settings";
995
+ tui.requestRender();
996
+ return;
997
+ }
998
+ if (tab === "settings" && (matchesKey(data, Key.shift(Key.tab)) || data.toLowerCase() === "s")) {
999
+ if (!projectTrusted && scope === "global") {
1000
+ ctx.ui.notify("Project settings require a trusted project", "warning");
1001
+ return;
1002
+ }
1003
+ scope = scope === "project" ? "global" : "project";
1004
+ reloadSettings();
1005
+ tui.requestRender();
1006
+ return;
1007
+ }
1008
+ if (matchesKey(data, Key.escape)) {
935
1009
  done(undefined);
936
1010
  return;
937
1011
  }
938
- settingsList.handleInput(data);
1012
+ if (tab === "help")
1013
+ return;
1014
+ if (matchesKey(data, Key.up)) {
1015
+ selectedSetting = selectedSetting === 0 ? specs.length - 1 : Math.max(0, selectedSetting - 1);
1016
+ } else if (matchesKey(data, Key.down)) {
1017
+ selectedSetting = (selectedSetting + 1) % specs.length;
1018
+ } else if (matchesKey(data, Key.enter) || matchesKey(data, Key.return)) {
1019
+ openEditor();
1020
+ } else {
1021
+ return;
1022
+ }
939
1023
  tui.requestRender();
940
1024
  },
941
- invalidate() {}
1025
+ invalidate() {
1026
+ editor?.invalidate();
1027
+ }
942
1028
  };
943
1029
  }, {
944
1030
  overlay: true,
@@ -1319,9 +1405,13 @@ function createGoosedumpIntegration(options = {}) {
1319
1405
  let compactSettings = DEFAULT_GOOSEDUMP_SETTINGS;
1320
1406
  let turnsRemaining = 0;
1321
1407
  let counterTriggered = false;
1322
- let compactionQueued = false;
1323
- let compactionHookActive = false;
1324
- let pendingKeep = null;
1408
+ let compactionState = { phase: "idle" };
1409
+ let sessionGeneration = 0;
1410
+ let settlementGeneration = 0;
1411
+ let operationGeneration = 0;
1412
+ let activeSessionFile = null;
1413
+ let sessionActive = false;
1414
+ let agentEndObserved = true;
1325
1415
  const rememberQueue = [];
1326
1416
  let rememberRunning = null;
1327
1417
  function enqueueRemember(target, reportError) {
@@ -1357,13 +1447,11 @@ function createGoosedumpIntegration(options = {}) {
1357
1447
  while (rememberRunning)
1358
1448
  await rememberRunning;
1359
1449
  }
1360
- function syncCompactCounters(ctx, clearPending = false) {
1361
- compactSettings = resolveGoosedumpSettings(ctx.cwd);
1450
+ function syncCompactCounters(ctx) {
1451
+ compactSettings = resolveGoosedumpSettings(ctx.cwd, projectSettingsTrusted(ctx));
1362
1452
  const completedTurns = completedTurnsSinceCompaction(ctx.sessionManager.getBranch());
1363
1453
  turnsRemaining = Math.max(0, compactSettings.turnsBeforeCompact - completedTurns);
1364
1454
  counterTriggered = compactSettings.turnsBeforeCompact > 0 && completedTurns >= compactSettings.turnsBeforeCompact;
1365
- if (clearPending)
1366
- pendingKeep = null;
1367
1455
  }
1368
1456
  function updateStatus(ctx) {
1369
1457
  if (!goosedumpAvailable)
@@ -1380,22 +1468,20 @@ function createGoosedumpIntegration(options = {}) {
1380
1468
  }
1381
1469
  const dot = ctx.ui.theme.fg(dotColor, "●");
1382
1470
  const counter = active ? Math.max(0, turnsRemaining).toString(16).toUpperCase().padStart(2, "0") : "--";
1383
- const label = ctx.ui.theme.fg("text", `${ctx.ui.theme.bold?.("GD") ?? "GD"}:${counter}`);
1471
+ const activity = compactionState.phase === "queued" ? " queued" : compactionState.phase === "running" ? " compacting" : "";
1472
+ const label = ctx.ui.theme.fg("text", `${ctx.ui.theme.bold?.("GD") ?? "GD"}:${counter}${activity}`);
1384
1473
  ctx.ui.setStatus("goosedump", `${dot} ${label}`);
1385
1474
  }
1475
+ function setCompactionState(ctx, state) {
1476
+ compactionState = state;
1477
+ updateStatus(ctx);
1478
+ }
1386
1479
  function noteCompletedTurn(ctx) {
1387
1480
  if (!goosedumpAvailable || !shouldOverrideDefaultCompaction)
1388
1481
  return;
1389
1482
  syncCompactCounters(ctx);
1390
1483
  updateStatus(ctx);
1391
- }
1392
- function normalThresholdTriggered(ctx) {
1393
- if (compactSettings.turnsBeforeCompact <= 0)
1394
- return false;
1395
- const usage = ctx.getContextUsage();
1396
- if (!usage || usage.tokens === null || usage.contextWindow <= 0)
1397
- return false;
1398
- return usage.tokens > usage.contextWindow - piReserveTokens(ctx.cwd);
1484
+ queueTurnCompaction(ctx, settlementGeneration + 1);
1399
1485
  }
1400
1486
  function checkGoosedump(ctx) {
1401
1487
  try {
@@ -1408,34 +1494,98 @@ function createGoosedumpIntegration(options = {}) {
1408
1494
  return false;
1409
1495
  }
1410
1496
  }
1411
- function requestCompaction(ctx, keep) {
1412
- if (compactionQueued || compactionHookActive)
1413
- return "busy";
1414
- if (keep === null && !hasCompactableHistory(ctx))
1415
- return "nothing-to-compact";
1416
- compactionQueued = true;
1417
- pendingKeep = keep;
1497
+ function requestIsCurrent(request) {
1498
+ return request.sessionGeneration === sessionGeneration && request.sessionFile === activeSessionFile;
1499
+ }
1500
+ function contextIsCurrent(ctx) {
1501
+ return sessionActive && (ctx.sessionManager.getSessionFile?.() ?? null) === activeSessionFile;
1502
+ }
1503
+ function runningOperationIsCurrent(operation, generation, sessionFile) {
1504
+ return generation === sessionGeneration && sessionFile === activeSessionFile && compactionState.phase === "running" && compactionState.operation === operation;
1505
+ }
1506
+ function requestHasCompactableHistory(ctx, keep) {
1507
+ return keep === null ? hasCompactableHistory(ctx) : keepBoundaryId(ctx.sessionManager.getBranch(), keep) !== undefined;
1508
+ }
1509
+ function queueTurnCompaction(ctx, eligibleSettlement) {
1510
+ if (!counterTriggered || compactionState.phase !== "idle")
1511
+ return;
1512
+ if (!hasCompactableHistory(ctx))
1513
+ return;
1514
+ setCompactionState(ctx, {
1515
+ phase: "queued",
1516
+ request: {
1517
+ keep: null,
1518
+ sessionGeneration,
1519
+ sessionFile: activeSessionFile,
1520
+ eligibleSettlement
1521
+ }
1522
+ });
1523
+ }
1524
+ function startQueuedCompaction(ctx) {
1525
+ if (compactionState.phase !== "queued")
1526
+ return false;
1527
+ const request = compactionState.request;
1528
+ if (!requestIsCurrent(request)) {
1529
+ setCompactionState(ctx, { phase: "idle" });
1530
+ return false;
1531
+ }
1532
+ if (!ctx.isIdle() || ctx.hasPendingMessages())
1533
+ return false;
1534
+ if (!requestHasCompactableHistory(ctx, request.keep)) {
1535
+ setCompactionState(ctx, { phase: "idle" });
1536
+ return false;
1537
+ }
1538
+ const operation = ++operationGeneration;
1539
+ const generation = request.sessionGeneration;
1540
+ const sessionFile = request.sessionFile;
1541
+ setCompactionState(ctx, {
1542
+ phase: "running",
1543
+ request,
1544
+ owner: "extension",
1545
+ operation,
1546
+ sessionGeneration: generation,
1547
+ sessionFile,
1548
+ hookActive: false
1549
+ });
1418
1550
  ctx.compact({
1419
1551
  onComplete: () => {
1420
- compactionQueued = false;
1421
- pendingKeep = null;
1552
+ if (!runningOperationIsCurrent(operation, generation, sessionFile))
1553
+ return;
1554
+ setCompactionState(ctx, { phase: "idle" });
1422
1555
  },
1423
1556
  onError: (error) => {
1424
- compactionQueued = false;
1425
- pendingKeep = null;
1557
+ if (!runningOperationIsCurrent(operation, generation, sessionFile))
1558
+ return;
1559
+ setCompactionState(ctx, { phase: "idle" });
1426
1560
  const message = error instanceof Error ? error.message : String(error);
1427
1561
  if (ctx.hasUI)
1428
1562
  ctx.ui.notify(`goosedump compaction failed: ${message}`, "error");
1429
1563
  }
1430
1564
  });
1431
- return "started";
1565
+ return true;
1566
+ }
1567
+ function requestCompaction(ctx, keep) {
1568
+ if (compactionState.phase !== "idle")
1569
+ return "busy";
1570
+ if (!requestHasCompactableHistory(ctx, keep))
1571
+ return "nothing-to-compact";
1572
+ setCompactionState(ctx, {
1573
+ phase: "queued",
1574
+ request: {
1575
+ keep,
1576
+ sessionGeneration,
1577
+ sessionFile: activeSessionFile,
1578
+ eligibleSettlement: settlementGeneration + 1
1579
+ }
1580
+ });
1581
+ return startQueuedCompaction(ctx) ? "started" : "queued";
1432
1582
  }
1433
1583
  function register(pi) {
1434
1584
  if (shouldRegisterTool) {
1435
1585
  pi.registerTool(defineTool({
1436
1586
  name: "goose_remember",
1437
1587
  label: "goose_remember",
1438
- description: "Use local gpt-oss-20b to extract typed memories and provenance from a session; store BGE embeddings in SQLite. Defaults to the current Pi session.",
1588
+ description: "Queue local gpt-oss-20b memory extraction and BGE embedding in the background. Defaults to the current Pi session.",
1439
1589
  promptSnippet: "Persist important context from the current or another session into durable memory",
1440
1590
  promptGuidelines: [
1441
1591
  "Use goose_remember after a milestone when important facts, decisions, preferences, procedures, or lessons should be retained.",
@@ -1445,20 +1595,19 @@ function createGoosedumpIntegration(options = {}) {
1445
1595
  provider: historyProviderParam("read"),
1446
1596
  session: historySessionParam()
1447
1597
  }),
1448
- async execute(_id, params, signal, _onUpdate, ctx) {
1598
+ async execute(_id, params, _signal, _onUpdate, ctx) {
1449
1599
  if (!goosedumpAvailable)
1450
1600
  return goosedumpUnavailableResult();
1451
- try {
1452
- const provider = params.provider ?? "pi";
1453
- const target = resolveTarget(ctx, provider, params.session);
1454
- if (!target)
1455
- return missingSessionId("goose_remember", provider);
1456
- const report = await goosedumpMemoryRemember(target, signal, nativeExecutablePath);
1457
- return textResult(report);
1458
- } catch (err) {
1459
- const message = err instanceof Error ? err.message : String(err);
1460
- return textResult(`goosedump error: ${message}`);
1461
- }
1601
+ const provider = params.provider ?? "pi";
1602
+ const target = resolveTarget(ctx, provider, params.session);
1603
+ if (!target)
1604
+ return missingSessionId("goose_remember", provider);
1605
+ enqueueRemember(target, (message) => {
1606
+ if (ctx.hasUI) {
1607
+ ctx.ui.notify(`goosedump memory learning failed: ${message}`, "warning");
1608
+ }
1609
+ });
1610
+ return textResult(`Memory learning queued for ${target}.`);
1462
1611
  }
1463
1612
  }));
1464
1613
  pi.registerTool(defineTool({
@@ -1709,7 +1858,7 @@ function createGoosedumpIntegration(options = {}) {
1709
1858
  if (result === "nothing-to-compact") {
1710
1859
  return textResult("Nothing to compact (session too small).");
1711
1860
  }
1712
- return textResult(compactStartedMessage(keep));
1861
+ return textResult(compactStartedMessage(keep, result === "queued"));
1713
1862
  }
1714
1863
  }));
1715
1864
  pi.registerTool(defineTool({
@@ -1779,82 +1928,163 @@ ${lines.join(`
1779
1928
  }
1780
1929
  }));
1781
1930
  }
1782
- function maybeAutoCompact(ctx) {
1931
+ function handleAgentSettled(ctx) {
1783
1932
  if (!goosedumpAvailable || !shouldOverrideDefaultCompaction)
1784
1933
  return;
1785
- if (!counterTriggered && !normalThresholdTriggered(ctx))
1786
- return;
1787
- if (compactionQueued)
1934
+ settlementGeneration += 1;
1935
+ if (compactionState.phase === "running" && compactionState.owner === "pi") {
1936
+ const request = compactionState.request;
1937
+ setCompactionState(ctx, request && requestIsCurrent(request) ? {
1938
+ phase: "queued",
1939
+ request: { ...request, eligibleSettlement: settlementGeneration + 1 }
1940
+ } : { phase: "idle" });
1788
1941
  return;
1789
- if (ctx.hasPendingMessages())
1790
- return;
1791
- if (!ctx.isIdle())
1792
- return;
1793
- if (!hasCompactableHistory(ctx))
1794
- return;
1795
- syncCompactCounters(ctx, true);
1796
- updateStatus(ctx);
1797
- compactionQueued = true;
1798
- ctx.compact({
1799
- onComplete: () => {
1800
- compactionQueued = false;
1801
- syncCompactCounters(ctx, true);
1802
- updateStatus(ctx);
1803
- },
1804
- onError: (error) => {
1805
- compactionQueued = false;
1806
- syncCompactCounters(ctx, true);
1807
- updateStatus(ctx);
1808
- const message = error instanceof Error ? error.message : String(error);
1809
- if (ctx.hasUI)
1810
- ctx.ui.notify(`goosedump compaction failed: ${message}`, "error");
1811
- }
1812
- });
1942
+ }
1943
+ if (compactionState.phase === "queued" && !requestIsCurrent(compactionState.request)) {
1944
+ setCompactionState(ctx, { phase: "idle" });
1945
+ }
1946
+ if (compactionState.phase === "idle") {
1947
+ queueTurnCompaction(ctx, settlementGeneration);
1948
+ }
1949
+ if (agentEndObserved && compactionState.phase === "queued" && compactionState.request.eligibleSettlement <= settlementGeneration) {
1950
+ startQueuedCompaction(ctx);
1951
+ }
1813
1952
  }
1814
1953
  pi.on("session_start", async (_event, ctx) => {
1954
+ sessionGeneration += 1;
1955
+ settlementGeneration = 0;
1956
+ activeSessionFile = ctx.sessionManager.getSessionFile?.() ?? null;
1957
+ sessionActive = true;
1958
+ agentEndObserved = true;
1959
+ compactionState = { phase: "idle" };
1815
1960
  goosedumpAvailable = checkGoosedump(ctx);
1816
1961
  notifyInvalidSettings(ctx);
1817
- syncCompactCounters(ctx, true);
1962
+ syncCompactCounters(ctx);
1818
1963
  updateStatus(ctx);
1964
+ queueTurnCompaction(ctx, 1);
1965
+ });
1966
+ pi.on("session_shutdown", async () => {
1967
+ sessionGeneration += 1;
1968
+ settlementGeneration = 0;
1969
+ activeSessionFile = null;
1970
+ sessionActive = false;
1971
+ agentEndObserved = true;
1972
+ compactionState = { phase: "idle" };
1973
+ });
1974
+ pi.on("agent_start", async () => {
1975
+ agentEndObserved = false;
1976
+ });
1977
+ pi.on("agent_end", async () => {
1978
+ agentEndObserved = true;
1819
1979
  });
1820
1980
  pi.on("turn_end", async (event, ctx) => {
1821
1981
  if (isCompletedAssistant(event.message))
1822
1982
  noteCompletedTurn(ctx);
1823
1983
  });
1824
1984
  pi.on("agent_settled", async (_event, ctx) => {
1825
- maybeAutoCompact(ctx);
1985
+ handleAgentSettled(ctx);
1826
1986
  });
1827
1987
  pi.on("session_before_compact", async (event, ctx) => {
1828
1988
  if (!shouldOverrideDefaultCompaction || !goosedumpAvailable)
1829
1989
  return;
1830
- if (event.customInstructions?.trim())
1831
- return;
1832
- if (event.signal.aborted)
1833
- return;
1834
- const { messagesToSummarize, turnPrefixMessages } = event.preparation;
1835
- if (pendingKeep === null && messagesToSummarize.length === 0 && turnPrefixMessages.length === 0) {
1990
+ if (event.customInstructions?.trim()) {
1991
+ if (compactionState.phase === "running")
1992
+ return { cancel: true };
1993
+ if (compactionState.phase === "queued") {
1994
+ setCompactionState(ctx, { phase: "idle" });
1995
+ }
1836
1996
  return;
1837
1997
  }
1838
- const target = currentSessionTarget(ctx);
1839
- if (!target)
1998
+ if (event.signal.aborted) {
1999
+ if (compactionState.phase === "queued" && requestIsCurrent(compactionState.request)) {
2000
+ setCompactionState(ctx, event.reason === "manual" ? { phase: "idle" } : {
2001
+ phase: "queued",
2002
+ request: {
2003
+ ...compactionState.request,
2004
+ eligibleSettlement: Math.max(compactionState.request.eligibleSettlement, settlementGeneration + 2)
2005
+ }
2006
+ });
2007
+ }
1840
2008
  return;
1841
- if (compactionHookActive)
1842
- return { cancel: true };
1843
- compactionHookActive = true;
2009
+ }
2010
+ let operation;
2011
+ let generation;
2012
+ let sessionFile;
2013
+ let request;
2014
+ let owner;
2015
+ if (compactionState.phase === "running") {
2016
+ if (compactionState.hookActive || compactionState.owner === "pi") {
2017
+ return { cancel: true };
2018
+ }
2019
+ operation = compactionState.operation;
2020
+ generation = compactionState.sessionGeneration;
2021
+ sessionFile = compactionState.sessionFile;
2022
+ request = compactionState.request;
2023
+ owner = "extension";
2024
+ compactionState = { ...compactionState, hookActive: true };
2025
+ } else {
2026
+ request = compactionState.phase === "queued" && requestIsCurrent(compactionState.request) ? compactionState.request : null;
2027
+ operation = ++operationGeneration;
2028
+ generation = sessionGeneration;
2029
+ sessionFile = activeSessionFile;
2030
+ owner = "pi";
2031
+ setCompactionState(ctx, {
2032
+ phase: "running",
2033
+ request,
2034
+ owner,
2035
+ operation,
2036
+ sessionGeneration: generation,
2037
+ sessionFile,
2038
+ hookActive: true
2039
+ });
2040
+ }
1844
2041
  try {
1845
- const keep = pendingKeep ?? undefined;
1846
- const compaction = await buildGoosedumpCompaction(target, event.preparation, event.branchEntries, effectiveSummaryMaxTokens(ctx.cwd), keep, event.signal, nativeExecutablePath);
2042
+ const { messagesToSummarize, turnPrefixMessages } = event.preparation;
2043
+ if ((request?.keep ?? null) === null && messagesToSummarize.length === 0 && turnPrefixMessages.length === 0) {
2044
+ return;
2045
+ }
2046
+ const target = currentSessionTarget(ctx);
2047
+ if (!target)
2048
+ return;
2049
+ let keep = request?.keep ?? undefined;
2050
+ if (keep !== undefined && keepBoundaryId(event.branchEntries, keep) === undefined) {
2051
+ if (ctx.hasUI) {
2052
+ ctx.ui.notify(`fewer than ${keep} user turns; using Pi's token-based cut`, "info");
2053
+ }
2054
+ keep = undefined;
2055
+ if (runningOperationIsCurrent(operation, generation, sessionFile)) {
2056
+ request = null;
2057
+ setCompactionState(ctx, {
2058
+ phase: "running",
2059
+ request,
2060
+ owner,
2061
+ operation,
2062
+ sessionGeneration: generation,
2063
+ sessionFile,
2064
+ hookActive: true
2065
+ });
2066
+ }
2067
+ }
2068
+ const compaction = await buildGoosedumpCompaction(target, event.preparation, event.branchEntries, effectiveSummaryMaxTokens(ctx.cwd, projectSettingsTrusted(ctx)), keep, event.signal, nativeExecutablePath);
2069
+ if (!runningOperationIsCurrent(operation, generation, sessionFile)) {
2070
+ return { cancel: true };
2071
+ }
1847
2072
  if (compaction && "cancel" in compaction) {
1848
2073
  if (ctx.hasUI)
1849
2074
  ctx.ui.notify(compaction.reason, "info");
1850
- return { cancel: true };
2075
+ return;
1851
2076
  }
1852
2077
  const warning = compaction?.details?.warning;
1853
2078
  if (warning && ctx.hasUI) {
1854
2079
  ctx.ui.notify(warning, "warning");
1855
2080
  }
1856
- return compaction ? { compaction } : undefined;
2081
+ if (compaction)
2082
+ return { compaction };
2083
+ return;
1857
2084
  } catch (err) {
2085
+ if (!runningOperationIsCurrent(operation, generation, sessionFile)) {
2086
+ return { cancel: true };
2087
+ }
1858
2088
  if (event.signal.aborted)
1859
2089
  return { cancel: true };
1860
2090
  if (ctx.hasUI) {
@@ -1863,15 +2093,32 @@ ${lines.join(`
1863
2093
  }
1864
2094
  return;
1865
2095
  } finally {
1866
- compactionHookActive = false;
1867
- pendingKeep = null;
2096
+ if (runningOperationIsCurrent(operation, generation, sessionFile)) {
2097
+ setCompactionState(ctx, owner === "pi" && event.reason === "manual" ? { phase: "idle" } : {
2098
+ phase: "running",
2099
+ request,
2100
+ owner,
2101
+ operation,
2102
+ sessionGeneration: generation,
2103
+ sessionFile,
2104
+ hookActive: false
2105
+ });
2106
+ }
1868
2107
  }
1869
2108
  });
1870
2109
  pi.on("session_compact", async (event, ctx) => {
1871
- if (!goosedumpAvailable || !shouldOverrideDefaultCompaction)
2110
+ if (!shouldOverrideDefaultCompaction)
2111
+ return;
2112
+ if (!contextIsCurrent(ctx))
1872
2113
  return;
1873
- syncCompactCounters(ctx, true);
2114
+ if (compactionState.phase === "queued" && compactionState.request.keep !== null && ctx.hasUI) {
2115
+ ctx.ui.notify("Queued keep request was superseded by another compaction.", "info");
2116
+ }
2117
+ compactionState = { phase: "idle" };
2118
+ syncCompactCounters(ctx);
1874
2119
  updateStatus(ctx);
2120
+ if (!goosedumpAvailable)
2121
+ return;
1875
2122
  const compactionEntry = event.compactionEntry;
1876
2123
  if (!event.fromExtension || !compactionEntry || !isRecord(compactionEntry.details) || compactionEntry.details.source !== "goosedump") {
1877
2124
  return;
@@ -1936,7 +2183,7 @@ ${lines.join(`
1936
2183
  } else if (result === "nothing-to-compact") {
1937
2184
  ctx.ui.notify("Nothing to compact (session too small)", "info");
1938
2185
  } else {
1939
- ctx.ui.notify(compactStartedMessage(keep), "info");
2186
+ ctx.ui.notify(compactStartedMessage(keep, result === "queued"), "info");
1940
2187
  }
1941
2188
  }
1942
2189
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-goosedump",
3
- "version": "0.12.14",
3
+ "version": "0.12.16",
4
4
  "description": "Pi extension for goosedump session search, durable memory, and compaction",
5
5
  "keywords": [
6
6
  "compaction",
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "@earendil-works/pi-tui": "^0.82.1",
41
- "@jarkkojs/goosedump": "^0.12.14",
41
+ "@jarkkojs/goosedump": "^0.12.16",
42
42
  "@sinclair/typebox": "^0.34.49"
43
43
  },
44
44
  "devDependencies": {