@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
@@ -0,0 +1,233 @@
1
+ // The repository a remote KB request is about, as the HTTP provider sends it.
2
+ //
3
+ // kb_* tools take no repository argument: fleet resolves the repository from
4
+ // the calling session (kb-self.ts). HttpKbProvider forwards that resolved
5
+ // repository to a shared remote KB server as two headers, so the server can
6
+ // keep repositories apart:
7
+ //
8
+ // X-Repository the normalised origin remote, `host/path`
9
+ // X-Repository-Commit the HEAD sha of the local folder, when readable
10
+ // X-Repository-Branch the checked-out branch of the local folder, when on
11
+ // one (not detached), percent-encoded
12
+ //
13
+ // All values come ONLY from fleet's resolved anchor, never from tool input.
14
+ import { execFileSync } from 'node:child_process';
15
+ import path from 'node:path';
16
+ import { gitExecutable } from '../../os/git-executable.js';
17
+ export const REPOSITORY_HEADER = 'X-Repository';
18
+ export const REPOSITORY_COMMIT_HEADER = 'X-Repository-Commit';
19
+ export const REPOSITORY_BRANCH_HEADER = 'X-Repository-Branch';
20
+ /** Longest X-Repository-Branch value (after percent-encoding) that is sent. */
21
+ export const MAX_BRANCH_LENGTH = 255;
22
+ /** Longest X-Repository value a receiving server accepts. */
23
+ export const MAX_REPOSITORY_LENGTH = 512;
24
+ const AZURE_HOST = 'dev.azure.com';
25
+ const VISUALSTUDIO_SUFFIX = '.visualstudio.com';
26
+ const URL_SCHEMES = new Set(['http', 'https', 'ssh', 'git', 'git+ssh', 'ssh+git']);
27
+ const HOSTNAME = /^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\[[0-9a-f:.]+\])$/;
28
+ /**
29
+ * Normalise a git remote URL to `host/path`: no scheme, no user info or
30
+ * credentials, no port, no query or fragment, no trailing `.git` or `/`. The
31
+ * host is lowercased; the path keeps its case. ssh forms (`git@host:org/repo`,
32
+ * `ssh://git@host/org/repo`) map to the same value as https. Azure DevOps
33
+ * spellings fold to `dev.azure.com/<org>/<project>/_git/<repo>` (org
34
+ * lowercased), as the receiving server canonicalises them. Characters outside
35
+ * printable ASCII (space, non-ASCII) are percent-encoded.
36
+ *
37
+ * Returns undefined for anything that is not a network remote (a local path, a
38
+ * file:// URL) or that would not be a valid header value.
39
+ */
40
+ export function normaliseRepositoryRemote(remoteUrl) {
41
+ const raw = remoteUrl.trim();
42
+ if (!raw || raw.includes('\\'))
43
+ return undefined;
44
+ let hostPart;
45
+ let pathPart;
46
+ const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(.*)$/.exec(raw);
47
+ if (scheme) {
48
+ if (!URL_SCHEMES.has(scheme[1].toLowerCase()))
49
+ return undefined;
50
+ const rest = scheme[2];
51
+ const slash = rest.indexOf('/');
52
+ const authority = slash < 0 ? rest : rest.slice(0, slash);
53
+ pathPart = slash < 0 ? '' : rest.slice(slash + 1);
54
+ // Drop user info (and any credentials in it): everything up to the LAST '@'
55
+ // of the authority, then the port.
56
+ hostPart = authority.slice(authority.lastIndexOf('@') + 1).replace(/:\d*$/, '');
57
+ }
58
+ else {
59
+ // scp-like form: [user@]host:path. A single-letter "host" is a Windows
60
+ // drive (C:/x), and a path with no ':' before its first '/' is local.
61
+ const scp = /^(?:[^@/]*@)?([^@/:]+):(.*)$/.exec(raw);
62
+ if (!scp || scp[1].length < 2)
63
+ return undefined;
64
+ hostPart = scp[1];
65
+ pathPart = scp[2];
66
+ }
67
+ // Real userinfo sits in the authority and is already stripped. An '@' still in
68
+ // the path means the parser misread credentials as the host (a password with a
69
+ // numeric prefix and a '/', e.g. `https://u:1234/pw@host/o/r` turns `u:1234`
70
+ // into host `u` and a port). Checked before the query/fragment strip so a
71
+ // `#`/`?` in such a password cannot hide the '@'. Send no header.
72
+ if (pathPart.includes('@'))
73
+ return undefined;
74
+ // Query and fragment never identify a repository and can carry tokens.
75
+ pathPart = pathPart.replace(/[?#].*$/, '');
76
+ const host = hostPart.toLowerCase();
77
+ const repoPath = pathPart
78
+ .replace(/^\/+/, '')
79
+ .replace(/\/+$/, '')
80
+ .replace(/\.git$/i, '')
81
+ .replace(/\/+$/, '');
82
+ // The host must be a hostname or a bracketed IPv6 literal. Anything else (a
83
+ // password containing '/', a query before the path, a non-numeric port) means
84
+ // the authority was not parsed as the remote intended, and what is left could
85
+ // carry credentials or tokens: send no header rather than a leaking one.
86
+ if (!repoPath || !HOSTNAME.test(host))
87
+ return undefined;
88
+ const value = canonicaliseAzure(percentEncode(`${host}/${repoPath}`));
89
+ return isValidRepositoryValue(value) ? value : undefined;
90
+ }
91
+ /**
92
+ * True when `value` is a header value a receiving server accepts: at most 512
93
+ * printable ASCII characters, no spaces, no scheme, no '@' before the first '/'.
94
+ */
95
+ export function isValidRepositoryValue(value) {
96
+ if (value.length === 0 || value.length > MAX_REPOSITORY_LENGTH)
97
+ return false;
98
+ if (!/^[!-~]+$/.test(value) || value.includes('://'))
99
+ return false;
100
+ const at = value.indexOf('@');
101
+ const slash = value.indexOf('/');
102
+ return slash > 0 && (at < 0 || slash < at);
103
+ }
104
+ function percentEncode(value) {
105
+ let out = '';
106
+ for (const ch of value) {
107
+ out += /^[!-~]$/.test(ch)
108
+ ? ch
109
+ : Array.from(Buffer.from(ch, 'utf8'), b => `%${b.toString(16).toUpperCase().padStart(2, '0')}`).join('');
110
+ }
111
+ return out;
112
+ }
113
+ function azureKey(org, project, repo) {
114
+ return `${AZURE_HOST}/${org.toLowerCase()}/${project}/_git/${repo}`;
115
+ }
116
+ const eq = (a, b) => a.toLowerCase() === b.toLowerCase();
117
+ // Mirrors the receiving server's canonicalisation of Azure DevOps spellings,
118
+ // so fleet sends the canonical key rather than relying on the server to fold it.
119
+ function canonicaliseAzure(value) {
120
+ const segments = value.split('/');
121
+ if (segments.some(s => s.length === 0))
122
+ return value;
123
+ const host = segments[0];
124
+ // ssh.dev.azure.com/v3/<org>/<project>/<repo>, vs-ssh.visualstudio.com/v3/...
125
+ if ((host === 'ssh.dev.azure.com' || host === 'vs-ssh.visualstudio.com')
126
+ && segments.length === 5 && eq(segments[1], 'v3')) {
127
+ return azureKey(segments[2], segments[3], segments[4]);
128
+ }
129
+ // dev.azure.com/<org>/<project>/_git/<repo>
130
+ if (host === AZURE_HOST && segments.length === 5 && eq(segments[3], '_git')) {
131
+ return azureKey(segments[1], segments[2], segments[4]);
132
+ }
133
+ if (host.endsWith(VISUALSTUDIO_SUFFIX) && host.length > VISUALSTUDIO_SUFFIX.length) {
134
+ const org = host.slice(0, -VISUALSTUDIO_SUFFIX.length);
135
+ // <org>.visualstudio.com/<project>/_git/<repo>
136
+ if (segments.length === 4 && eq(segments[2], '_git')) {
137
+ return azureKey(org, segments[1], segments[3]);
138
+ }
139
+ // <org>.visualstudio.com/DefaultCollection/<project>/_git/<repo>
140
+ if (segments.length === 5 && eq(segments[1], 'DefaultCollection') && eq(segments[3], '_git')) {
141
+ return azureKey(org, segments[2], segments[4]);
142
+ }
143
+ }
144
+ return value;
145
+ }
146
+ function gitOut(folder, args) {
147
+ // Same ceiling as resolveProjectSlug / kb-self: the folder itself must be the
148
+ // repository, never a checkout it merely sits inside.
149
+ const env = { ...process.env, GIT_CEILING_DIRECTORIES: path.dirname(folder) };
150
+ try {
151
+ return execFileSync(gitExecutable(), args, {
152
+ cwd: folder, env, encoding: 'utf-8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
153
+ }).trim();
154
+ }
155
+ catch {
156
+ return undefined;
157
+ }
158
+ }
159
+ /** A full SHA-1 or SHA-256 commit id, lowercase. */
160
+ export const COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
161
+ /** How long a read HEAD sha is reused before git is asked again. */
162
+ export const HEAD_COMMIT_TTL_MS = 5000;
163
+ /**
164
+ * A reader for the HEAD sha of a local folder, cached for `ttlMs` so it is not
165
+ * re-read on every request. Returns undefined (never throws) when the folder
166
+ * is not a git repository or HEAD cannot be resolved (unborn branch).
167
+ */
168
+ export function headCommitReader(folder, ttlMs = HEAD_COMMIT_TTL_MS) {
169
+ let cached;
170
+ return () => {
171
+ const now = Date.now();
172
+ if (cached && now - cached.at < ttlMs)
173
+ return cached.value;
174
+ const sha = gitOut(folder, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])?.toLowerCase();
175
+ cached = { value: sha && COMMIT_SHA.test(sha) ? sha : undefined, at: now };
176
+ return cached.value;
177
+ };
178
+ }
179
+ const BRANCH_REF_PREFIX = 'refs/heads/';
180
+ /**
181
+ * True when `value` is an X-Repository-Branch value that may be sent: 1-255
182
+ * printable ASCII characters, no spaces.
183
+ */
184
+ export function isValidBranchValue(value) {
185
+ return value.length > 0 && value.length <= MAX_BRANCH_LENGTH && /^[!-~]+$/.test(value);
186
+ }
187
+ /**
188
+ * The header value for a branch name: characters outside printable ASCII
189
+ * (non-ASCII, control, space) percent-encoded as UTF-8. Undefined when the
190
+ * result is empty or longer than MAX_BRANCH_LENGTH.
191
+ */
192
+ export function branchHeaderValue(branch) {
193
+ const value = percentEncode(branch);
194
+ return isValidBranchValue(value) ? value : undefined;
195
+ }
196
+ /**
197
+ * A reader for the checked-out branch of a local folder (`git symbolic-ref
198
+ * --quiet HEAD`, with `refs/heads/` stripped), cached for `ttlMs` like
199
+ * headCommitReader so a branch switch shows within one TTL. `--short` is not
200
+ * used: it prints `heads/x` when a tag `x` also exists. Returns the header value
201
+ * (see branchHeaderValue), or undefined (never throws) on a detached HEAD, a HEAD
202
+ * not under refs/heads/, a folder that is not a git repository, a git failure or
203
+ * timeout, or an invalid value.
204
+ */
205
+ export function headBranchReader(folder, ttlMs = HEAD_COMMIT_TTL_MS) {
206
+ let cached;
207
+ return () => {
208
+ const now = Date.now();
209
+ if (cached && now - cached.at < ttlMs)
210
+ return cached.value;
211
+ const ref = gitOut(folder, ['symbolic-ref', '--quiet', 'HEAD']);
212
+ const branch = ref?.startsWith(BRANCH_REF_PREFIX) ? ref.slice(BRANCH_REF_PREFIX.length) : undefined;
213
+ cached = { value: branch ? branchHeaderValue(branch) : undefined, at: now };
214
+ return cached.value;
215
+ };
216
+ }
217
+ /**
218
+ * The repository identity for a resolved KB anchor, or undefined when there is
219
+ * none. `remoteUrl` is set only when the folder lives on another host: then
220
+ * the identity is that remote and the commit and branch are unknown (git
221
+ * cannot run there). Otherwise the identity is the local folder's origin
222
+ * remote, the commit is its HEAD and the branch its checked-out branch.
223
+ */
224
+ export function resolveRepositoryIdentity(folder, remoteUrl) {
225
+ if (remoteUrl && remoteUrl.trim()) {
226
+ const remote = normaliseRepositoryRemote(remoteUrl);
227
+ return remote ? { remote } : undefined;
228
+ }
229
+ const origin = gitOut(folder, ['remote', 'get-url', 'origin']);
230
+ const remote = origin ? normaliseRepositoryRemote(origin) : undefined;
231
+ return remote ? { remote, commitOf: headCommitReader(folder), branchOf: headBranchReader(folder) } : undefined;
232
+ }
233
+ //# sourceMappingURL=repository-header.js.map
@@ -11,7 +11,7 @@ export declare function isSqliteProject(provider: MemoryProvider): provider is S
11
11
  /**
12
12
  * Narrows a project KB provider to SqliteProvider, for call sites that use
13
13
  * SqliteProvider-only capabilities not part of the MemoryProvider interface
14
- * (list, feedback, freshnessSweep, reconcilePrefilter, resolveContradiction,
14
+ * (list, freshnessSweep, reconcilePrefilter, resolveContradiction,
15
15
  * hasEntry, the DirectiveProvider methods, and capture's second CaptureOpts
16
16
  * argument).
17
17
  *
@@ -12,7 +12,7 @@ export function isSqliteProject(provider) {
12
12
  /**
13
13
  * Narrows a project KB provider to SqliteProvider, for call sites that use
14
14
  * SqliteProvider-only capabilities not part of the MemoryProvider interface
15
- * (list, feedback, freshnessSweep, reconcilePrefilter, resolveContradiction,
15
+ * (list, freshnessSweep, reconcilePrefilter, resolveContradiction,
16
16
  * hasEntry, the DirectiveProvider methods, and capture's second CaptureOpts
17
17
  * argument).
18
18
  *
@@ -1,5 +1,10 @@
1
1
  import { type DiscardResult, type RetireOptions } from './types.js';
2
2
  import type { MemoryProvider, KBEntry, KBEntryInput, CaptureOpts, CaptureResult, QueryOptions, EntryTrustFilter, KBResult, FileContextResult, PrimeOptions, PrimedContext, SyncOptions, SyncResult, Confidence, ProviderStats } from './types.js';
3
+ /**
4
+ * The reason recorded when a demotion arrives through the committed project
5
+ * bible rather than a local kb_demote. Must clear MIN_DEMOTE_REASON_LENGTH.
6
+ */
7
+ export declare const BIBLE_DEMOTION_REASON = "demoted in the project bible";
3
8
  export declare class SqliteProvider implements MemoryProvider {
4
9
  private db;
5
10
  readonly dbPath: string;
@@ -99,6 +104,55 @@ export declare class SqliteProvider implements MemoryProvider {
99
104
  * entry to the bible.
100
105
  */
101
106
  getSourceFileBases(ids: string[]): Map<string, Record<string, string> | null>;
107
+ /**
108
+ * The bible trust time of each given id that exists: when this clone's trust
109
+ * in the row dates from, as a bible records it. promoted_at when the row was
110
+ * promoted here; else the updated_at the bible carried when the row was
111
+ * imported (bible_updated_at); else null for an imported row from before that
112
+ * column existed -- its trust came from a bible, and the local import time
113
+ * says nothing about when it was promoted. Any other row falls back to
114
+ * created_at. An unknown id is absent from the map. Fed to
115
+ * standingAgainstTombstone (bible-import.ts) by kb_export, and used for the
116
+ * updated_at a bible writer records, so every clone compares the same value.
117
+ * Internal to this provider, not an MCP surface.
118
+ */
119
+ getBibleTrustTimes(ids: string[]): Map<string, string | null>;
120
+ /** getBibleTrustTimes' rule for one raw row (needs promoted_at, bible_updated_at, source, created_at). */
121
+ private bibleTrustTimeOf;
122
+ /**
123
+ * Read-only accessor for the demotion state of the given entry ids: the
124
+ * CURRENT confidence and demoted_at of each id that exists. An unknown id is
125
+ * simply absent from the map.
126
+ *
127
+ * Deliberately NOT routed through list(): list() excludes stale and superseded
128
+ * rows, and a demoted entry that later went stale is exactly the one whose
129
+ * tombstone other clones most need -- their bible still carries the entry.
130
+ * Policy (what counts as demoted enough to tombstone) lives in the caller
131
+ * (src/tools/kb-bible-commit.ts); this member only reports the two columns.
132
+ * Internal to this provider, not an MCP surface.
133
+ */
134
+ getDemotionState(ids: string[]): Map<string, {
135
+ confidence: Confidence;
136
+ demoted_at?: string;
137
+ }>;
138
+ /**
139
+ * For each of the given ids that EXISTS locally, whether that row is LIVE
140
+ * CONFIRMED: confidence is CONFIRMED and the row is not stale, not superseded
141
+ * and not flagged_for_review.
142
+ *
143
+ * An id with NO local row is simply ABSENT from the map -- the caller must be
144
+ * able to tell "I hold a row and it is no longer trustworthy" (do not surface
145
+ * the bible's version of it) from "I have never seen this id" (the cold-seed
146
+ * case the bible exists to serve). A boolean-only return would conflate them.
147
+ *
148
+ * ONE predicate, deliberately not a demoted_at check. A demotion is only one
149
+ * of the ways a row stops being live CONFIRMED; staleness, supersession and a
150
+ * review flag are the others, and a cold seed that re-surfaced the bible's
151
+ * CONFIRMED copy of any of them would be re-asserting knowledge this clone has
152
+ * already stopped trusting. Reads the rows DIRECTLY rather than through list(),
153
+ * which filters stale and superseded rows out and so cannot report them.
154
+ */
155
+ getLiveConfirmedState(ids: string[]): Map<string, boolean>;
102
156
  private checkFreshness;
103
157
  freshnessSweep(root?: string): Promise<{
104
158
  checked: number;
@@ -158,6 +212,8 @@ export declare class SqliteProvider implements MemoryProvider {
158
212
  exclude_disputed?: boolean;
159
213
  /** MEMBER own-scope: only entries tagged with this value (ANDed with `tag`). */
160
214
  owner_tag?: string;
215
+ /** Also list stale entries (kb_list never sets it; the kb-server ownership lookup does). */
216
+ include_stale?: boolean;
161
217
  }): Promise<KBEntry[]>;
162
218
  promote(id: string, reason?: string, opts?: {
163
219
  ownerTag?: string;
@@ -166,6 +222,119 @@ export declare class SqliteProvider implements MemoryProvider {
166
222
  confidence_before: Confidence;
167
223
  confidence_after: Confidence;
168
224
  }>;
225
+ /**
226
+ * Evidence paths cited by a demote. Deliberately STRICTER than the basis
227
+ * check promote() runs: a demote reason is an audit record, so a path that
228
+ * cannot be pointed at inside this provider's anchor is refused rather than
229
+ * recorded as an unverifiable string.
230
+ *
231
+ * Refuses, all with E-DEMOTE-EVIDENCE-UNRESOLVED:
232
+ * - any path that is not anchor-relative -- an ABSOLUTE path, or one with
233
+ * a '..' segment. Both are "out of the anchor": an absolute path names a
234
+ * location the anchor does not contain, and was previously accepted and
235
+ * recorded verbatim, which contradicted this very comment. The check is
236
+ * delegated to validateFilePaths (path-validation.ts), the SAME guard
237
+ * every other caller-supplied kb_* file list already runs (kb_capture,
238
+ * kb_context, kb_invalidate, kb_session_prime and the HTTP routes), so
239
+ * this is not a third hand-rolled path guard. It runs BEFORE existence,
240
+ * so a path that happens to land on a real file outside the repo is
241
+ * still refused, and it applies even on the shared-global no-anchor KB,
242
+ * where nothing absolute could be verified against an anchor anyway;
243
+ * - a path that does not resolve, via the SAME resolver promote uses
244
+ * (unresolvableBasisFiles -> resolveBasisFile);
245
+ * - a path that resolves to something that is not a regular file
246
+ * (directories are not evidence).
247
+ */
248
+ private assertResolvableDemoteEvidence;
249
+ /**
250
+ * The demote-time basis snapshot: sha256 of each cited source file AS IT IS
251
+ * ON DISK RIGHT NOW, keyed by the original (unresolved) path string, the
252
+ * same key convention source_file_hashes uses.
253
+ *
254
+ * This MUST NOT be derived from the source_file_hashes column. That column
255
+ * is the CAPTURE-time basis; copying it was the defect in the superseded
256
+ * upstream attempt, and it silently breaks the ping-pong guard that asks
257
+ * whether the tree has moved on SINCE the demotion. Files that cannot be
258
+ * read are simply absent from the map (a demote is still allowed on an
259
+ * entry whose basis has since disappeared -- unlike promote, which refuses).
260
+ *
261
+ * sha256 and not `git hash-object`: this snapshot is compared against a
262
+ * later re-read of the same files by the same code, so it must not depend on
263
+ * git being available or on the file being in a work tree.
264
+ */
265
+ private demoteBasisHashes;
266
+ /**
267
+ * kb_demote: withdraw trust from a CONFIRMED entry, CONFIRMED -> INFERRED.
268
+ *
269
+ * The inverse of promote() in intent but NOT its mirror image in mechanics:
270
+ *
271
+ * - it is NOT a ladder. Only CONFIRMED is demotable; INFERRED/UNVERIFIED
272
+ * are REFUSED (E-DEMOTE-NOT-CONFIRMED), never silently returned as a
273
+ * no-op, so a caller can never believe it lowered trust that was already
274
+ * at the floor;
275
+ * - promoted_at and source are left untouched. promote() stamps
276
+ * source='promotion'; a demotion must not erase the provenance of the
277
+ * promotion it is reversing, and promoted_at stays as the record of when
278
+ * the (now withdrawn) trust was granted;
279
+ * - a STALE entry MAY be demoted. Staleness is a freshness verdict, trust
280
+ * is a separate axis, and the entries most worth demoting are exactly the
281
+ * ones the sweep has already flagged;
282
+ * - evidence is REQUIRED, like promote's resolvable basis: at least one
283
+ * evidence file, each of which must resolve inside the anchor
284
+ * (E-DEMOTE-EVIDENCE-UNRESOLVED otherwise).
285
+ *
286
+ * EVERY refusal is checked BEFORE any write, in the order below, and the
287
+ * order is load-bearing: the own-scope/unknown-id check comes first so a
288
+ * member can never learn that an entry it does not own exists by probing for
289
+ * a different refusal message.
290
+ */
291
+ demote(id: string, reason: string, evidenceFiles: string[], opts?: {
292
+ ownerTag?: string;
293
+ }): Promise<{
294
+ id: string;
295
+ confidence_before: Confidence;
296
+ confidence_after: Confidence;
297
+ }>;
298
+ /**
299
+ * Apply ONE explicit demotion tombstone from a committed project bible to the
300
+ * local row, so a demotion recorded on another clone actually lands here.
301
+ *
302
+ * Returns true only when a row was written. Every "no" is a silent false, not
303
+ * a throw: a bible carries tombstones for the whole project and most clones
304
+ * hold only some of those ids, so an inapplicable tombstone is the normal
305
+ * case, not an error.
306
+ *
307
+ * The rules, each of which silently corrupts another clone's KB if got wrong:
308
+ *
309
+ * - NEVER CREATE. A tombstoned id with no local row stays absent. A
310
+ * tombstone withdraws trust in a row; it is not a way to author one.
311
+ * - ONE RE-PROMOTION RULE. Demote only when standingAgainstTombstone
312
+ * (bible-import.ts) says 'withdrawn' for the row's bible trust time
313
+ * (getBibleTrustTimes): promoted_at, else the updated_at the bible carried
314
+ * at import -- never the local import time. kb_export uses the same rule to
315
+ * decide whether to re-add a tombstoned entry, so the two never disagree.
316
+ * - demoted_at is stamped with the TOMBSTONE's value, not now(): it records
317
+ * when trust was withdrawn, which happened on the other clone. That value
318
+ * is clamped to now (clampBibleTimeToNow), so a future-dated tombstone
319
+ * never stores a demoted_at that every later re-promotion falls before.
320
+ * - NO ownerTag CHECK. Bible-imported rows carry no member tag (see
321
+ * importBibleEntries, which builds its input with tags: [] and author
322
+ * 'unknown'), so an owner check here would make every imported row
323
+ * permanently undemotable. The trust boundary for this path is the
324
+ * git-reviewed bible file, not entry ownership.
325
+ *
326
+ * ABSENCE IS NEVER A DEMOTION: this method is only ever called for an id that
327
+ * carries an EXPLICIT tombstone. A local CONFIRMED row merely missing from the
328
+ * bible (a local-only promotion, or one refused by the basis filter) is never
329
+ * passed here and must stay untouched.
330
+ *
331
+ * Two refusals are inherited from demote() because they are invariants of the
332
+ * store, not of the local/remote distinction: a superseded row is already out
333
+ * of every read path (the write would have no observable meaning), and a
334
+ * user-directive is human-terminal in both directions -- a bible must not be
335
+ * able to deactivate a directive a human set here.
336
+ */
337
+ applyBibleDemotion(id: string, tombstoneAt: string): boolean;
169
338
  feedback(id: string, reason: string, author: string): Promise<KBEntry>;
170
339
  flaggedPairs(): Promise<{
171
340
  original: KBEntry;