@apralabs/apra-fleet 0.4.4 → 0.4.5

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 (268) hide show
  1. package/README.md +49 -4
  2. package/dist/agents/backlog-groomer.md +5 -0
  3. package/dist/agents/ci-watcher.md +5 -0
  4. package/dist/agents/deployer.md +20 -2
  5. package/dist/agents/doer.md +38 -2
  6. package/dist/agents/harvester.md +12 -9
  7. package/dist/agents/integ-test-runner.md +5 -0
  8. package/dist/agents/kb-reconciler.md +6 -0
  9. package/dist/agents/plan-reviewer.md +5 -0
  10. package/dist/agents/planner.md +5 -0
  11. package/dist/agents/regression-test-runner.md +5 -0
  12. package/dist/agents/reviewer.md +67 -15
  13. package/dist/agents/schemas/deployer-output.json +5 -0
  14. package/dist/agents/schemas/doer-output.json +78 -2
  15. package/dist/agents/schemas/reviewer-output.json +104 -2
  16. package/dist/cli/auth.js +5 -1
  17. package/dist/cli/beads-pin.js +6 -7
  18. package/dist/cli/claude-mod.d.ts +75 -0
  19. package/dist/cli/claude-mod.js +288 -0
  20. package/dist/cli/dolt-install.d.ts +1 -1
  21. package/dist/cli/dolt-install.js +5 -1
  22. package/dist/cli/fleet-se-guard.d.ts +8 -0
  23. package/dist/cli/fleet-se-guard.js +19 -3
  24. package/dist/cli/install-guard.d.ts +9 -0
  25. package/dist/cli/install-guard.js +24 -0
  26. package/dist/cli/install.d.ts +12 -0
  27. package/dist/cli/install.js +180 -20
  28. package/dist/cli/kb-profile.d.ts +16 -0
  29. package/dist/cli/kb-profile.js +81 -0
  30. package/dist/cli/start.js +3 -0
  31. package/dist/cli/uninstall.js +13 -3
  32. package/dist/cli/update.d.ts +4 -0
  33. package/dist/cli/update.js +19 -3
  34. package/dist/commands/kb-server.d.ts +10 -1
  35. package/dist/commands/kb-server.js +285 -11
  36. package/dist/index.js +22 -1
  37. package/dist/os/git-executable.d.ts +57 -0
  38. package/dist/os/git-executable.js +85 -0
  39. package/dist/os/go-concurrency.d.ts +44 -0
  40. package/dist/os/go-concurrency.js +53 -0
  41. package/dist/os/index.d.ts +1 -0
  42. package/dist/os/index.js +1 -0
  43. package/dist/os/linux.d.ts +2 -0
  44. package/dist/os/linux.js +10 -1
  45. package/dist/os/os-commands.d.ts +25 -0
  46. package/dist/os/os-commands.js +2 -0
  47. package/dist/os/windows-executable.d.ts +53 -0
  48. package/dist/os/windows-executable.js +185 -0
  49. package/dist/os/windows-gitbash.d.ts +23 -14
  50. package/dist/os/windows-gitbash.js +40 -16
  51. package/dist/os/windows.d.ts +2 -0
  52. package/dist/os/windows.js +37 -6
  53. package/dist/paths.d.ts +10 -1
  54. package/dist/paths.js +19 -2
  55. package/dist/services/agy-project.d.ts +7 -1
  56. package/dist/services/agy-project.js +7 -2
  57. package/dist/services/auth-socket.d.ts +18 -0
  58. package/dist/services/auth-socket.js +30 -4
  59. package/dist/services/credential-store.d.ts +33 -0
  60. package/dist/services/credential-store.js +79 -2
  61. package/dist/services/http-transport.d.ts +29 -0
  62. package/dist/services/http-transport.js +166 -37
  63. package/dist/services/kb-tool-profile.d.ts +36 -0
  64. package/dist/services/kb-tool-profile.js +88 -0
  65. package/dist/services/knowledge/bible-blob-id.js +10 -1
  66. package/dist/services/knowledge/bible-import.d.ts +108 -0
  67. package/dist/services/knowledge/bible-import.js +137 -4
  68. package/dist/services/knowledge/file-hash.js +6 -5
  69. package/dist/services/knowledge/http-provider.d.ts +303 -20
  70. package/dist/services/knowledge/http-provider.js +795 -125
  71. package/dist/services/knowledge/kb-config.d.ts +65 -1
  72. package/dist/services/knowledge/kb-config.js +143 -3
  73. package/dist/services/knowledge/kb-http-auth-state.d.ts +26 -0
  74. package/dist/services/knowledge/kb-http-auth-state.js +40 -0
  75. package/dist/services/knowledge/kb-providers.d.ts +9 -2
  76. package/dist/services/knowledge/kb-providers.js +67 -37
  77. package/dist/services/knowledge/kb-removed-scope-keys.js +1 -1
  78. package/dist/services/knowledge/kb-self.d.ts +122 -9
  79. package/dist/services/knowledge/kb-self.js +196 -36
  80. package/dist/services/knowledge/member-bible-view.js +16 -3
  81. package/dist/services/knowledge/path-validation.d.ts +7 -0
  82. package/dist/services/knowledge/path-validation.js +11 -0
  83. package/dist/services/knowledge/project-slug.js +3 -2
  84. package/dist/services/knowledge/repository-header.d.ts +77 -0
  85. package/dist/services/knowledge/repository-header.js +233 -0
  86. package/dist/services/knowledge/require-sqlite-project.d.ts +1 -1
  87. package/dist/services/knowledge/require-sqlite-project.js +1 -1
  88. package/dist/services/knowledge/sqlite-provider.d.ts +169 -0
  89. package/dist/services/knowledge/sqlite-provider.js +416 -4
  90. package/dist/services/knowledge/types.d.ts +15 -2
  91. package/dist/services/member-busy.d.ts +12 -0
  92. package/dist/services/member-busy.js +20 -0
  93. package/dist/services/member-config-io.d.ts +3 -2
  94. package/dist/services/member-config-io.js +7 -4
  95. package/dist/services/member-fleet-install.js +1 -0
  96. package/dist/services/member-tool-allowlist.d.ts +1 -1
  97. package/dist/services/member-tool-allowlist.js +8 -4
  98. package/dist/services/port-holder.js +2 -1
  99. package/dist/services/service-manager/types.d.ts +17 -1
  100. package/dist/services/service-manager/windows.d.ts +7 -2
  101. package/dist/services/service-manager/windows.js +28 -11
  102. package/dist/services/service-notice.d.ts +7 -0
  103. package/dist/services/service-notice.js +19 -0
  104. package/dist/services/session-registry.d.ts +13 -0
  105. package/dist/services/session-registry.js +13 -0
  106. package/dist/services/session-roots.d.ts +67 -0
  107. package/dist/services/session-roots.js +126 -0
  108. package/dist/services/statusline.d.ts +21 -0
  109. package/dist/services/statusline.js +97 -1
  110. package/dist/services/supervisor-service-cleanup.js +2 -1
  111. package/dist/services/tool-registry.js +108 -20
  112. package/dist/services/tool-scope.d.ts +34 -1
  113. package/dist/services/tool-scope.js +27 -2
  114. package/dist/services/vcs/azure-devops.js +10 -0
  115. package/dist/services/vcs/bitbucket.d.ts +22 -1
  116. package/dist/services/vcs/bitbucket.js +163 -17
  117. package/dist/services/vcs/types.d.ts +25 -2
  118. package/dist/services/watch/project-resolver.js +2 -1
  119. package/dist/skills/pm/cost.md +5 -1
  120. package/dist/skills/pm/index.md +9 -9
  121. package/dist/skills/pm/sprint.md +2 -1
  122. package/dist/tools/check-status.d.ts +51 -0
  123. package/dist/tools/check-status.js +124 -12
  124. package/dist/tools/code-intelligence-freshness.js +1 -1
  125. package/dist/tools/code-intelligence-gitnexus.d.ts +19 -0
  126. package/dist/tools/code-intelligence-gitnexus.js +166 -9
  127. package/dist/tools/code-intelligence-readiness.d.ts +58 -1
  128. package/dist/tools/code-intelligence-readiness.js +93 -8
  129. package/dist/tools/code-intelligence-reindex.d.ts +25 -1
  130. package/dist/tools/code-intelligence-reindex.js +76 -4
  131. package/dist/tools/code-intelligence.d.ts +1 -1
  132. package/dist/tools/code-intelligence.js +1 -1
  133. package/dist/tools/execute-command.js +14 -8
  134. package/dist/tools/execute-prompt.js +6 -2
  135. package/dist/tools/fleet-snapshot.d.ts +21 -0
  136. package/dist/tools/fleet-snapshot.js +78 -0
  137. package/dist/tools/kb-bible-commit.d.ts +25 -11
  138. package/dist/tools/kb-bible-commit.js +142 -33
  139. package/dist/tools/kb-capture.d.ts +2 -2
  140. package/dist/tools/kb-context.js +47 -27
  141. package/dist/tools/kb-demote.d.ts +27 -0
  142. package/dist/tools/kb-demote.js +37 -0
  143. package/dist/tools/kb-export.d.ts +35 -3
  144. package/dist/tools/kb-export.js +56 -13
  145. package/dist/tools/kb-feedback.d.ts +2 -0
  146. package/dist/tools/kb-feedback.js +17 -7
  147. package/dist/tools/kb-harvest.js +28 -9
  148. package/dist/tools/kb-import.d.ts +18 -2
  149. package/dist/tools/kb-import.js +24 -9
  150. package/dist/tools/kb-invalidate.d.ts +11 -3
  151. package/dist/tools/kb-invalidate.js +80 -7
  152. package/dist/tools/kb-list.js +38 -10
  153. package/dist/tools/kb-promote.js +6 -4
  154. package/dist/tools/kb-query.d.ts +3 -0
  155. package/dist/tools/kb-query.js +181 -37
  156. package/dist/tools/kb-session-prime.d.ts +4 -4
  157. package/dist/tools/kb-session-prime.js +89 -9
  158. package/dist/tools/kb-setup.d.ts +20 -0
  159. package/dist/tools/kb-setup.js +149 -11
  160. package/dist/tools/list-members.js +1 -1
  161. package/dist/tools/member-detail.js +7 -3
  162. package/dist/tools/provision-vcs-auth.d.ts +28 -3
  163. package/dist/tools/provision-vcs-auth.js +53 -7
  164. package/dist/tools/receive-files.js +7 -4
  165. package/dist/tools/send-files.js +5 -4
  166. package/dist/tools/send-message.d.ts +3 -0
  167. package/dist/tools/send-message.js +15 -2
  168. package/dist/tools/stop-prompt.js +3 -1
  169. package/dist/tools/vcs-credential-exec.d.ts +45 -3
  170. package/dist/tools/vcs-credential-exec.js +90 -11
  171. package/dist/utils/process-utils.js +5 -1
  172. package/dist/utils/redact-known-secrets.d.ts +17 -0
  173. package/dist/utils/redact-known-secrets.js +70 -0
  174. package/dist/utils/skill-matrix.js +1 -1
  175. package/dist/utils/vcs-provider-detect.js +2 -2
  176. package/dist/workflows/auto-sprint.js +245 -9
  177. package/package.json +10 -7
  178. package/packages/apra-fleet-client/package.json +1 -1
  179. package/packages/apra-fleet-client/src/client/api.mjs +172 -19
  180. package/packages/apra-fleet-client/src/client/reconnecting-transport.mjs +35 -2
  181. package/packages/apra-fleet-client/src/client/transport.mjs +6 -0
  182. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +5 -0
  183. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +5 -0
  184. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +20 -2
  185. package/packages/apra-fleet-se/apra-pm/agents/doer.md +38 -2
  186. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +12 -9
  187. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +5 -0
  188. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +6 -0
  189. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +5 -0
  190. package/packages/apra-fleet-se/apra-pm/agents/planner.md +5 -0
  191. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +5 -0
  192. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +67 -15
  193. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +5 -0
  194. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +78 -2
  195. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +104 -2
  196. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +5 -1
  197. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +9 -9
  198. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +2 -1
  199. package/packages/apra-fleet-se/bin/cli.mjs +104 -31
  200. package/packages/apra-fleet-se/bin/serve.mjs +46 -8
  201. package/packages/apra-fleet-se/fleet-sprint/abort.mjs +184 -32
  202. package/packages/apra-fleet-se/fleet-sprint/bd-sync-command.mjs +69 -0
  203. package/packages/apra-fleet-se/fleet-sprint/beads-children.mjs +21 -0
  204. package/packages/apra-fleet-se/fleet-sprint/beads-lock-probe.mjs +176 -0
  205. package/packages/apra-fleet-se/fleet-sprint/beads-reachability.mjs +126 -0
  206. package/packages/apra-fleet-se/fleet-sprint/beads-scope.mjs +158 -1
  207. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +82 -2
  208. package/packages/apra-fleet-se/fleet-sprint/coordination.mjs +23 -6
  209. package/packages/apra-fleet-se/fleet-sprint/decision-notify.mjs +338 -0
  210. package/packages/apra-fleet-se/fleet-sprint/decision-wait.mjs +731 -0
  211. package/packages/apra-fleet-se/fleet-sprint/decisions.mjs +372 -0
  212. package/packages/apra-fleet-se/fleet-sprint/dispatch-role.mjs +44 -11
  213. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +4 -1
  214. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +9 -3
  215. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +314 -19
  216. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +72 -4
  217. package/packages/apra-fleet-se/fleet-sprint/git-sync.mjs +7 -1
  218. package/packages/apra-fleet-se/fleet-sprint/git-topology.mjs +112 -1
  219. package/packages/apra-fleet-se/fleet-sprint/guarded-modules.mjs +36 -2
  220. package/packages/apra-fleet-se/fleet-sprint/kb.mjs +736 -101
  221. package/packages/apra-fleet-se/fleet-sprint/member-init-probe.mjs +1 -1
  222. package/packages/apra-fleet-se/fleet-sprint/member-provisioning.mjs +7 -1
  223. package/packages/apra-fleet-se/fleet-sprint/phases/deploy.mjs +49 -2
  224. package/packages/apra-fleet-se/fleet-sprint/phases/develop.mjs +206 -3
  225. package/packages/apra-fleet-se/fleet-sprint/phases/final-review.mjs +61 -3
  226. package/packages/apra-fleet-se/fleet-sprint/phases/harvest.mjs +81 -31
  227. package/packages/apra-fleet-se/fleet-sprint/phases/plan.mjs +7 -3
  228. package/packages/apra-fleet-se/fleet-sprint/phases/publish-pr.mjs +39 -14
  229. package/packages/apra-fleet-se/fleet-sprint/phases/re-review.mjs +17 -1
  230. package/packages/apra-fleet-se/fleet-sprint/phases/review.mjs +18 -3
  231. package/packages/apra-fleet-se/fleet-sprint/pr-body.mjs +14 -1
  232. package/packages/apra-fleet-se/fleet-sprint/prompts.mjs +32 -5
  233. package/packages/apra-fleet-se/fleet-sprint/runner.js +824 -98
  234. package/packages/apra-fleet-se/fleet-sprint/se-os-commands.mjs +4 -2
  235. package/packages/apra-fleet-se/fleet-sprint/se-posix.mjs +54 -1
  236. package/packages/apra-fleet-se/fleet-sprint/se-windows.mjs +29 -2
  237. package/packages/apra-fleet-se/fleet-sprint/set-aside.mjs +288 -0
  238. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +3 -2
  239. package/packages/apra-fleet-se/fleet-sprint/sprint-args.mjs +20 -0
  240. package/packages/apra-fleet-se/fleet-sprint/sprint-report.mjs +21 -0
  241. package/packages/apra-fleet-se/fleet-sprint/sprint-state.mjs +9 -0
  242. package/packages/apra-fleet-se/fleet-sprint/vcs-auth.mjs +605 -32
  243. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +811 -17
  244. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +89 -1
  245. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +225 -2
  246. package/packages/apra-fleet-se/fleet-sprint/worklists.mjs +59 -3
  247. package/packages/apra-fleet-se/src/supervisor/api.mjs +148 -8
  248. package/packages/apra-fleet-se/src/supervisor/dashboard.mjs +6 -3
  249. package/packages/apra-fleet-se/src/supervisor/dolt-mutex.mjs +30 -10
  250. package/packages/apra-fleet-se/src/supervisor/fleet-members.mjs +17 -4
  251. package/packages/apra-fleet-se/src/supervisor/history.mjs +8 -1
  252. package/packages/apra-fleet-se/src/supervisor/id-allocator.mjs +92 -2
  253. package/packages/apra-fleet-se/src/supervisor/proxy.mjs +26 -1
  254. package/packages/apra-fleet-se/src/supervisor/server.mjs +151 -8
  255. package/packages/apra-fleet-se/src/supervisor/spawner.mjs +11 -9
  256. package/packages/apra-fleet-se/src/supervisor/watchdog.mjs +7 -1
  257. package/packages/apra-fleet-workflow/package.json +2 -1
  258. package/packages/apra-fleet-workflow/src/viewer/index.mjs +86 -5
  259. package/packages/apra-fleet-workflow/src/viewer/request-guard.mjs +222 -0
  260. package/packages/apra-fleet-workflow/src/workflow/index.mjs +34 -2
  261. package/plugins/claude-code/fleet-status/.claude-plugin/plugin.json +7 -0
  262. package/plugins/claude-code/fleet-status/hooks/hooks.json +1 -0
  263. package/plugins/claude-code/fleet-status/hooks/register.tsx +906 -0
  264. package/plugins/claude-code/fleet-status/types/index.d.ts +88 -0
  265. package/skills/fleet/auth-bitbucket.md +47 -20
  266. package/skills/fleet/onboarding.md +1 -1
  267. package/skills/fleet/skill-matrix.md +3 -3
  268. package/version.json +1 -1
@@ -9,6 +9,8 @@ import { logWarn } from '../utils/log-helpers.js';
9
9
  import { requireSqliteProject } from '../services/knowledge/require-sqlite-project.js';
10
10
  import { KB_CONFIG_PATH } from '../services/knowledge/kb-config.js';
11
11
  import { filterProjectBibleCandidates } from '../services/knowledge/bible-basis-filter.js';
12
+ import { extractBibleDemotions, standingAgainstTombstone } from '../services/knowledge/bible-import.js';
13
+ import { gitExecutable } from '../os/git-executable.js';
12
14
  // T3.4 (F8b, D8): export half of the shareable, diffable team bible. Writes
13
15
  // all CONFIRMED, non-superseded, non-stale project entries to
14
16
  // <repo>/.fleet/kb-canonical.json. Registered as a real MCP tool (not just an
@@ -71,7 +73,13 @@ export function withSourceFileHashes(entry, basis) {
71
73
  * predicate admitted it against); when given and non-empty it is written as
72
74
  * source_file_hashes (format v3). Nothing is hashed here.
73
75
  */
74
- export function toCanonicalEntry(e, basis) {
76
+ /**
77
+ * `trustTime` is the row's bible trust time (SqliteProvider.getBibleTrustTimes)
78
+ * when the caller has it, so an entry this clone imported keeps the updated_at
79
+ * its bible carried instead of taking the local import time. null/undefined
80
+ * falls back to promoted_at, then created_at.
81
+ */
82
+ export function toCanonicalEntry(e, basis, trustTime) {
75
83
  const entry = {
76
84
  id: e.id,
77
85
  type: e.type,
@@ -80,7 +88,7 @@ export function toCanonicalEntry(e, basis) {
80
88
  symbols: e.symbols,
81
89
  source_files: e.source_files,
82
90
  confidence: e.confidence,
83
- updated_at: e.promoted_at || e.created_at,
91
+ updated_at: trustTime || e.promoted_at || e.created_at,
84
92
  };
85
93
  if (basis && Object.keys(basis).length > 0)
86
94
  entry.source_file_hashes = sortedBasis(basis);
@@ -109,8 +117,20 @@ export function compareById(a, b) {
109
117
  /**
110
118
  * The entries of the bible already on disk, in either shape (legacy bare array
111
119
  * or v2/v3 envelope). null when the file is absent or unparseable.
120
+ *
121
+ * Entries only, exactly as before: callers that do not care about tombstones are
122
+ * unchanged. readBibleDocument below is the sibling reader for callers that do.
112
123
  */
113
124
  export function readBibleEntries(outPath) {
125
+ return readBibleDocument(outPath)?.entries ?? null;
126
+ }
127
+ /**
128
+ * The entries AND the demotion tombstones of the bible already on disk. Same
129
+ * acceptance as readBibleEntries (both shapes; null when absent or unparseable);
130
+ * a bible with no demotions field yields an empty tombstone list, never a
131
+ * failure.
132
+ */
133
+ export function readBibleDocument(outPath) {
114
134
  if (!fs.existsSync(outPath))
115
135
  return null;
116
136
  try {
@@ -118,7 +138,9 @@ export function readBibleEntries(outPath) {
118
138
  const existing = Array.isArray(parsed)
119
139
  ? parsed
120
140
  : (parsed && Array.isArray(parsed.entries) ? parsed.entries : null);
121
- return existing;
141
+ if (existing === null)
142
+ return null;
143
+ return { entries: existing, demotions: extractBibleDemotions(parsed) };
122
144
  }
123
145
  catch {
124
146
  return null;
@@ -131,10 +153,10 @@ export function readBibleEntries(outPath) {
131
153
  * caller decides whether that is fatal. Never pushes.
132
154
  */
133
155
  export function commitBiblePath(repoPath, outPath, message) {
134
- execFileSync('git', ['add', outPath], {
156
+ execFileSync(gitExecutable(), ['add', outPath], {
135
157
  cwd: repoPath, timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
136
158
  });
137
- execFileSync('git', ['-c', 'user.name=pm-kb', '-c', 'user.email=kb@pm.local', 'commit', '-m', message, '--', outPath], { cwd: repoPath, timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
159
+ execFileSync(gitExecutable(), ['-c', 'user.name=pm-kb', '-c', 'user.email=kb@pm.local', 'commit', '-m', message, '--', outPath], { cwd: repoPath, timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
138
160
  }
139
161
  /**
140
162
  * Resolve HEAD, degrading gracefully to null rather than throwing: a repo with
@@ -174,7 +196,7 @@ function gitOrNull(repoPath, args) {
174
196
  if (!isGitRepo(repoPath))
175
197
  return null;
176
198
  try {
177
- const out = execFileSync('git', args, {
199
+ const out = execFileSync(gitExecutable(), args, {
178
200
  cwd: repoPath, encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
179
201
  }).trim();
180
202
  return out.length > 0 ? out : null;
@@ -274,7 +296,7 @@ export function isGitRepo(repoPath) {
274
296
  // is a no-op, so there is nothing to commit. Any output (modified, or a
275
297
  // brand-new untracked file on the very first export) means it changed.
276
298
  export function bibleContentChanged(repoPath, outPath) {
277
- const status = execFileSync('git', ['status', '--porcelain', '--', outPath], {
299
+ const status = execFileSync(gitExecutable(), ['status', '--porcelain', '--', outPath], {
278
300
  cwd: repoPath, encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
279
301
  });
280
302
  return status.trim().length > 0;
@@ -341,9 +363,9 @@ function byId(a, b) {
341
363
  * but cannot be parsed as either shape THROWS: the project export is additive
342
364
  * and must never overwrite (and so silently drop) a bible it cannot read.
343
365
  */
344
- function readExistingBibleEntries(outPath) {
366
+ function readExistingBibleDocument(outPath) {
345
367
  if (!fs.existsSync(outPath))
346
- return [];
368
+ return { entries: [], demotions: [] };
347
369
  let parsed;
348
370
  try {
349
371
  parsed = JSON.parse(fs.readFileSync(outPath, 'utf-8'));
@@ -360,7 +382,7 @@ function readExistingBibleEntries(outPath) {
360
382
  if (list === null) {
361
383
  throw new Error('kb_export: existing bible has no entries array, refusing to overwrite it: ' + outPath);
362
384
  }
363
- return list;
385
+ return { entries: list, demotions: extractBibleDemotions(parsed) };
364
386
  }
365
387
  // PROJECT-SCOPE EXPORT: basis filter + additive merge.
366
388
  //
@@ -383,26 +405,47 @@ function readExistingBibleEntries(outPath) {
383
405
  // `exported` in the response is the number of entries in the bible as written
384
406
  // (or as left on disk when nothing was added), not the number newly added.
385
407
  async function exportProjectBible(source, repoPath, outPath, input) {
386
- const existing = readExistingBibleEntries(outPath);
408
+ const { entries: existing, demotions } = readExistingBibleDocument(outPath);
387
409
  const existingIds = new Set(existing.map(e => String(e.id)));
410
+ const tombstones = new Map(demotions.map(d => [d.id, d]));
388
411
  const confirmed = await source.list({ confidence: ['CONFIRMED'] });
389
- const newCandidates = confirmed.filter(e => !existingIds.has(e.id));
412
+ // TOMBSTONE GATE, before the basis filter. An id another clone demoted is not
413
+ // re-added just because this clone still holds it CONFIRMED -- that is how a
414
+ // demotion would be silently undone on the next export. The ONE exception is a
415
+ // row standingAgainstTombstone calls 'repromoted' -- the same rule kb_import
416
+ // applies -- so the entry comes back and its tombstone is cleared in the same
417
+ // write.
418
+ const notInBible = confirmed.filter(e => !existingIds.has(e.id));
419
+ const trustTimes = source.getBibleTrustTimes(notInBible.map(e => e.id));
420
+ const newCandidates = notInBible.filter(e => {
421
+ const tombstone = tombstones.get(e.id);
422
+ if (!tombstone)
423
+ return true;
424
+ return standingAgainstTombstone(trustTimes.get(e.id) ?? null, tombstone.at) === 'repromoted';
425
+ });
390
426
  const bases = source.getSourceFileBases(newCandidates.map(e => e.id));
391
427
  const qualifying = await filterProjectBibleCandidates(newCandidates, bases, repoPath);
392
428
  if (qualifying.length === 0) {
393
429
  return JSON.stringify({ exported: existing.length, path: outPath, scope: 'project', committed: false });
394
430
  }
431
+ for (const e of qualifying)
432
+ tombstones.delete(e.id);
395
433
  // Each added entry carries the exact stored basis it was just admitted against.
396
- const merged = [...existing, ...qualifying.map(e => toCanonicalEntry(e, bases.get(e.id)))].sort(byId);
434
+ const merged = [...existing, ...qualifying.map(e => toCanonicalEntry(e, bases.get(e.id), trustTimes.get(e.id)))].sort(byId);
397
435
  assertNoDuplicateBibleIds(merged, 'kb_export');
436
+ const nextDemotions = Array.from(tombstones.values()).sort(compareById);
398
437
  const bible = {
399
438
  version: BIBLE_FORMAT_VERSION,
400
439
  provenance: {
401
440
  commit: input.baseCommit ?? resolveHeadCommit(repoPath),
402
441
  branch: input.baseBranch ?? resolveBranch(repoPath),
442
+ // Entries only: the tombstones below are deliberately not counted.
403
443
  entry_count: merged.length,
404
444
  },
405
445
  entries: merged,
446
+ // Omitted entirely when there are none, so a bible that never saw a
447
+ // demotion is byte-identical to one written before the field existed.
448
+ ...(nextDemotions.length > 0 ? { demotions: nextDemotions } : {}),
406
449
  };
407
450
  const fleetDir = path.dirname(outPath);
408
451
  if (!fs.existsSync(fleetDir))
@@ -1,5 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { type KbAnchor } from '../services/knowledge/kb-self.js';
3
+ import type { Author } from '../services/knowledge/types.js';
4
+ export declare function validateAuthor(role: string | undefined): Author | 'unknown';
3
5
  export declare const kbFeedbackSchema: z.ZodObject<{
4
6
  repo_path: z.ZodOptional<z.ZodUnknown>;
5
7
  repo: z.ZodOptional<z.ZodUnknown>;
@@ -2,13 +2,14 @@ import { z } from 'zod';
2
2
  import { KB_REMOVED_SCOPE_KEYS_SHAPE } from '../services/knowledge/kb-removed-scope-keys.js';
3
3
  import { getSelfKbProviders, memberOwnerTag } from '../services/knowledge/kb-self.js';
4
4
  import { KbMemberViewError } from '../services/knowledge/member-bible-view.js';
5
- import { requireSqliteProject } from '../services/knowledge/require-sqlite-project.js';
5
+ import { isSqliteProject } from '../services/knowledge/require-sqlite-project.js';
6
+ import { HttpKbProvider } from '../services/knowledge/http-provider.js';
6
7
  // D5 (T2.3) pattern, DUPLICATED here rather than imported: src/tools/kb-capture.ts
7
8
  // is touched ONLY by T1.1 per PLAN.md's shared-file sequencing, so this tool
8
9
  // validates its own role hint against the same Author enum instead of
9
10
  // exporting a shared helper out of a file this task must not modify.
10
11
  const AUTHOR_VALUES = ['doer', 'reviewer', 'planner', 'plan-reviewer', 'kb-agent', 'kb-reconciler', 'harvest', 'pm', 'user'];
11
- function validateAuthor(role) {
12
+ export function validateAuthor(role) {
12
13
  if (role && AUTHOR_VALUES.includes(role)) {
13
14
  return role;
14
15
  }
@@ -32,15 +33,24 @@ export const kbFeedbackSchema = z.object({
32
33
  // review only (never staled) because directives outrank agent experience and
33
34
  // the human decides -- see SqliteProvider.feedback() for the exact guard.
34
35
  export async function kbFeedback(input, anchor) {
35
- // A MEMBER session reads its checkout bible view, which is read-only: a
36
- // typed no-op that touches no store (checked before any provider is opened).
36
+ // A MEMBER session does not downvote entries in the shared KB, under either
37
+ // provider: a typed no-op that touches no store (checked before any provider
38
+ // is opened).
37
39
  if (memberOwnerTag(anchor) !== undefined) {
38
- throw new KbMemberViewError('E-MEMBER-VIEW-READ-ONLY', '', `kb_feedback is not available in a member session: member KB reads come from the checkout bible, which is read-only; entry '${input.id}' was not changed.`, 'Run kb_feedback from a FULL session (no member identity), or flag the entry for review through the maintainer.');
40
+ throw new KbMemberViewError('E-MEMBER-VIEW-READ-ONLY', '', `kb_feedback is not available in a member session: a member session does not flag entries in the shared KB (over SQLite its reads come from the read-only checkout bible; under an http KB provider the server's entries are shared by every member); entry '${input.id}' was not changed.`, 'Run kb_feedback from a FULL session (no member identity), or flag the entry for review through the maintainer.');
39
41
  }
40
42
  const providers = await getSelfKbProviders(anchor);
41
- const sqliteProvider = requireSqliteProject(providers.project, 'kb_feedback');
42
43
  const author = validateAuthor(input.role);
43
- const entry = await sqliteProvider.feedback(input.id, input.reason, author);
44
+ // An HTTP-backed KB: the remote server owns the entry and decides its
45
+ // stale/flagged state; its response is returned as is (an unreachable
46
+ // server is a thrown E-KB-HTTP-UNREACHABLE; nothing is queued). Confidence is never written or invented client-side.
47
+ if (providers.project instanceof HttpKbProvider) {
48
+ return JSON.stringify(await providers.project.feedback(input.id, input.reason, author));
49
+ }
50
+ if (!isSqliteProject(providers.project)) {
51
+ throw new Error('kb_feedback: this operation is not supported by the configured KB provider');
52
+ }
53
+ const entry = await providers.project.feedback(input.id, input.reason, author);
44
54
  return JSON.stringify({
45
55
  id: entry.id,
46
56
  stale: entry.stale,
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import { KB_REMOVED_SCOPE_KEYS_SHAPE } from '../services/knowledge/kb-removed-scope-keys.js';
3
3
  import { getSelfKbProviders } from '../services/knowledge/kb-self.js';
4
4
  import { KbCaptureRejected } from '../services/knowledge/types.js';
5
+ import { logWarn } from '../utils/log-helpers.js';
5
6
  export const kbHarvestSchema = z.object({
6
7
  session_transcript: z.string().optional()
7
8
  .describe('Full session transcript text to scan for learnings'),
@@ -16,6 +17,8 @@ const LEARNING_PATTERNS = [
16
17
  /(?:^|\n)\s*(?:The (?:issue|problem|fix|solution|root cause) (?:is|was))\s*[:\-]?\s*(.+?)(?:\n\n|\n(?=[A-Z])|$)/gis,
17
18
  /(?:^|\n)\s*(?:Important:|Key insight:|Lesson learned:|TIL:)\s*(.+?)(?:\n\n|\n(?=[A-Z])|$)/gis,
18
19
  ];
20
+ /** Longest first_error text carried into the kb_harvest response. */
21
+ const MAX_FIRST_ERROR_CHARS = 500;
19
22
  const FILE_PATH_RE = /(?:^|\s)((?:src|lib|tests?|docs?)\/[\w./-]+\.\w+)/g;
20
23
  const SYMBOL_RE = /`(\w{2,}(?:\.\w+)?(?:\(\))?)`/g;
21
24
  function extractFilePaths(text) {
@@ -82,7 +85,7 @@ function extractLearnings(transcript) {
82
85
  // author='harvest', source='harvest' so it is distinguishable in queries.
83
86
  export async function kbHarvest(input, anchor) {
84
87
  if (!input.session_transcript) {
85
- return JSON.stringify({ entries_captured: 0, entries_updated: 0, entries_skipped: 0, entries_rejected: 0 });
88
+ return JSON.stringify({ entries_captured: 0, entries_updated: 0, entries_skipped: 0, entries_rejected: 0, entries_failed: 0 });
86
89
  }
87
90
  const providers = await getSelfKbProviders(anchor);
88
91
  const provider = providers.project;
@@ -91,6 +94,11 @@ export async function kbHarvest(input, anchor) {
91
94
  let entries_updated = 0;
92
95
  let entries_skipped = 0;
93
96
  let entries_rejected = 0;
97
+ let entries_failed = 0;
98
+ // The first non-rejection failure, reported only when nothing landed, so a
99
+ // harvest whose every capture failed (a broken DB, a server that is down)
100
+ // says why instead of hiding it in the count.
101
+ let first_error;
94
102
  // D5 + revised D7 (T2.3): harvested entries are UNVERIFIED, regex-extracted,
95
103
  // low-trust captures from the execute_prompt autowire -- distinct provenance
96
104
  // from real KB-Agent captures (author='kb-agent', source='session'/'review').
@@ -111,12 +119,15 @@ export async function kbHarvest(input, anchor) {
111
119
  source,
112
120
  confidence: 'UNVERIFIED',
113
121
  };
114
- // KB-TRUST PHASE 1: capture now fails closed on an uncheckable basis, and
115
- // harvest is the highest-volume writer -- its regex extraction frequently
116
- // yields no file paths at all. Isolate each capture so one rejected entry
117
- // is counted and the loop continues; an unhandled throw here would abort
118
- // the remaining entries and die silently, because auto-harvest is
119
- // dispatched fire-and-forget with a bare .catch() in execute-prompt.ts.
122
+ // Isolate each capture so one failure never costs the learnings after
123
+ // it: an unhandled throw here would abort the remaining entries and die
124
+ // silently, because auto-harvest is dispatched fire-and-forget with a bare
125
+ // .catch() in execute-prompt.ts. A capture refused for its basis
126
+ // (KB-TRUST PHASE 1: harvest's regex extraction often yields no file
127
+ // paths) is counted as rejected. Any other failure -- e.g. a remote KB
128
+ // server that is down, where the http provider queues nothing -- is
129
+ // logged with the entry title and counted as failed, so the caller sees
130
+ // that the harvest must be repeated.
120
131
  let audn_decision;
121
132
  try {
122
133
  ({ audn_decision } = await provider.capture(entryInput));
@@ -126,7 +137,11 @@ export async function kbHarvest(input, anchor) {
126
137
  entries_rejected++;
127
138
  continue;
128
139
  }
129
- throw err;
140
+ entries_failed++;
141
+ const message = err instanceof Error ? err.message : String(err);
142
+ first_error ??= message.length > MAX_FIRST_ERROR_CHARS ? `${message.slice(0, MAX_FIRST_ERROR_CHARS)}...` : message;
143
+ logWarn('kb-harvest', `capture of "${entryInput.title}" failed and was not stored: ${message}`);
144
+ continue;
130
145
  }
131
146
  if (audn_decision === 'add' || audn_decision === 'flagged') {
132
147
  entries_captured++;
@@ -138,6 +153,10 @@ export async function kbHarvest(input, anchor) {
138
153
  entries_skipped++;
139
154
  }
140
155
  }
141
- return JSON.stringify({ entries_captured, entries_updated, entries_skipped, entries_rejected });
156
+ const landed = entries_captured + entries_updated + entries_skipped;
157
+ return JSON.stringify({
158
+ entries_captured, entries_updated, entries_skipped, entries_rejected, entries_failed,
159
+ ...(landed === 0 && first_error !== undefined ? { first_error } : {}),
160
+ });
142
161
  }
143
162
  //# sourceMappingURL=kb-harvest.js.map
@@ -10,16 +10,16 @@ export declare const kbImportSchema: z.ZodObject<{
10
10
  skip_sweep: z.ZodOptional<z.ZodBoolean>;
11
11
  }, "strip", z.ZodTypeAny, {
12
12
  path?: string | undefined;
13
- repo?: unknown;
14
13
  scope?: "project" | undefined;
14
+ repo?: unknown;
15
15
  repo_path?: unknown;
16
16
  repo_remote_url?: unknown;
17
17
  ref?: string | undefined;
18
18
  skip_sweep?: boolean | undefined;
19
19
  }, {
20
20
  path?: string | undefined;
21
- repo?: unknown;
22
21
  scope?: "project" | undefined;
22
+ repo?: unknown;
23
23
  repo_path?: unknown;
24
24
  repo_remote_url?: unknown;
25
25
  ref?: string | undefined;
@@ -38,6 +38,14 @@ export interface KbImportReport {
38
38
  * bible, so re-importing an old bible deliberately drops those entries.
39
39
  */
40
40
  rejected: number;
41
+ /**
42
+ * Local rows taken CONFIRMED -> INFERRED by an EXPLICIT demotion tombstone in
43
+ * the imported bible -- the cross-clone half of kb_demote. Counts rows
44
+ * actually changed, not tombstones read: a tombstone naming an id this clone
45
+ * does not hold, or one whose row was re-promoted after the demotion, adds
46
+ * nothing. An entry merely ABSENT from the bible is never demoted.
47
+ */
48
+ demoted: number;
41
49
  sweep: {
42
50
  checked: number;
43
51
  staled: number;
@@ -55,6 +63,14 @@ export interface KbImportReport {
55
63
  * uncommitted content was not imported.
56
64
  */
57
65
  worktree_ignored?: boolean;
66
+ /**
67
+ * Present (true) exactly when the project KB is the http provider: the KB
68
+ * server is the source of truth, so the bible is neither read nor imported
69
+ * and every count is 0. `reason` says why.
70
+ */
71
+ bible_skipped?: true;
72
+ reason?: string;
58
73
  }
74
+ export declare const KB_IMPORT_HTTP_SKIP_REASON = "bible import is not used over the http KB provider: the KB server is the source of truth";
59
75
  export declare function kbImport(input: KbImportInput, anchor?: KbAnchor): Promise<string>;
60
76
  //# sourceMappingURL=kb-import.d.ts.map
@@ -4,8 +4,8 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { getKbProviders } from '../services/knowledge/kb-providers.js';
6
6
  import { resolveKbAnchor } from '../services/knowledge/kb-self.js';
7
- import { parseBibleText, importBibleEntries } from '../services/knowledge/bible-import.js';
8
- import { requireSqliteProject } from '../services/knowledge/require-sqlite-project.js';
7
+ import { parseBibleDocument, importBibleEntries } from '../services/knowledge/bible-import.js';
8
+ import { requireSqliteProject, isSqliteProject } from '../services/knowledge/require-sqlite-project.js';
9
9
  import { KbMaintainerGrantError, memberLacksKbMaintainer } from '../services/knowledge/kb-maintainer-grant.js';
10
10
  import { OWN_BIBLE_REL, BibleBlobIntegrityError, bibleBytesBlobId, isSafeBibleRef, readCommittedBibleBlob, } from '../services/knowledge/bible-blob-id.js';
11
11
  // T2.1 (F4, D3 HARDENED): kb_import -- the trusted-channel write path that lets a
@@ -117,11 +117,23 @@ function requireLocalFolder(folder) {
117
117
  }
118
118
  return folder;
119
119
  }
120
+ export const KB_IMPORT_HTTP_SKIP_REASON = 'bible import is not used over the http KB provider: the KB server is the source of truth';
120
121
  export async function kbImport(input, anchor) {
121
122
  const resolved = resolveKbAnchor(anchor);
122
123
  const repoAnchor = requireLocalFolder(resolved.folder);
123
124
  const ownBible = path.join(repoAnchor, '.fleet', 'kb-canonical.json');
124
125
  const biblePath = input.path ?? ownBible;
126
+ // Over http the KB server is the source of truth: the bible is not read
127
+ // and nothing is imported (decided before any bible read or grant check).
128
+ const providers = await getKbProviders(repoAnchor, resolved.remoteUrl);
129
+ if (!isSqliteProject(providers.project)) {
130
+ const skipped = {
131
+ imported: 0, skipped: 0, linked: 0, flagged: 0, rejected: 0, demoted: 0,
132
+ sweep: { checked: 0, staled: 0, unstaled: 0 },
133
+ bible_skipped: true, reason: KB_IMPORT_HTTP_SKIP_REASON,
134
+ };
135
+ return JSON.stringify(skipped);
136
+ }
125
137
  const lacksGrant = memberLacksKbMaintainer(anchor);
126
138
  const namesOwnBible = input.path === undefined || path.resolve(input.path) === path.resolve(ownBible);
127
139
  if (!namesOwnBible && lacksGrant) {
@@ -131,7 +143,9 @@ export async function kbImport(input, anchor) {
131
143
  // importing anything (reject otherwise -- non-zero exit at the CLI).
132
144
  // Parsing (both on-disk shapes) is shared with the member bible view
133
145
  // (services/knowledge/bible-import.ts); a malformed file throws KbBibleError.
134
- let bibleEntries;
146
+ // The DOCUMENT parse, not the entries-only one: the demotion tombstones are
147
+ // the cross-clone half of this import and must come from the same parse.
148
+ let bibleDoc;
135
149
  // Set whenever the bible was read from git (no-grant sessions always; any
136
150
  // session passing `ref`): the ref read, the hash-verified blob id, and
137
151
  // whether the work-tree copy differed.
@@ -179,7 +193,7 @@ export async function kbImport(input, anchor) {
179
193
  // Line endings are normalized for the comparison only (autocrlf checkouts).
180
194
  const lf = (t) => t.replace(/\r\n/g, '\n');
181
195
  committedSource = { ref, worktree_ignored: worktree === null || lf(worktree) !== lf(committed.text), blobId: committed.blobId };
182
- bibleEntries = parseBibleText(committed.text, ref + ':' + rel, 'kb_import');
196
+ bibleDoc = parseBibleDocument(committed.text, ref + ':' + rel, 'kb_import');
183
197
  }
184
198
  else {
185
199
  if (!fs.existsSync(biblePath)) {
@@ -187,11 +201,10 @@ export async function kbImport(input, anchor) {
187
201
  }
188
202
  // Read once: the bytes parsed are the bytes whose blob id is recorded.
189
203
  fileBytes = fs.readFileSync(biblePath);
190
- bibleEntries = parseBibleText(fileBytes.toString('utf-8'), biblePath, 'kb_import');
204
+ bibleDoc = parseBibleDocument(fileBytes.toString('utf-8'), biblePath, 'kb_import');
191
205
  }
192
206
  // repoAnchor (resolved above) selects the KB, so an import 'for' repo B can
193
207
  // never land in whichever repo the server process happens to sit in.
194
- const providers = await getKbProviders(repoAnchor, resolved.remoteUrl);
195
208
  const provider = requireSqliteProject(providers.project, 'kb_import');
196
209
  // Trust anchor (see the header): a committed bible is imported by a member
197
210
  // session without the grant only when the maintainer side recorded its
@@ -206,7 +219,9 @@ export async function kbImport(input, anchor) {
206
219
  // Same entry loop the member bible view uses: import mode (bible confidence
207
220
  // preserved, directives quarantined), id-exists skip first, per-entry
208
221
  // isolation of capture basis rejections.
209
- const { imported, skipped, linked, flagged, rejected } = await importBibleEntries(provider, bibleEntries);
222
+ // Tombstones ride along in the same call so entries and demotions can never
223
+ // be applied from two different reads of the file.
224
+ const { imported, skipped, linked, flagged, rejected, demoted } = await importBibleEntries(provider, bibleDoc.entries, { demotions: bibleDoc.demotions });
210
225
  // A FULL or kb_maintainer session is trusted to import at bible confidence,
211
226
  // so the bible it just imported becomes trusted for member sessions too:
212
227
  // record the blob id the bytes would have as this repo's committed own
@@ -243,8 +258,8 @@ export async function kbImport(input, anchor) {
243
258
  ? { checked: 0, staled: 0, unstaled: 0 }
244
259
  : await provider.freshnessSweep(repoAnchor);
245
260
  const report = committedSource
246
- ? { imported, skipped, linked, flagged, rejected, sweep, bible_source: committedSource.ref, worktree_ignored: committedSource.worktree_ignored }
247
- : { imported, skipped, linked, flagged, rejected, sweep };
261
+ ? { imported, skipped, linked, flagged, rejected, demoted, sweep, bible_source: committedSource.ref, worktree_ignored: committedSource.worktree_ignored }
262
+ : { imported, skipped, linked, flagged, rejected, demoted, sweep };
248
263
  return JSON.stringify(report);
249
264
  }
250
265
  //# sourceMappingURL=kb-import.js.map
@@ -9,18 +9,26 @@ export declare const kbInvalidateSchema: z.ZodObject<{
9
9
  }, "strip", z.ZodTypeAny, {
10
10
  files?: string[] | undefined;
11
11
  repo?: unknown;
12
+ ids?: string[] | undefined;
12
13
  repo_path?: unknown;
13
14
  repo_remote_url?: unknown;
14
- ids?: string[] | undefined;
15
15
  }, {
16
16
  files?: string[] | undefined;
17
17
  repo?: unknown;
18
+ ids?: string[] | undefined;
18
19
  repo_path?: unknown;
19
20
  repo_remote_url?: unknown;
20
- ids?: string[] | undefined;
21
21
  }>;
22
22
  export type KbInvalidateInput = z.infer<typeof kbInvalidateSchema>;
23
+ export declare const KB_HOOK_MARKER = "# apra-fleet KB invalidation hook";
23
24
  export declare const KB_POST_COMMIT_HOOK = "#!/bin/sh\n# apra-fleet KB invalidation hook\n# Marks context-cache entries stale for files changed in the last commit\ngit diff-tree --no-commit-id -r --name-only HEAD | while IFS= read -r f; do\n [ -n \"$f\" ] && node dist/index.js kb invalidate \"$f\" 2>/dev/null || true\ndone\n";
24
- export declare function installKbPostCommitHook(repoPath: string): void;
25
+ export type KbHookInstallResult = {
26
+ installed: true;
27
+ hookPath: string;
28
+ } | {
29
+ installed: false;
30
+ reason: string;
31
+ };
32
+ export declare function installKbPostCommitHook(repoPath: string): KbHookInstallResult;
25
33
  export declare function kbInvalidate(input: KbInvalidateInput, anchor?: KbAnchor): Promise<string>;
26
34
  //# sourceMappingURL=kb-invalidate.d.ts.map
@@ -2,10 +2,13 @@ import { z } from 'zod';
2
2
  import { KB_REMOVED_SCOPE_KEYS_SHAPE } from '../services/knowledge/kb-removed-scope-keys.js';
3
3
  import path from 'node:path';
4
4
  import fs from 'node:fs';
5
+ import { execFileSync } from 'node:child_process';
5
6
  import { getSelfKbProviders, memberOwnerTag } from '../services/knowledge/kb-self.js';
6
- import { requireSqliteProject } from '../services/knowledge/require-sqlite-project.js';
7
+ import { isSqliteProject } from '../services/knowledge/require-sqlite-project.js';
8
+ import { KbHttpUnsupportedError } from '../services/knowledge/http-provider.js';
7
9
  import { validateFilePaths } from '../services/knowledge/path-validation.js';
8
10
  import { memberLacksKbMaintainer } from '../services/knowledge/kb-maintainer-grant.js';
11
+ import { gitExecutable } from '../os/git-executable.js';
9
12
  export const kbInvalidateSchema = z.object({
10
13
  files: z.array(z.string()).min(1).optional().describe('File paths to invalidate (context-cache entries for these files will be marked stale)'),
11
14
  ids: z.array(z.string().min(1)).min(1).optional().describe('Entry ids to discard (sets superseded_at; the entry drops from all reads). Exactly one of files or ids.'),
@@ -13,20 +16,85 @@ export const kbInvalidateSchema = z.object({
13
16
  // is refused with E-SCOPE-KEY-REMOVED instead of silently re-scoped.
14
17
  ...KB_REMOVED_SCOPE_KEYS_SHAPE,
15
18
  });
19
+ // Identifies a post-commit hook fleet wrote; kb_setup only rewrites files carrying it.
20
+ export const KB_HOOK_MARKER = '# apra-fleet KB invalidation hook';
16
21
  export const KB_POST_COMMIT_HOOK = `#!/bin/sh
17
- # apra-fleet KB invalidation hook
22
+ ${KB_HOOK_MARKER}
18
23
  # Marks context-cache entries stale for files changed in the last commit
19
24
  git diff-tree --no-commit-id -r --name-only HEAD | while IFS= read -r f; do
20
25
  [ -n "$f" ] && node dist/index.js kb invalidate "$f" 2>/dev/null || true
21
26
  done
22
27
  `;
28
+ // Ask git for a path (`git rev-parse <args>`), made absolute against repoPath.
29
+ // Used for the hooks dir -- in a linked worktree .git is a file, and
30
+ // core.hooksPath may relocate it -- and the git common dir. Fails loud, naming repoPath.
31
+ function gitRevParsePath(repoPath, args) {
32
+ const command = `git rev-parse ${args.join(' ')}`;
33
+ let out;
34
+ try {
35
+ out = execFileSync(gitExecutable(), ['rev-parse', ...args], {
36
+ cwd: repoPath, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
37
+ }).trim().split(/\r?\n/)[0]?.trim() ?? '';
38
+ }
39
+ catch (err) {
40
+ const msg = err instanceof Error ? err.message : String(err);
41
+ throw new Error(`Cannot resolve git path for ${repoPath} (${command}): ${msg}`);
42
+ }
43
+ if (!out) {
44
+ throw new Error(`Cannot resolve git path for ${repoPath}: ${command} printed nothing`);
45
+ }
46
+ return path.isAbsolute(out) ? out : path.join(repoPath, out);
47
+ }
48
+ // Realpath of p, or of its nearest existing ancestor with the rest re-appended,
49
+ // so a not-yet-created dir compares in the same form as an existing one
50
+ // (Windows 8.3 short names, macOS /var -> /private/var).
51
+ function canonicalPath(p) {
52
+ const resolved = path.resolve(p);
53
+ if (fs.existsSync(resolved))
54
+ return fs.realpathSync.native(resolved);
55
+ const parent = path.dirname(resolved);
56
+ if (parent === resolved)
57
+ return resolved;
58
+ return path.join(canonicalPath(parent), path.basename(resolved));
59
+ }
60
+ function isWithin(base, target) {
61
+ const rel = path.relative(base, target);
62
+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel));
63
+ }
64
+ // The hooks dir must sit under the worktree or the git common dir; a global
65
+ // core.hooksPath pointing elsewhere is shared by other repos and not ours to write.
66
+ function hookDirInsideRepo(repoPath, hookDir) {
67
+ const target = canonicalPath(hookDir);
68
+ const commonDir = gitRevParsePath(repoPath, ['--git-common-dir']);
69
+ return [repoPath, commonDir].some((base) => isWithin(canonicalPath(base), target));
70
+ }
71
+ // True when hookPath is absent, or is a regular file carrying KB_HOOK_MARKER.
72
+ // A symlink, directory or unmarked file belongs to someone else.
73
+ function hookIsOursOrAbsent(hookPath) {
74
+ let stat;
75
+ try {
76
+ stat = fs.lstatSync(hookPath);
77
+ }
78
+ catch (err) {
79
+ if (err.code === 'ENOENT')
80
+ return true;
81
+ const msg = err instanceof Error ? err.message : String(err);
82
+ throw new Error(`Cannot inspect existing post-commit hook at ${hookPath}: ${msg}`);
83
+ }
84
+ return stat.isFile() && fs.readFileSync(hookPath, 'utf8').includes(KB_HOOK_MARKER);
85
+ }
23
86
  export function installKbPostCommitHook(repoPath) {
24
- const hookDir = path.join(repoPath, '.git', 'hooks');
25
- if (!fs.existsSync(hookDir)) {
26
- fs.mkdirSync(hookDir, { recursive: true });
87
+ const hookDir = gitRevParsePath(repoPath, ['--git-path', 'hooks']);
88
+ if (!hookDirInsideRepo(repoPath, hookDir)) {
89
+ return { installed: false, reason: `hooks dir ${hookDir} is outside the repo and its git dir (core.hooksPath)` };
27
90
  }
28
91
  const hookPath = path.join(hookDir, 'post-commit');
92
+ if (!hookIsOursOrAbsent(hookPath)) {
93
+ return { installed: false, reason: `existing post-commit at ${hookPath} is not ours` };
94
+ }
95
+ fs.mkdirSync(hookDir, { recursive: true });
29
96
  fs.writeFileSync(hookPath, KB_POST_COMMIT_HOOK, { mode: 0o755 });
97
+ return { installed: true, hookPath };
30
98
  }
31
99
  // A MEMBER session WITHOUT the kb_maintainer grant may not retire a CONFIRMED
32
100
  // entry by either form: a discarded (ids) or file-invalidated (files) row is
@@ -54,10 +122,15 @@ export async function kbInvalidate(input, anchor) {
54
122
  validateFilePaths(input.files);
55
123
  const providers = await getSelfKbProviders(anchor);
56
124
  // MEMBER session: only the caller's own captures (member:<uuid>) for these
57
- // files are invalidated; other members' entries are left untouched.
125
+ // files are invalidated; other members' entries are left untouched. The
126
+ // KB server has no own-scope invalidate route, so over http a MEMBER
127
+ // invalidate is refused before anything is sent.
58
128
  const ownerTag = memberOwnerTag(anchor);
59
129
  if (ownerTag !== undefined) {
60
- const { invalidated, refused } = await requireSqliteProject(providers.project, 'kb_invalidate')
130
+ if (!isSqliteProject(providers.project)) {
131
+ throw new KbHttpUnsupportedError('kb_invalidate with files in a MEMBER session (own-scope invalidate)', 'nothing was invalidated', 'invalidate the files from a FULL session, or use a local SQLite KB (kb_setup provider sqlite).');
132
+ }
133
+ const { invalidated, refused } = await providers.project
61
134
  .invalidate(input.files, { ownerTag, ...(keepConfirmed ? { keepConfirmed: true } : {}) });
62
135
  return JSON.stringify(refused !== undefined ? { invalidated, files: input.files, refused } : { invalidated, files: input.files });
63
136
  }