@remnic/core 10.0.108 → 10.0.110

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 (76) hide show
  1. package/dist/access-admin-ops-surface.js +15 -15
  2. package/dist/access-cli.js +15 -15
  3. package/dist/access-coding-context-resolution.d.ts.map +1 -1
  4. package/dist/access-coding-context-resolution.js +2 -2
  5. package/dist/access-extraction-force-flush.js +15 -15
  6. package/dist/access-http-briefing.js +15 -15
  7. package/dist/access-http-query.js +15 -15
  8. package/dist/access-http.js +15 -15
  9. package/dist/access-identity-continuity-surface.js +15 -15
  10. package/dist/access-lcm-surface.js +15 -15
  11. package/dist/access-mcp.js +15 -15
  12. package/dist/access-observe-transcript.js +2 -2
  13. package/dist/access-observe-write-surface.js +15 -15
  14. package/dist/access-offline-manifest.js +5 -5
  15. package/dist/access-operations-batch.js +15 -15
  16. package/dist/access-operations.js +15 -15
  17. package/dist/access-recall-concurrency.js +15 -15
  18. package/dist/access-recall-response.js +15 -15
  19. package/dist/access-recall-surface.js +15 -15
  20. package/dist/access-service.js +15 -15
  21. package/dist/buffer.js +4 -4
  22. package/dist/{chunk-NUQEREIP.js → chunk-3QNFHI6T.js} +6 -4
  23. package/dist/chunk-3QNFHI6T.js.map +1 -0
  24. package/dist/{chunk-CCFGLUSC.js → chunk-4TYIHHPW.js} +18 -17
  25. package/dist/chunk-4TYIHHPW.js.map +1 -0
  26. package/dist/{chunk-4RAJT5L2.js → chunk-5HFCXTGY.js} +99 -4
  27. package/dist/chunk-5HFCXTGY.js.map +1 -0
  28. package/dist/{chunk-QZPXXABV.js → chunk-7ZEF43SR.js} +4 -4
  29. package/dist/{chunk-YU3TOAXV.js → chunk-AOAREXFV.js} +2 -2
  30. package/dist/{chunk-GCZJ7XRI.js → chunk-EAHNSQ7H.js} +2 -2
  31. package/dist/{chunk-LGEHAQHK.js → chunk-HRWZEP5O.js} +2 -2
  32. package/dist/{chunk-PZJQ46DH.js → chunk-JCAMHTS2.js} +2 -2
  33. package/dist/{chunk-5NFF2TSD.js → chunk-KBUFYKUN.js} +2 -2
  34. package/dist/{chunk-4IJFJQPD.js → chunk-MYXJCR3E.js} +2 -2
  35. package/dist/{chunk-4ANH42MO.js → chunk-OLJYBMFW.js} +2 -2
  36. package/dist/{chunk-V2QSNFCT.js → chunk-U5I2G4VU.js} +2 -2
  37. package/dist/{chunk-2R3ACFYN.js → chunk-U7LMXR2W.js} +2 -2
  38. package/dist/{chunk-QRMG4HK4.js → chunk-UPWOMMVU.js} +3 -3
  39. package/dist/{chunk-2BXPAOOR.js → chunk-VLUWWPKO.js} +2 -2
  40. package/dist/{chunk-HCCRWSP7.js → chunk-WOXO4HE6.js} +3 -3
  41. package/dist/cli.js +15 -15
  42. package/dist/coding/export-okf-codegraph.js +1 -1
  43. package/dist/coding/git-context.d.ts +33 -0
  44. package/dist/coding/git-context.d.ts.map +1 -1
  45. package/dist/explicit-capture.js +15 -15
  46. package/dist/extraction.js +5 -5
  47. package/dist/index.js +15 -15
  48. package/dist/offline-sync-impression-drain.js +4 -4
  49. package/dist/operator-toolkit.js +5 -5
  50. package/dist/orchestration/backlog-scheduler.js +16 -16
  51. package/dist/orchestration/buffer-drain-runner.js +16 -16
  52. package/dist/orchestration/maintenance.js +5 -5
  53. package/dist/orchestrator.js +15 -15
  54. package/dist/recall-navigation.js +15 -15
  55. package/dist/source-agent-qualifier.js +4 -4
  56. package/package.json +2 -2
  57. package/src/access-coding-context-resolution.ts +2 -1
  58. package/src/access-service.ts +2 -2
  59. package/src/coding/git-context.test.ts +270 -0
  60. package/src/coding/git-context.ts +140 -3
  61. package/dist/chunk-4RAJT5L2.js.map +0 -1
  62. package/dist/chunk-CCFGLUSC.js.map +0 -1
  63. package/dist/chunk-NUQEREIP.js.map +0 -1
  64. /package/dist/{chunk-QZPXXABV.js.map → chunk-7ZEF43SR.js.map} +0 -0
  65. /package/dist/{chunk-YU3TOAXV.js.map → chunk-AOAREXFV.js.map} +0 -0
  66. /package/dist/{chunk-GCZJ7XRI.js.map → chunk-EAHNSQ7H.js.map} +0 -0
  67. /package/dist/{chunk-LGEHAQHK.js.map → chunk-HRWZEP5O.js.map} +0 -0
  68. /package/dist/{chunk-PZJQ46DH.js.map → chunk-JCAMHTS2.js.map} +0 -0
  69. /package/dist/{chunk-5NFF2TSD.js.map → chunk-KBUFYKUN.js.map} +0 -0
  70. /package/dist/{chunk-4IJFJQPD.js.map → chunk-MYXJCR3E.js.map} +0 -0
  71. /package/dist/{chunk-4ANH42MO.js.map → chunk-OLJYBMFW.js.map} +0 -0
  72. /package/dist/{chunk-V2QSNFCT.js.map → chunk-U5I2G4VU.js.map} +0 -0
  73. /package/dist/{chunk-2R3ACFYN.js.map → chunk-U7LMXR2W.js.map} +0 -0
  74. /package/dist/{chunk-QRMG4HK4.js.map → chunk-UPWOMMVU.js.map} +0 -0
  75. /package/dist/{chunk-2BXPAOOR.js.map → chunk-VLUWWPKO.js.map} +0 -0
  76. /package/dist/{chunk-HCCRWSP7.js.map → chunk-WOXO4HE6.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runRecallNavigation
3
- } from "./chunk-CCFGLUSC.js";
3
+ } from "./chunk-4TYIHHPW.js";
4
4
  import "./chunk-6P7U3HWG.js";
5
5
  import "./chunk-PQM3B54K.js";
6
6
  import "./chunk-B3DR2JBZ.js";
@@ -28,7 +28,7 @@ import "./chunk-5VWN3FJS.js";
28
28
  import "./chunk-RXSGBO7Y.js";
29
29
  import "./chunk-TBUEE7XF.js";
30
30
  import "./chunk-5PHOU5QI.js";
31
- import "./chunk-2BXPAOOR.js";
31
+ import "./chunk-VLUWWPKO.js";
32
32
  import "./chunk-I74SUMNI.js";
33
33
  import "./chunk-ILNPU5W5.js";
34
34
  import "./chunk-FGDKJJZS.js";
@@ -144,8 +144,8 @@ import "./chunk-MGN2RQRG.js";
144
144
  import "./chunk-EVWDNKQA.js";
145
145
  import "./chunk-2LA3H54D.js";
146
146
  import "./chunk-ROI7BK7H.js";
147
- import "./chunk-4ANH42MO.js";
148
- import "./chunk-YU3TOAXV.js";
147
+ import "./chunk-OLJYBMFW.js";
148
+ import "./chunk-AOAREXFV.js";
149
149
  import "./chunk-KFY3SGN7.js";
150
150
  import "./chunk-3T74IZB3.js";
151
151
  import "./chunk-CMTINOFS.js";
@@ -184,9 +184,9 @@ import "./chunk-IHCXMYSE.js";
184
184
  import "./chunk-D6IGZYTN.js";
185
185
  import "./chunk-W7K5BP3M.js";
186
186
  import "./chunk-LZIOY7ZU.js";
187
- import "./chunk-2R3ACFYN.js";
187
+ import "./chunk-U7LMXR2W.js";
188
188
  import "./chunk-EI6V5UXY.js";
189
- import "./chunk-4IJFJQPD.js";
189
+ import "./chunk-MYXJCR3E.js";
190
190
  import "./chunk-UA2NDTIU.js";
191
191
  import "./chunk-6XTUZKCZ.js";
192
192
  import "./chunk-54V4BZWP.js";
@@ -284,8 +284,8 @@ import "./chunk-GKCXTSFF.js";
284
284
  import "./chunk-2LSZVONP.js";
285
285
  import "./chunk-DEUNUKTD.js";
286
286
  import "./chunk-LXY5VVGM.js";
287
- import "./chunk-5NFF2TSD.js";
288
- import "./chunk-HCCRWSP7.js";
287
+ import "./chunk-KBUFYKUN.js";
288
+ import "./chunk-WOXO4HE6.js";
289
289
  import "./chunk-THV6PZ7V.js";
290
290
  import "./chunk-CSAKJVXW.js";
291
291
  import "./chunk-K2XUWZBM.js";
@@ -439,12 +439,12 @@ import "./chunk-RMMA44HE.js";
439
439
  import "./chunk-T4KY6UYF.js";
440
440
  import "./chunk-P3WRNWWM.js";
441
441
  import "./chunk-SYOIVK7K.js";
442
- import "./chunk-LGEHAQHK.js";
442
+ import "./chunk-HRWZEP5O.js";
443
443
  import "./chunk-M2XR6B6V.js";
444
444
  import "./chunk-JDY34KBL.js";
445
- import "./chunk-V2QSNFCT.js";
446
- import "./chunk-QRMG4HK4.js";
447
- import "./chunk-PZJQ46DH.js";
445
+ import "./chunk-U5I2G4VU.js";
446
+ import "./chunk-UPWOMMVU.js";
447
+ import "./chunk-JCAMHTS2.js";
448
448
  import "./chunk-EHHQJTAU.js";
449
449
  import "./chunk-L272A5QW.js";
450
450
  import "./chunk-BNZAR6PO.js";
@@ -475,7 +475,7 @@ import "./chunk-AQEJKOKI.js";
475
475
  import "./chunk-4RNBLLZR.js";
476
476
  import "./chunk-C5LWPYS3.js";
477
477
  import "./chunk-WZU5AGO6.js";
478
- import "./chunk-GCZJ7XRI.js";
478
+ import "./chunk-EAHNSQ7H.js";
479
479
  import "./chunk-25BUV3TU.js";
480
480
  import "./chunk-4IVRQMZW.js";
481
481
  import "./chunk-353C5UNV.js";
@@ -525,8 +525,8 @@ import "./chunk-2BPPGNAQ.js";
525
525
  import "./chunk-5R627MYY.js";
526
526
  import "./chunk-F5GVIPC7.js";
527
527
  import "./chunk-X4OZMANG.js";
528
- import "./chunk-NUQEREIP.js";
529
- import "./chunk-4RAJT5L2.js";
528
+ import "./chunk-3QNFHI6T.js";
529
+ import "./chunk-5HFCXTGY.js";
530
530
  import "./chunk-ZEFVK7XC.js";
531
531
  import "./chunk-I3V3JJS7.js";
532
532
  import "./chunk-DJSJ4ULL.js";
@@ -3,7 +3,7 @@ import {
3
3
  headerConnector,
4
4
  renderExtractionConversation,
5
5
  resolveSourceConnector
6
- } from "./chunk-4IJFJQPD.js";
6
+ } from "./chunk-MYXJCR3E.js";
7
7
  import "./chunk-UA2NDTIU.js";
8
8
  import "./chunk-6XTUZKCZ.js";
9
9
  import "./chunk-D3ZKHLN2.js";
@@ -14,7 +14,7 @@ import "./chunk-VEWZZM3H.js";
14
14
  import "./chunk-WCKLRFGF.js";
15
15
  import "./chunk-3UXOZBHV.js";
16
16
  import "./chunk-AL3TCNSJ.js";
17
- import "./chunk-HCCRWSP7.js";
17
+ import "./chunk-WOXO4HE6.js";
18
18
  import "./chunk-THV6PZ7V.js";
19
19
  import "./chunk-CSAKJVXW.js";
20
20
  import "./chunk-K2XUWZBM.js";
@@ -93,7 +93,7 @@ import "./chunk-W5BIQOAJ.js";
93
93
  import "./chunk-HADD45AR.js";
94
94
  import "./chunk-RNFMFC37.js";
95
95
  import "./chunk-C5C7IJ4Q.js";
96
- import "./chunk-PZJQ46DH.js";
96
+ import "./chunk-JCAMHTS2.js";
97
97
  import "./chunk-L272A5QW.js";
98
98
  import "./chunk-BNZAR6PO.js";
99
99
  import "./chunk-ZA53AZND.js";
@@ -126,7 +126,7 @@ import "./chunk-5GKPFL3S.js";
126
126
  import "./chunk-JAKIDQB2.js";
127
127
  import "./chunk-P7FMDTKL.js";
128
128
  import "./chunk-X4OZMANG.js";
129
- import "./chunk-4RAJT5L2.js";
129
+ import "./chunk-5HFCXTGY.js";
130
130
  import "./chunk-ZEFVK7XC.js";
131
131
  import "./chunk-R2MBW2S4.js";
132
132
  import "./chunk-M5GVCJSJ.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remnic/core",
3
- "version": "10.0.108",
3
+ "version": "10.0.110",
4
4
  "description": "Framework-agnostic Remnic memory engine — orchestrator, storage, extraction, search, trust zones",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -3386,7 +3386,7 @@
3386
3386
  "core"
3387
3387
  ],
3388
3388
  "peerDependencies": {
3389
- "@remnic/coding-graph": "^10.0.108"
3389
+ "@remnic/coding-graph": "^10.0.110"
3390
3390
  },
3391
3391
  "peerDependenciesMeta": {
3392
3392
  "@remnic/coding-graph": {
@@ -1,5 +1,5 @@
1
1
  import { projectTagProjectId } from "./coding/coding-namespace.js";
2
- import { resolveGitContext } from "./coding/git-context.js";
2
+ import { resolveGitContext, sharedGitContextCache } from "./coding/git-context.js";
3
3
  import type { CodingContext } from "./types.js";
4
4
 
5
5
  export interface InterruptibleCodingScopeInput {
@@ -22,6 +22,7 @@ export async function resolveCodingContextFromOptions(
22
22
  const gitContext = await resolveGitContext(options.cwd, {
23
23
  abortSignal: options.abortSignal,
24
24
  deadlineMs: options.deadlineMs,
25
+ cache: sharedGitContextCache,
25
26
  });
26
27
  if (!gitContext) return null;
27
28
  return {
@@ -81,7 +81,7 @@ import {
81
81
  type DecisionSurfaceResponse,
82
82
  handleCodingDecision,
83
83
  } from "./coding/decision-surfaces.js";
84
- import { resolveGitContext } from "./coding/git-context.js";
84
+ import { resolveGitContext, sharedNonRepoGitContextCache } from "./coding/git-context.js";
85
85
  import { defaultGitInvokerSync } from "./coding/git-context.js";
86
86
  import {
87
87
  type DeltaSurfaceRequest,
@@ -2591,7 +2591,7 @@ export class EngramAccessService extends SupportPassportAccessServiceBase {
2591
2591
  // cwd → git resolution
2592
2592
  if (typeof options.cwd === "string" && options.cwd.trim().length > 0) {
2593
2593
  try {
2594
- const gitCtx = await resolveGitContext(options.cwd);
2594
+ const gitCtx = await resolveGitContext(options.cwd, { cache: sharedNonRepoGitContextCache });
2595
2595
  if (gitCtx) {
2596
2596
  this.setCodingContext({
2597
2597
  sessionKey,
@@ -7,10 +7,14 @@
7
7
  */
8
8
 
9
9
  import assert from "node:assert/strict";
10
+ import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
11
+ import os from "node:os";
12
+ import path from "node:path";
10
13
  import test from "node:test";
11
14
 
12
15
  import {
13
16
  expandTildePath,
17
+ GitContextCache,
14
18
  normalizeOriginUrl,
15
19
  resolveGitContext,
16
20
  stableHash,
@@ -552,3 +556,269 @@ test("resolveGitContext: cwd inside repo returns repo root, not cwd", async () =
552
556
  assert.ok(ctx);
553
557
  assert.equal(ctx!.rootPath, root);
554
558
  });
559
+
560
+ // ──────────────────────────────────────────────────────────────────────────
561
+ // Memoization (COS-666): per-request git spawns blocked the event loop.
562
+ // ──────────────────────────────────────────────────────────────────────────
563
+
564
+ async function makeRepoDir(head: string): Promise<string> {
565
+ const root = await mkdtemp(path.join(os.tmpdir(), "git-context-cache-"));
566
+ await mkdir(path.join(root, ".git"));
567
+ await writeFile(path.join(root, ".git", "HEAD"), head);
568
+ return root;
569
+ }
570
+
571
+ function rootInvoker(root: string, onCall?: () => void, branch: () => string = () => "main"): GitInvoker {
572
+ return (_cwd, args) => {
573
+ onCall?.();
574
+ if (args[0] === "rev-parse" && args[1] === "--show-toplevel") return { stdout: `${root}\n`, exitCode: 0 };
575
+ if (args[0] === "rev-parse") return { stdout: `${branch()}\n`, exitCode: 0 };
576
+ return { stdout: "", exitCode: 1 };
577
+ };
578
+ }
579
+
580
+ test("resolveGitContext with a cache spawns git once per cwd within the TTL", async () => {
581
+ const root = await makeRepoDir("ref: refs/heads/main\n");
582
+ let calls = 0;
583
+ const invoker = rootInvoker(root, () => {
584
+ calls += 1;
585
+ });
586
+ let clock = 1_000;
587
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => clock });
588
+ const first = await resolveGitContext("/repo/sub", { invoker, cache });
589
+ const callsAfterFirst = calls;
590
+ assert.ok(first);
591
+ assert.ok(callsAfterFirst > 0);
592
+
593
+ clock += 29_000;
594
+ assert.deepEqual(await resolveGitContext("/repo/sub", { invoker, cache }), first);
595
+ assert.equal(calls, callsAfterFirst, "cache hit must not spawn git");
596
+
597
+ clock += 2_000; // past TTL
598
+ await resolveGitContext("/repo/sub", { invoker, cache });
599
+ assert.equal(calls, callsAfterFirst * 2, "expired entry re-resolves");
600
+ });
601
+
602
+ test("a cache hit is served only while HEAD is unchanged; a checkout re-asks git", async () => {
603
+ const root = await makeRepoDir("ref: refs/heads/main\n");
604
+ let calls = 0;
605
+ let branch = "main";
606
+ const invoker = rootInvoker(
607
+ root,
608
+ () => {
609
+ calls += 1;
610
+ },
611
+ () => branch,
612
+ );
613
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
614
+ assert.equal((await resolveGitContext("/repo", { invoker, cache }))?.branch, "main");
615
+ const callsAfterFirst = calls;
616
+ assert.equal((await resolveGitContext("/repo", { invoker, cache }))?.branch, "main");
617
+ assert.equal(calls, callsAfterFirst, "unchanged HEAD: no spawn");
618
+
619
+ // Git, not a regex over HEAD, names the branch (e.g. heads/main when a tag shares the name).
620
+ branch = "heads/feat";
621
+ await writeFile(path.join(root, ".git", "HEAD"), "ref: refs/heads/feat\n");
622
+ assert.equal((await resolveGitContext("/repo", { invoker, cache }))?.branch, "heads/feat");
623
+ assert.ok(calls > callsAfterFirst, "checkout must re-ask git");
624
+ const callsAfterCheckout = calls;
625
+ assert.equal((await resolveGitContext("/repo", { invoker, cache }))?.branch, "heads/feat");
626
+ assert.equal(calls, callsAfterCheckout, "the new HEAD is cached again");
627
+ });
628
+
629
+ test("a cache hit follows a linked worktree's .git file, and re-resolves when HEAD is unreadable", async () => {
630
+ const gitDir = await makeRepoDir("ref: refs/heads/wt-branch\n");
631
+ const worktree = await mkdtemp(path.join(os.tmpdir(), "git-context-wt-"));
632
+ await writeFile(path.join(worktree, ".git"), `gitdir: ${path.join(gitDir, ".git")}\n`);
633
+ let calls = 0;
634
+ const invoker = rootInvoker(worktree, () => {
635
+ calls += 1;
636
+ });
637
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
638
+ await resolveGitContext("/wt", { invoker, cache });
639
+ const callsAfterFirst = calls;
640
+ await resolveGitContext("/wt", { invoker, cache });
641
+ assert.equal(calls, callsAfterFirst, "worktree HEAD unchanged: served from cache");
642
+
643
+ await rm(path.join(gitDir, ".git", "HEAD"));
644
+ await resolveGitContext("/wt", { invoker, cache });
645
+ assert.ok(calls > callsAfterFirst, "unreadable HEAD falls back to a full resolve");
646
+ });
647
+
648
+ test("HEADs that cannot vouch for the branch (reftable placeholder, symlink) are never cached", async () => {
649
+ const reftable = await makeRepoDir("ref: refs/heads/.invalid\n");
650
+ const symlinked = await makeRepoDir("ref: refs/heads/main\n");
651
+ await rm(path.join(symlinked, ".git", "HEAD"));
652
+ await symlink("refs/heads/main", path.join(symlinked, ".git", "HEAD"));
653
+ for (const root of [reftable, symlinked]) {
654
+ let calls = 0;
655
+ const invoker = rootInvoker(root, () => {
656
+ calls += 1;
657
+ });
658
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
659
+ await resolveGitContext("/repo", { invoker, cache });
660
+ const afterFirst = calls;
661
+ await resolveGitContext("/repo", { invoker, cache });
662
+ assert.equal(calls, afterFirst * 2, `${root} must be re-resolved on every call`);
663
+ }
664
+ });
665
+
666
+ test("a cache hit returns a copy, so a caller cannot poison the cached entry", async () => {
667
+ const root = await makeRepoDir("ref: refs/heads/main\n");
668
+ const invoker = rootInvoker(root);
669
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
670
+ const first = await resolveGitContext("/repo", { invoker, cache });
671
+ first!.branch = "poisoned-first";
672
+ assert.equal((await resolveGitContext("/repo", { invoker, cache }))?.branch, "main");
673
+ const hit = await resolveGitContext("/repo", { invoker, cache });
674
+ hit!.branch = "poisoned";
675
+ assert.equal((await resolveGitContext("/repo", { invoker, cache }))?.branch, "main");
676
+ });
677
+
678
+ test("a checkout racing the branch probe is not pinned: the next call re-asks git", async () => {
679
+ const root = await makeRepoDir("ref: refs/heads/main\n");
680
+ let calls = 0;
681
+ let branch = "main";
682
+ const racing: GitInvoker = async (cwd, args) => {
683
+ const result = await rootInvoker(root, () => {
684
+ calls += 1;
685
+ }, () => branch)(cwd, args);
686
+ if (args[1] === "--abbrev-ref") {
687
+ // git has answered "main"; the checkout lands right after.
688
+ branch = "feat";
689
+ await writeFile(path.join(root, ".git", "HEAD"), "ref: refs/heads/feat\n");
690
+ }
691
+ return result;
692
+ };
693
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
694
+ assert.equal((await resolveGitContext("/repo", { invoker: racing, cache }))?.branch, "main");
695
+ assert.equal((await resolveGitContext("/repo", { invoker: racing, cache }))?.branch, "feat");
696
+ });
697
+
698
+ test("a lookup aborted mid-flight is not cached even if the invoker swallows the abort", async () => {
699
+ const controller = new AbortController();
700
+ let calls = 0;
701
+ const swallowing: GitInvoker = () => {
702
+ calls += 1;
703
+ controller.abort(new Error("stop"));
704
+ return { stdout: "", exitCode: 1 };
705
+ };
706
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
707
+ await resolveGitContext("/repo", { invoker: swallowing, cache, abortSignal: controller.signal });
708
+ assert.equal(cache.has("/repo"), false);
709
+ assert.equal(calls, 1);
710
+ });
711
+
712
+ test("a throwing invoker is not cached as 'not a repo'", async () => {
713
+ let calls = 0;
714
+ const throwing: GitInvoker = () => {
715
+ calls += 1;
716
+ throw new Error("EMFILE");
717
+ };
718
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
719
+ assert.equal(await resolveGitContext("/repo", { invoker: throwing, cache }), null);
720
+ assert.equal(await resolveGitContext("/repo", { invoker: throwing, cache }), null);
721
+ assert.equal(calls, 2);
722
+ });
723
+
724
+ test("resolveGitContext cache also remembers 'not a repo' and never caches aborts", async () => {
725
+ let calls = 0;
726
+ const notRepo: GitInvoker = () => {
727
+ calls += 1;
728
+ return { stdout: "", exitCode: 128 };
729
+ };
730
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
731
+ assert.equal(await resolveGitContext("/tmp/x", { invoker: notRepo, cache }), null);
732
+ assert.equal(await resolveGitContext("/tmp/x", { invoker: notRepo, cache }), null);
733
+ assert.equal(calls, 1);
734
+
735
+ const controller = new AbortController();
736
+ controller.abort(new Error("stop"));
737
+ await assert.rejects(resolveGitContext("/tmp/y", { invoker: notRepo, cache, abortSignal: controller.signal }));
738
+ assert.equal(await resolveGitContext("/tmp/y", { invoker: notRepo, cache }), null, "abort was not cached");
739
+ });
740
+
741
+ test("GitContextCache is bounded", async () => {
742
+ const cache = new GitContextCache({ ttlMs: 30_000, maxEntries: 2, now: () => 0 });
743
+ cache.set("a", null);
744
+ cache.set("b", null);
745
+ cache.set("c", null);
746
+ assert.equal(cache.has("a"), false);
747
+ assert.equal(cache.has("c"), true);
748
+ });
749
+
750
+ test("a warm cache hit still honors an aborted signal and an expired deadline", async () => {
751
+ const root = await makeRepoDir("ref: refs/heads/main\n");
752
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
753
+ await resolveGitContext("/repo", { invoker: rootInvoker(root), cache });
754
+ assert.equal(cache.has("/repo"), true, "the fixture must reach the cache or this test proves nothing");
755
+
756
+ const controller = new AbortController();
757
+ controller.abort(new Error("stop"));
758
+ await assert.rejects(
759
+ resolveGitContext("/repo", { invoker: rootInvoker(root), cache, abortSignal: controller.signal }),
760
+ /stop/,
761
+ );
762
+ await assert.rejects(
763
+ resolveGitContext("/repo", { invoker: rootInvoker(root), cache, deadlineMs: 100, now: () => 200 }),
764
+ /deadline/,
765
+ );
766
+ });
767
+
768
+ test("a probe timeout (exit 124) or spawn failure (127) is not cached as 'not a repo'", async () => {
769
+ for (const exitCode of [124, 127]) {
770
+ let calls = 0;
771
+ const flaky: GitInvoker = () => {
772
+ calls += 1;
773
+ return { stdout: "", exitCode };
774
+ };
775
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
776
+ assert.equal(await resolveGitContext("/repo", { invoker: flaky, cache }), null);
777
+ assert.equal(await resolveGitContext("/repo", { invoker: flaky, cache }), null);
778
+ assert.equal(calls, 2, `exit ${exitCode} must be retried, not cached`);
779
+ }
780
+ });
781
+
782
+ test("a partial context (later probe timed out) is not cached", async () => {
783
+ let originCalls = 0;
784
+ const root = await makeRepoDir("ref: refs/heads/main\n");
785
+ const partial: GitInvoker = (cwd, args) => {
786
+ if (args[0] === "remote") {
787
+ originCalls += 1;
788
+ return { stdout: "", exitCode: 124 };
789
+ }
790
+ return rootInvoker(root)(cwd, args);
791
+ };
792
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
793
+ assert.ok(await resolveGitContext("/repo", { invoker: partial, cache }));
794
+ assert.ok(await resolveGitContext("/repo", { invoker: partial, cache }));
795
+ assert.equal(originCalls, 2);
796
+ });
797
+
798
+ test("a non-repo-only cache remembers non-repos but always re-reads repos", async () => {
799
+ const root = await makeRepoDir("ref: refs/heads/main\n");
800
+ let calls = 0;
801
+ const count = () => {
802
+ calls += 1;
803
+ };
804
+ const cacheable = new GitContextCache({ ttlMs: 30_000, now: () => 0 });
805
+ await resolveGitContext("/repo", { invoker: rootInvoker(root, count), cache: cacheable });
806
+ assert.equal(cacheable.has("/repo"), true, "default policy caches this fixture");
807
+
808
+ calls = 0;
809
+ const cache = new GitContextCache({ ttlMs: 30_000, now: () => 0, cacheRepos: false });
810
+ await resolveGitContext("/repo", { invoker: rootInvoker(root, count), cache });
811
+ const afterFirst = calls;
812
+ await resolveGitContext("/repo", { invoker: rootInvoker(root, count), cache });
813
+ assert.equal(cache.has("/repo"), false);
814
+ assert.equal(calls, afterFirst * 2, "repo result must not be served from a non-repo cache");
815
+
816
+ let nonRepoCalls = 0;
817
+ const notRepo: GitInvoker = () => {
818
+ nonRepoCalls += 1;
819
+ return { stdout: "", exitCode: 128 };
820
+ };
821
+ await resolveGitContext("/tmp/z", { invoker: notRepo, cache });
822
+ await resolveGitContext("/tmp/z", { invoker: notRepo, cache });
823
+ assert.equal(nonRepoCalls, 1);
824
+ });
@@ -21,6 +21,7 @@
21
21
  * when the directory is not inside a git worktree, because being outside a
22
22
  * repo is a normal runtime state (e.g. agent opened in a scratch dir).
23
23
  */
24
+ import { lstat, readFile, stat } from "node:fs/promises";
24
25
  import path from "node:path";
25
26
 
26
27
  import { abortError } from "../abort-error.js";
@@ -96,6 +97,8 @@ export interface SyncGitInvoker {
96
97
  // ──────────────────────────────────────────────────────────────────────────
97
98
 
98
99
  const DEFAULT_GIT_TIMEOUT_MS = 2_000;
100
+ const GIT_TIMEOUT_EXIT_CODE = 124;
101
+ const GIT_SPAWN_ERROR_EXIT_CODE = 127;
99
102
 
100
103
  export function defaultGitInvokerSync(): SyncGitInvoker {
101
104
  return (cwd: string, args: string[]) => {
@@ -105,7 +108,7 @@ export function defaultGitInvokerSync(): SyncGitInvoker {
105
108
  timeout: DEFAULT_GIT_TIMEOUT_MS,
106
109
  shell: false,
107
110
  });
108
- if (result.error) return { stdout: "", exitCode: 127 };
111
+ if (result.error) return { stdout: "", exitCode: GIT_SPAWN_ERROR_EXIT_CODE };
109
112
  return {
110
113
  stdout: typeof result.stdout === "string" ? result.stdout : "",
111
114
  exitCode: typeof result.status === "number" ? result.status : 1,
@@ -161,7 +164,7 @@ export function defaultGitInvoker(): GitInvoker {
161
164
  child.stdout?.on("data", (chunk: string | Buffer) => {
162
165
  stdout += chunk.toString();
163
166
  });
164
- child.once("error", () => finish({ stdout: "", exitCode: 127 }));
167
+ child.once("error", () => finish({ stdout: "", exitCode: GIT_SPAWN_ERROR_EXIT_CODE }));
165
168
  child.once("close", (exitCode: number | null) => {
166
169
  finish({ stdout, exitCode: typeof exitCode === "number" ? exitCode : 1 });
167
170
  });
@@ -173,7 +176,7 @@ export function defaultGitInvoker(): GitInvoker {
173
176
  );
174
177
  timer = setTimeout(() => {
175
178
  child.kill("SIGTERM");
176
- finish({ stdout: "", exitCode: 124 });
179
+ finish({ stdout: "", exitCode: GIT_TIMEOUT_EXIT_CODE });
177
180
  }, timeoutMs);
178
181
  if (options.abortSignal?.aborted) onAbort();
179
182
  return promise;
@@ -320,6 +323,55 @@ export interface ResolveGitContextOptions {
320
323
  deadlineMs?: number;
321
324
  /** Injectable clock for deadline tests. */
322
325
  now?: () => number;
326
+ /**
327
+ * Share results across calls. Each miss costs up to five `git` spawns on the
328
+ * event loop, so per-request callers (recall, memory_store) pass one.
329
+ */
330
+ cache?: GitContextCache;
331
+ }
332
+
333
+ /** Short-lived, bounded memo of git resolution per cwd (COS-666). */
334
+ export class GitContextCache {
335
+ private readonly entries = new Map<string, { value: GitContext | null; head?: string; at: number }>();
336
+ private readonly ttlMs: number;
337
+ private readonly maxEntries: number;
338
+ private readonly now: () => number;
339
+
340
+ private readonly cacheRepos: boolean;
341
+
342
+ constructor(options: { ttlMs?: number; maxEntries?: number; now?: () => number; cacheRepos?: boolean } = {}) {
343
+ this.cacheRepos = options.cacheRepos ?? true;
344
+ this.ttlMs = options.ttlMs ?? 30_000;
345
+ this.maxEntries = options.maxEntries ?? 256;
346
+ this.now = options.now ?? Date.now;
347
+ }
348
+
349
+ has(key: string): boolean {
350
+ return this.get(key) !== undefined;
351
+ }
352
+
353
+ /** `undefined` = miss; `value: null` = cached "not a repo". */
354
+ get(key: string): { value: GitContext | null; head?: string } | undefined {
355
+ const hit = this.entries.get(key);
356
+ if (!hit) return undefined;
357
+ if (this.now() - hit.at >= this.ttlMs) {
358
+ this.entries.delete(key);
359
+ return undefined;
360
+ }
361
+ return hit;
362
+ }
363
+
364
+ set(key: string, value: GitContext | null, head?: string): void {
365
+ // Negative-only caches never hold a branch, so a session snapshot taken
366
+ // from them cannot carry a stale one.
367
+ if (value !== null && !this.cacheRepos) return;
368
+ this.entries.delete(key);
369
+ this.entries.set(key, { value, head, at: this.now() });
370
+ if (this.entries.size > this.maxEntries) {
371
+ const oldest = this.entries.keys().next();
372
+ if (!oldest.done) this.entries.delete(oldest.value);
373
+ }
374
+ }
323
375
  }
324
376
 
325
377
  /**
@@ -334,6 +386,82 @@ export interface ResolveGitContextOptions {
334
386
  export async function resolveGitContext(
335
387
  cwd: string,
336
388
  options: ResolveGitContextOptions = {},
389
+ ): Promise<GitContext | null> {
390
+ const { cache } = options;
391
+ if (!cache) return resolveGitContextUncached(cwd, options);
392
+ // A cache hit must not mask cancellation or an exhausted deadline.
393
+ throwIfInterrupted(options);
394
+ const hit = cache.get(cwd);
395
+ if (hit?.value === null) return null;
396
+ // The branch picks the write/recall namespace and git alone decides it, so a
397
+ // hit is served only while HEAD is byte-identical to what git answered for.
398
+ if (hit?.value && hit.head !== undefined && (await readHeadFile(hit.value.rootPath)) === hit.head) {
399
+ return { ...hit.value };
400
+ }
401
+ // Timeouts and spawn failures are not answers about the repo, so a lookup
402
+ // that hit one (even partially) is never cached.
403
+ let inconclusive = false;
404
+ // HEAD is snapshotted once git names the root and BEFORE the branch probe: a
405
+ // checkout racing the probe then leaves the entry older than HEAD, so the
406
+ // next hit mismatches and re-resolves (never a stale branch pinned to a new HEAD).
407
+ let head: string | undefined;
408
+ const inner = options.invoker ?? defaultGitInvoker();
409
+ const invoker: GitInvoker = async (probeCwd, args, invokeOptions) => {
410
+ let result: GitInvokeResult;
411
+ try {
412
+ result = await inner(probeCwd, args, invokeOptions);
413
+ } catch (err) {
414
+ inconclusive = true;
415
+ throw err;
416
+ }
417
+ if (result.exitCode === GIT_TIMEOUT_EXIT_CODE || result.exitCode === GIT_SPAWN_ERROR_EXIT_CODE) inconclusive = true;
418
+ if (args[1] === "--show-toplevel" && result.exitCode === 0) head = await readHeadFile(result.stdout.trim());
419
+ return result;
420
+ };
421
+ const value = await resolveGitContextUncached(cwd, { ...options, invoker });
422
+ if (inconclusive || options.abortSignal?.aborted) return value;
423
+ if (value === null || head !== undefined) cache.set(cwd, value && { ...value }, head);
424
+ return value;
425
+ }
426
+
427
+ /**
428
+ * Raw `HEAD` contents without spawning git, or `undefined` when they cannot
429
+ * vouch for the branch: unreadable, a symlinked HEAD (old
430
+ * `core.preferSymlinkRefs`), or reftable's constant `refs/heads/.invalid`
431
+ * placeholder (HEAD never changes on checkout there). Callers then re-resolve.
432
+ */
433
+ async function readHeadFile(rootPath: string): Promise<string | undefined> {
434
+ try {
435
+ let gitDir = path.join(rootPath, ".git");
436
+ if ((await stat(gitDir)).isFile()) {
437
+ // Linked worktree: `.git` is a file pointing at the real git dir.
438
+ const pointer = /^gitdir:\s*(.+)$/m.exec(await readFile(gitDir, "utf-8"));
439
+ if (!pointer?.[1]) return undefined;
440
+ gitDir = path.resolve(rootPath, pointer[1].trim());
441
+ }
442
+ const headPath = path.join(gitDir, "HEAD");
443
+ if ((await lstat(headPath)).isSymbolicLink()) return undefined;
444
+ const head = await readFile(headPath, "utf-8");
445
+ return head.includes("refs/heads/.invalid") ? undefined : head;
446
+ } catch {
447
+ return undefined;
448
+ }
449
+ }
450
+
451
+ function throwIfInterrupted(options: ResolveGitContextOptions): void {
452
+ if (options.abortSignal?.aborted) {
453
+ throw options.abortSignal.reason instanceof Error
454
+ ? options.abortSignal.reason
455
+ : abortError("git context resolution aborted");
456
+ }
457
+ if (options.deadlineMs !== undefined && (options.now ?? Date.now)() >= options.deadlineMs) {
458
+ throw abortError("git context resolution deadline exceeded");
459
+ }
460
+ }
461
+
462
+ async function resolveGitContextUncached(
463
+ cwd: string,
464
+ options: ResolveGitContextOptions,
337
465
  ): Promise<GitContext | null> {
338
466
  // Wrap the whole body so the documented "Never throws" contract is
339
467
  // enforced. Possible throw sites include:
@@ -436,3 +564,12 @@ export async function resolveGitContext(
436
564
  return null;
437
565
  }
438
566
  }
567
+
568
+ /** Process-wide cache for per-request callers (recall scope). */
569
+ export const sharedGitContextCache = new GitContextCache();
570
+
571
+ /**
572
+ * Session-attach callers snapshot the branch once per session, so they must
573
+ * read a repo fresh; they only skip repeat probes of non-repo directories.
574
+ */
575
+ export const sharedNonRepoGitContextCache = new GitContextCache({ cacheRepos: false });