@namzu/sdk 71.0.1 → 72.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/dist/agents/QueryAgent.d.ts.map +1 -1
  3. package/dist/agents/QueryAgent.js +1 -0
  4. package/dist/agents/QueryAgent.js.map +1 -1
  5. package/dist/authorization/readonly-commands.d.ts +9 -1
  6. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  7. package/dist/authorization/readonly-commands.js +70 -4
  8. package/dist/authorization/readonly-commands.js.map +1 -1
  9. package/dist/authorization/shell-paths.d.ts.map +1 -1
  10. package/dist/authorization/shell-paths.js +68 -16
  11. package/dist/authorization/shell-paths.js.map +1 -1
  12. package/dist/compaction/index.d.ts +1 -1
  13. package/dist/compaction/index.d.ts.map +1 -1
  14. package/dist/compaction/index.js +1 -1
  15. package/dist/compaction/index.js.map +1 -1
  16. package/dist/compaction/manual.d.ts +8 -0
  17. package/dist/compaction/manual.d.ts.map +1 -1
  18. package/dist/compaction/manual.js +18 -14
  19. package/dist/compaction/manual.js.map +1 -1
  20. package/dist/compaction/model-summary.d.ts +24 -6
  21. package/dist/compaction/model-summary.d.ts.map +1 -1
  22. package/dist/compaction/model-summary.js +152 -28
  23. package/dist/compaction/model-summary.js.map +1 -1
  24. package/dist/compaction/restore.d.ts +23 -0
  25. package/dist/compaction/restore.d.ts.map +1 -1
  26. package/dist/compaction/restore.js +59 -1
  27. package/dist/compaction/restore.js.map +1 -1
  28. package/dist/compaction/summary.d.ts +37 -2
  29. package/dist/compaction/summary.d.ts.map +1 -1
  30. package/dist/compaction/summary.js +46 -6
  31. package/dist/compaction/summary.js.map +1 -1
  32. package/dist/config/registry.d.ts +2 -0
  33. package/dist/config/registry.d.ts.map +1 -1
  34. package/dist/config/registry.js +76 -5
  35. package/dist/config/registry.js.map +1 -1
  36. package/dist/config/runtime.js +3 -3
  37. package/dist/config/runtime.js.map +1 -1
  38. package/dist/connector/index.d.ts +2 -2
  39. package/dist/connector/index.d.ts.map +1 -1
  40. package/dist/connector/index.js +1 -1
  41. package/dist/connector/index.js.map +1 -1
  42. package/dist/connector/mcp/adapter.d.ts +8 -0
  43. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  44. package/dist/connector/mcp/adapter.js +131 -1
  45. package/dist/connector/mcp/adapter.js.map +1 -1
  46. package/dist/connector/mcp/client.d.ts +26 -6
  47. package/dist/connector/mcp/client.d.ts.map +1 -1
  48. package/dist/connector/mcp/client.js +49 -7
  49. package/dist/connector/mcp/client.js.map +1 -1
  50. package/dist/connector/mcp/index.d.ts +2 -0
  51. package/dist/connector/mcp/index.d.ts.map +1 -1
  52. package/dist/connector/mcp/index.js +1 -0
  53. package/dist/connector/mcp/index.js.map +1 -1
  54. package/dist/connector/mcp/sandbox-stdio.d.ts +67 -0
  55. package/dist/connector/mcp/sandbox-stdio.d.ts.map +1 -0
  56. package/dist/connector/mcp/sandbox-stdio.js +178 -0
  57. package/dist/connector/mcp/sandbox-stdio.js.map +1 -0
  58. package/dist/connector/mcp/stdio-program.d.ts +34 -0
  59. package/dist/connector/mcp/stdio-program.d.ts.map +1 -0
  60. package/dist/connector/mcp/stdio-program.js +47 -0
  61. package/dist/connector/mcp/stdio-program.js.map +1 -0
  62. package/dist/connector/mcp/stdio.d.ts +12 -0
  63. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  64. package/dist/connector/mcp/stdio.js +54 -7
  65. package/dist/connector/mcp/stdio.js.map +1 -1
  66. package/dist/connector/web/guarded-fetch.d.ts +51 -2
  67. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  68. package/dist/connector/web/guarded-fetch.js +140 -19
  69. package/dist/connector/web/guarded-fetch.js.map +1 -1
  70. package/dist/connector/web/index.d.ts +2 -2
  71. package/dist/connector/web/index.d.ts.map +1 -1
  72. package/dist/connector/web/index.js +1 -1
  73. package/dist/connector/web/index.js.map +1 -1
  74. package/dist/constants/mcp/index.d.ts +29 -0
  75. package/dist/constants/mcp/index.d.ts.map +1 -1
  76. package/dist/constants/mcp/index.js +29 -0
  77. package/dist/constants/mcp/index.js.map +1 -1
  78. package/dist/manager/agent/lifecycle.d.ts +18 -1
  79. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  80. package/dist/manager/agent/lifecycle.js +53 -8
  81. package/dist/manager/agent/lifecycle.js.map +1 -1
  82. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  83. package/dist/plugin/hook-module/capabilities.js +24 -13
  84. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  85. package/dist/plugin/hook-module/host.d.ts +31 -0
  86. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  87. package/dist/plugin/hook-module/host.js +56 -13
  88. package/dist/plugin/hook-module/host.js.map +1 -1
  89. package/dist/plugin/hook-module/index.d.ts +3 -2
  90. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  91. package/dist/plugin/hook-module/index.js +2 -1
  92. package/dist/plugin/hook-module/index.js.map +1 -1
  93. package/dist/plugin/index.d.ts +2 -1
  94. package/dist/plugin/index.d.ts.map +1 -1
  95. package/dist/plugin/index.js +1 -0
  96. package/dist/plugin/index.js.map +1 -1
  97. package/dist/plugin/shell-hook-execute.d.ts +55 -0
  98. package/dist/plugin/shell-hook-execute.d.ts.map +1 -0
  99. package/dist/plugin/shell-hook-execute.js +73 -0
  100. package/dist/plugin/shell-hook-execute.js.map +1 -0
  101. package/dist/plugin/shell-hook-restrict.d.ts +31 -0
  102. package/dist/plugin/shell-hook-restrict.d.ts.map +1 -0
  103. package/dist/plugin/shell-hook-restrict.js +69 -0
  104. package/dist/plugin/shell-hook-restrict.js.map +1 -0
  105. package/dist/plugin/shell-hook.d.ts +73 -4
  106. package/dist/plugin/shell-hook.d.ts.map +1 -1
  107. package/dist/plugin/shell-hook.js +118 -17
  108. package/dist/plugin/shell-hook.js.map +1 -1
  109. package/dist/public-runtime.d.ts +9 -7
  110. package/dist/public-runtime.d.ts.map +1 -1
  111. package/dist/public-runtime.js +6 -5
  112. package/dist/public-runtime.js.map +1 -1
  113. package/dist/public-types.d.ts +4 -2
  114. package/dist/public-types.d.ts.map +1 -1
  115. package/dist/runtime/jobs/websocket-source.d.ts +2 -22
  116. package/dist/runtime/jobs/websocket-source.d.ts.map +1 -1
  117. package/dist/runtime/jobs/websocket-source.js +2 -33
  118. package/dist/runtime/jobs/websocket-source.js.map +1 -1
  119. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  120. package/dist/runtime/query/compact-session.js +5 -0
  121. package/dist/runtime/query/compact-session.js.map +1 -1
  122. package/dist/runtime/query/events.d.ts +7 -0
  123. package/dist/runtime/query/events.d.ts.map +1 -1
  124. package/dist/runtime/query/events.js +29 -11
  125. package/dist/runtime/query/events.js.map +1 -1
  126. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  127. package/dist/runtime/query/executor/tool-call-admission.js +51 -10
  128. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  129. package/dist/runtime/query/index.d.ts +6 -0
  130. package/dist/runtime/query/index.d.ts.map +1 -1
  131. package/dist/runtime/query/index.js +3 -0
  132. package/dist/runtime/query/index.js.map +1 -1
  133. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  134. package/dist/runtime/query/iteration/phases/compaction.js +21 -3
  135. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  136. package/dist/runtime/query/iteration/phases/context.d.ts +4 -0
  137. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  138. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  139. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  140. package/dist/runtime/query/path-escalation.js +90 -17
  141. package/dist/runtime/query/path-escalation.js.map +1 -1
  142. package/dist/runtime/query/steering.d.ts +15 -0
  143. package/dist/runtime/query/steering.d.ts.map +1 -1
  144. package/dist/runtime/query/steering.js +27 -3
  145. package/dist/runtime/query/steering.js.map +1 -1
  146. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  147. package/dist/scheduler/completion-inbox.js +15 -0
  148. package/dist/scheduler/completion-inbox.js.map +1 -1
  149. package/dist/session/workspace/driver.d.ts +12 -0
  150. package/dist/session/workspace/driver.d.ts.map +1 -1
  151. package/dist/session/workspace/git-worktree.d.ts +16 -0
  152. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  153. package/dist/session/workspace/git-worktree.js +35 -0
  154. package/dist/session/workspace/git-worktree.js.map +1 -1
  155. package/dist/session/workspace/holds.d.ts +78 -0
  156. package/dist/session/workspace/holds.d.ts.map +1 -0
  157. package/dist/session/workspace/holds.js +150 -0
  158. package/dist/session/workspace/holds.js.map +1 -0
  159. package/dist/session/workspace/index.d.ts +3 -1
  160. package/dist/session/workspace/index.d.ts.map +1 -1
  161. package/dist/session/workspace/index.js +2 -1
  162. package/dist/session/workspace/index.js.map +1 -1
  163. package/dist/store/config/index.d.ts +3 -0
  164. package/dist/store/config/index.d.ts.map +1 -1
  165. package/dist/store/config/index.js +3 -0
  166. package/dist/store/config/index.js.map +1 -1
  167. package/dist/store/session-index/index.d.ts +13 -0
  168. package/dist/store/session-index/index.d.ts.map +1 -1
  169. package/dist/store/session-index/index.js +1 -0
  170. package/dist/store/session-index/index.js.map +1 -1
  171. package/dist/store/session-index/rebuild.d.ts +12 -0
  172. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  173. package/dist/store/session-index/rebuild.js +20 -4
  174. package/dist/store/session-index/rebuild.js.map +1 -1
  175. package/dist/store/session-index/sqlite.d.ts +20 -0
  176. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  177. package/dist/store/session-index/sqlite.js +50 -12
  178. package/dist/store/session-index/sqlite.js.map +1 -1
  179. package/dist/tools/admit-facts.d.ts.map +1 -1
  180. package/dist/tools/admit-facts.js +59 -0
  181. package/dist/tools/admit-facts.js.map +1 -1
  182. package/dist/tools/builtins/grep.d.ts.map +1 -1
  183. package/dist/tools/builtins/grep.js +57 -0
  184. package/dist/tools/builtins/grep.js.map +1 -1
  185. package/dist/tools/builtins/lsp.d.ts.map +1 -1
  186. package/dist/tools/builtins/lsp.js +41 -4
  187. package/dist/tools/builtins/lsp.js.map +1 -1
  188. package/dist/tools/coordinator/ask-user-question.d.ts.map +1 -1
  189. package/dist/tools/coordinator/ask-user-question.js +67 -3
  190. package/dist/tools/coordinator/ask-user-question.js.map +1 -1
  191. package/dist/turn/memory-promoter.d.ts.map +1 -1
  192. package/dist/turn/memory-promoter.js +20 -4
  193. package/dist/turn/memory-promoter.js.map +1 -1
  194. package/dist/types/agent/base.d.ts +6 -0
  195. package/dist/types/agent/base.d.ts.map +1 -1
  196. package/dist/types/agent/task.d.ts +5 -0
  197. package/dist/types/agent/task.d.ts.map +1 -1
  198. package/dist/types/agent/task.js.map +1 -1
  199. package/dist/types/code-navigation/index.d.ts +34 -4
  200. package/dist/types/code-navigation/index.d.ts.map +1 -1
  201. package/dist/types/hitl/index.d.ts +8 -0
  202. package/dist/types/hitl/index.d.ts.map +1 -1
  203. package/dist/types/hitl/index.js.map +1 -1
  204. package/dist/types/message/index.d.ts +7 -0
  205. package/dist/types/message/index.d.ts.map +1 -1
  206. package/dist/types/message/index.js.map +1 -1
  207. package/dist/types/tool/presentation.d.ts +21 -0
  208. package/dist/types/tool/presentation.d.ts.map +1 -1
  209. package/package.json +6 -6
  210. package/src/agents/QueryAgent.ts +1 -0
  211. package/src/authorization/readonly-commands.ts +72 -4
  212. package/src/authorization/shell-paths.ts +75 -18
  213. package/src/compaction/index.ts +1 -0
  214. package/src/compaction/manual.ts +48 -12
  215. package/src/compaction/model-summary.ts +163 -28
  216. package/src/compaction/restore.ts +74 -1
  217. package/src/compaction/summary.ts +69 -3
  218. package/src/config/registry.ts +87 -5
  219. package/src/config/runtime.ts +3 -3
  220. package/src/connector/index.ts +3 -0
  221. package/src/connector/mcp/adapter.ts +137 -1
  222. package/src/connector/mcp/client.ts +49 -7
  223. package/src/connector/mcp/index.ts +5 -0
  224. package/src/connector/mcp/sandbox-stdio.ts +214 -0
  225. package/src/connector/mcp/stdio-program.ts +68 -0
  226. package/src/connector/mcp/stdio.ts +61 -7
  227. package/src/connector/web/guarded-fetch.ts +197 -30
  228. package/src/connector/web/index.ts +4 -1
  229. package/src/constants/mcp/index.ts +31 -0
  230. package/src/manager/agent/lifecycle.ts +58 -13
  231. package/src/plugin/hook-module/capabilities.ts +36 -14
  232. package/src/plugin/hook-module/host.ts +86 -13
  233. package/src/plugin/hook-module/index.ts +3 -0
  234. package/src/plugin/index.ts +4 -0
  235. package/src/plugin/shell-hook-execute.ts +126 -0
  236. package/src/plugin/shell-hook-restrict.ts +66 -0
  237. package/src/plugin/shell-hook.ts +209 -16
  238. package/src/public-runtime.ts +19 -0
  239. package/src/public-types.ts +20 -0
  240. package/src/runtime/jobs/websocket-source.ts +2 -46
  241. package/src/runtime/query/compact-session.ts +5 -0
  242. package/src/runtime/query/events.ts +29 -11
  243. package/src/runtime/query/executor/tool-call-admission.ts +62 -17
  244. package/src/runtime/query/index.ts +10 -0
  245. package/src/runtime/query/iteration/phases/compaction.ts +26 -2
  246. package/src/runtime/query/iteration/phases/context.ts +6 -0
  247. package/src/runtime/query/path-escalation.ts +102 -16
  248. package/src/runtime/query/steering.ts +38 -3
  249. package/src/scheduler/completion-inbox.ts +14 -0
  250. package/src/session/workspace/driver.ts +12 -0
  251. package/src/session/workspace/git-worktree.ts +49 -0
  252. package/src/session/workspace/holds.ts +201 -0
  253. package/src/session/workspace/index.ts +13 -1
  254. package/src/store/config/index.ts +6 -0
  255. package/src/store/session-index/index.ts +14 -0
  256. package/src/store/session-index/rebuild.ts +22 -4
  257. package/src/store/session-index/sqlite.ts +63 -14
  258. package/src/tools/admit-facts.ts +64 -0
  259. package/src/tools/builtins/grep.ts +52 -0
  260. package/src/tools/builtins/lsp.ts +47 -4
  261. package/src/tools/coordinator/ask-user-question.ts +88 -4
  262. package/src/turn/memory-promoter.ts +24 -3
  263. package/src/types/agent/base.ts +7 -0
  264. package/src/types/agent/task.ts +5 -0
  265. package/src/types/code-navigation/index.ts +48 -4
  266. package/src/types/hitl/index.ts +8 -0
  267. package/src/types/message/index.ts +7 -0
  268. package/src/types/tool/presentation.ts +22 -0
@@ -0,0 +1,201 @@
1
+ /**
2
+ * WorkspaceHoldStore — which live session or subagent is working in a checkout.
3
+ *
4
+ * A Git worktree belongs to whoever is using it right now, not only to the ref
5
+ * a driver created it from. A driver that removes a checkout while another
6
+ * process has it open takes that process's uncommitted files with it, so a
7
+ * removal asks this store first.
8
+ *
9
+ * ## What is on disk
10
+ *
11
+ * `<root>/workspace-holds/<key>/<pid>-<token>.json`, one file per holding, so
12
+ * two holders of the same path never write over each other and neither needs a
13
+ * lock. `<key>` is a hash of the canonical path; the body carries the path
14
+ * itself, so a key that belongs to something else is never believed.
15
+ *
16
+ * ## How liveness is decided
17
+ *
18
+ * A holding is the pid of the process that took it. On this machine the pid is
19
+ * asked whether it still exists: a crashed or killed session leaves its file
20
+ * behind, and every later look unlinks it. A record from another host on a
21
+ * shared home directory cannot be checked from here, so it is treated as live —
22
+ * the same rule the stored-memory lock uses. The residual risk is the same and
23
+ * is deliberate: a pid reused by an unrelated process reads as live, and a
24
+ * checkout stays where it is rather than being removed on a guess.
25
+ */
26
+
27
+ import { createHash, randomUUID } from 'node:crypto'
28
+ import { mkdir, readFile, readdir, realpath, unlink, writeFile } from 'node:fs/promises'
29
+ import { hostname as osHostname } from 'node:os'
30
+ import { join, resolve } from 'node:path'
31
+ import { resolveNamzuHome } from '../home.js'
32
+
33
+ /** One live use of a checkout. */
34
+ export interface WorkspaceHold {
35
+ /** The managed checkout root that must not be removed. */
36
+ readonly path: string
37
+ /** The folder the holder works in, which may be below `path`. */
38
+ readonly folder: string
39
+ /** Who holds it, for a person reading the refusal or the log. */
40
+ readonly holder: string
41
+ }
42
+
43
+ export interface WorkspaceHoldRequest {
44
+ /** The checkout root, as the driver knows it. */
45
+ readonly path: string
46
+ /** The folder the holder works in. Defaults to `path`. */
47
+ readonly folder?: string
48
+ /** A short, honest description: `session:1234`, `subagent:1234:review`. */
49
+ readonly holder: string
50
+ }
51
+
52
+ /** Ask a store who is working in a checkout, and record this process doing so. */
53
+ export interface WorkspaceHoldStore {
54
+ /**
55
+ * Record a holding. Resolves with an idempotent release; the caller keeps it
56
+ * for as long as it works in the checkout and releases it before it ends.
57
+ */
58
+ add(request: WorkspaceHoldRequest): Promise<() => Promise<void>>
59
+ /** Live holdings of `path`; empty when nothing holds it. */
60
+ holders(path: string): Promise<readonly WorkspaceHold[]>
61
+ }
62
+
63
+ export interface DiskWorkspaceHoldStoreOptions {
64
+ /** Directory the holdings live in. Defaults to {@link defaultWorkspaceHoldsDir}. */
65
+ readonly root?: string
66
+ /** True when a process with this pid exists on this machine. */
67
+ readonly isPidAlive?: (pid: number) => boolean
68
+ readonly hostname?: string
69
+ }
70
+
71
+ /** The refusal a removal reports when a live session or subagent still has the checkout. */
72
+ export class WorkspaceInUseError extends Error {
73
+ override readonly name = 'WorkspaceInUseError'
74
+ constructor(
75
+ readonly path: string,
76
+ readonly holders: readonly WorkspaceHold[],
77
+ ) {
78
+ const who = holders.map((hold) => `${hold.holder}, working in ${hold.folder}`).join('; ')
79
+ super(
80
+ `The worktree ${path} was not removed: a running session or subagent still has it (${who}). Its uncommitted files are untouched. Close that session, then remove it again.`,
81
+ )
82
+ }
83
+ }
84
+
85
+ function defaultIsPidAlive(pid: number): boolean {
86
+ try {
87
+ process.kill(pid, 0)
88
+ return true
89
+ } catch (error) {
90
+ // EPERM means the process is there and belongs to somebody else.
91
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH'
92
+ }
93
+ }
94
+
95
+ function isErrno(error: unknown, code: string): boolean {
96
+ return (error as NodeJS.ErrnoException | undefined)?.code === code
97
+ }
98
+
99
+ function keyFor(path: string): string {
100
+ return createHash('sha256').update(path).digest('hex').slice(0, 24)
101
+ }
102
+
103
+ interface HoldBody {
104
+ readonly v: 1
105
+ readonly path: string
106
+ readonly folder: string
107
+ readonly holder: string
108
+ readonly pid: number
109
+ readonly hostname: string
110
+ readonly startedAt: string
111
+ }
112
+
113
+ /** Resolve every existing path component, so two spellings of one folder share a key. */
114
+ async function canonical(path: string): Promise<string> {
115
+ try {
116
+ return await realpath(resolve(path))
117
+ } catch {
118
+ return resolve(path)
119
+ }
120
+ }
121
+
122
+ export class DiskWorkspaceHoldStore implements WorkspaceHoldStore {
123
+ private readonly root: string
124
+ private readonly isPidAlive: (pid: number) => boolean
125
+ private readonly hostname: string
126
+
127
+ constructor(options: DiskWorkspaceHoldStoreOptions = {}) {
128
+ this.root = resolve(options.root ?? defaultWorkspaceHoldsDir())
129
+ this.isPidAlive = options.isPidAlive ?? defaultIsPidAlive
130
+ this.hostname = options.hostname ?? osHostname()
131
+ }
132
+
133
+ private async directoryFor(path: string): Promise<string> {
134
+ return join(this.root, keyFor(await canonical(path)))
135
+ }
136
+
137
+ async add(request: WorkspaceHoldRequest): Promise<() => Promise<void>> {
138
+ const path = await canonical(request.path)
139
+ const directory = await this.directoryFor(path)
140
+ await mkdir(directory, { recursive: true, mode: 0o700 })
141
+ const body: HoldBody = {
142
+ v: 1,
143
+ path,
144
+ folder: await canonical(request.folder ?? path),
145
+ holder: request.holder,
146
+ pid: process.pid,
147
+ hostname: this.hostname,
148
+ startedAt: new Date().toISOString(),
149
+ }
150
+ const file = join(directory, `${process.pid}-${randomUUID()}.json`)
151
+ await writeFile(file, `${JSON.stringify(body)}\n`, { flag: 'wx', mode: 0o600 })
152
+ let released = false
153
+ return async () => {
154
+ if (released) return
155
+ released = true
156
+ await unlink(file).catch((error) => {
157
+ if (!isErrno(error, 'ENOENT')) throw error
158
+ })
159
+ }
160
+ }
161
+
162
+ async holders(path: string): Promise<readonly WorkspaceHold[]> {
163
+ const canonicalPath = await canonical(path)
164
+ const directory = await this.directoryFor(canonicalPath)
165
+ let names: string[]
166
+ try {
167
+ names = await readdir(directory)
168
+ } catch (error) {
169
+ if (isErrno(error, 'ENOENT')) return []
170
+ throw error
171
+ }
172
+ const found: WorkspaceHold[] = []
173
+ for (const name of names.sort()) {
174
+ if (!name.endsWith('.json')) continue
175
+ const file = join(directory, name)
176
+ let body: HoldBody
177
+ try {
178
+ body = JSON.parse(await readFile(file, 'utf8')) as HoldBody
179
+ } catch {
180
+ continue
181
+ }
182
+ if (body.v !== 1 || body.path !== canonicalPath) continue
183
+ if (body.hostname !== this.hostname) {
184
+ found.push({ path: body.path, folder: body.folder, holder: body.holder })
185
+ continue
186
+ }
187
+ if (this.isPidAlive(body.pid)) {
188
+ found.push({ path: body.path, folder: body.folder, holder: body.holder })
189
+ continue
190
+ }
191
+ // The holder is gone and its release never ran: this file is litter.
192
+ await unlink(file).catch(() => undefined)
193
+ }
194
+ return found
195
+ }
196
+ }
197
+
198
+ /** `<NAMZU_HOME>/workspace-holds`: one machine's view of who has which checkout. */
199
+ export function defaultWorkspaceHoldsDir(env: NodeJS.ProcessEnv = process.env): string {
200
+ return join(resolveNamzuHome({ env }), 'workspace-holds')
201
+ }
@@ -19,9 +19,21 @@ export type {
19
19
 
20
20
  export { WorkspaceBackendRegistry } from './registry.js'
21
21
 
22
- export { GitWorktreeDriver, parseWorktreeList } from './git-worktree.js'
22
+ export { GitWorktreeDriver, defaultWorktreesDir, parseWorktreeList } from './git-worktree.js'
23
23
  export type { ExecFile, ExecFileResult, GitWorktreeDriverConfig } from './git-worktree.js'
24
24
 
25
+ export {
26
+ DiskWorkspaceHoldStore,
27
+ defaultWorkspaceHoldsDir,
28
+ WorkspaceInUseError,
29
+ } from './holds.js'
30
+ export type {
31
+ DiskWorkspaceHoldStoreOptions,
32
+ WorkspaceHold,
33
+ WorkspaceHoldRequest,
34
+ WorkspaceHoldStore,
35
+ } from './holds.js'
36
+
25
37
  export { SharedSessionWorkspace } from './shared-session.js'
26
38
  export type {
27
39
  RegisterSharedSessionPlanInput,
@@ -21,6 +21,8 @@ export interface ConfigOverrideStore {
21
21
  load(): Record<string, unknown>
22
22
  /** Persist one namespace's accumulated override. */
23
23
  save(namespace: string, override: unknown): void
24
+ /** Where the overrides live, for a message that names the file. Absent for memory. */
25
+ location?(): string
24
26
  }
25
27
 
26
28
  /** The default: nothing survives the process, and it says so by its name. */
@@ -50,6 +52,10 @@ export class DiskConfigOverrideStore implements ConfigOverrideStore {
50
52
 
51
53
  constructor(private readonly path: string) {}
52
54
 
55
+ location(): string {
56
+ return this.path
57
+ }
58
+
53
59
  load(): Record<string, unknown> {
54
60
  if (this.cache) return { ...this.cache }
55
61
  try {
@@ -177,6 +177,13 @@ export interface SessionLogLocation {
177
177
  }
178
178
 
179
179
  export interface SessionIndex {
180
+ /**
181
+ * True while the index was opened on demand and no read has caught it up with
182
+ * the logs yet: the next list, search or lookup reads every log first, so a
183
+ * caller that makes a person wait can say so. Absent on a backend that does
184
+ * not defer.
185
+ */
186
+ readonly syncPending?: boolean
180
187
  readonly backend: 'sqlite' | 'scan'
181
188
  /** Derive (or continue deriving) one session from its records. */
182
189
  indexSession(input: SessionLogInput): Promise<IndexedSession | undefined>
@@ -216,6 +223,12 @@ export interface OpenSessionIndexOptions {
216
223
  * catch up with the logs in the background; every read waits for it.
217
224
  */
218
225
  readonly syncInBackground?: boolean
226
+ /**
227
+ * SQLite only: open without reading any log, and catch up with the logs the
228
+ * first time a read asks. A write never starts the catch-up. The scan
229
+ * backend reads on first use already.
230
+ */
231
+ readonly syncOnDemand?: boolean
219
232
  }
220
233
 
221
234
  /**
@@ -234,6 +247,7 @@ export async function openSessionIndex(
234
247
  home,
235
248
  path: options.path ?? join(home, 'index.sqlite'),
236
249
  ...(options.syncInBackground === true ? { syncInBackground: true } : {}),
250
+ ...(options.syncOnDemand === true ? { syncOnDemand: true } : {}),
237
251
  })
238
252
  }
239
253
 
@@ -745,8 +745,26 @@ export abstract class SessionIndexBase implements SessionIndex {
745
745
  return Promise.resolve()
746
746
  }
747
747
 
748
+ /**
749
+ * What a read about one session waits for. A backend that syncs on first read
750
+ * overrides it to bring only that session's rows current, so a lookup the turn
751
+ * itself makes does not read every log.
752
+ */
753
+ protected settledFor(_sessionId: SessionId | undefined): Promise<void> {
754
+ return this.settled()
755
+ }
756
+
757
+ /**
758
+ * What a write waits for: a catch-up already running, never one that has not
759
+ * started. A backend that syncs on first read overrides it, so a write at the
760
+ * start of a conversation does not pay for reading every log.
761
+ */
762
+ protected settledForWrite(): Promise<void> {
763
+ return this.settled()
764
+ }
765
+
748
766
  async getSession(sessionId: SessionId): Promise<IndexedSession | undefined> {
749
- await this.settled()
767
+ await this.settledFor(sessionId)
750
768
  return this.sessionNow(sessionId)
751
769
  }
752
770
 
@@ -765,7 +783,7 @@ export abstract class SessionIndexBase implements SessionIndex {
765
783
  * clears the row, so a write that ran beside it could be undone.
766
784
  */
767
785
  async indexSession(input: SessionLogInput): Promise<IndexedSession | undefined> {
768
- await this.settled()
786
+ await this.settledForWrite()
769
787
  return this.indexSessionNow(input)
770
788
  }
771
789
 
@@ -882,7 +900,7 @@ export abstract class SessionIndexBase implements SessionIndex {
882
900
  }
883
901
 
884
902
  async refresh(location: SessionLogLocation): Promise<SessionStaleness> {
885
- await this.settled()
903
+ await this.settledForWrite()
886
904
  return this.refreshNow(location)
887
905
  }
888
906
 
@@ -912,7 +930,7 @@ export abstract class SessionIndexBase implements SessionIndex {
912
930
  }
913
931
 
914
932
  async sync(home: string): Promise<void> {
915
- await this.settled()
933
+ await this.settledForWrite()
916
934
  return this.syncNow(home)
917
935
  }
918
936
 
@@ -477,6 +477,13 @@ export interface SqliteSessionIndexOptions {
477
477
  * longer waits on a home with thousands of logs.
478
478
  */
479
479
  readonly syncInBackground?: boolean
480
+ /**
481
+ * Return once the index is open and current in version, and read the logs
482
+ * only when something first asks for a list, a search or a lookup. Opening
483
+ * does no session work; that first read waits for the catch-up, later reads
484
+ * find it done, and a write never starts it.
485
+ */
486
+ readonly syncOnDemand?: boolean
480
487
  }
481
488
 
482
489
  export interface RebuildSqliteSessionIndexOptions extends SqliteSessionIndexOptions {
@@ -485,6 +492,8 @@ export interface RebuildSqliteSessionIndexOptions extends SqliteSessionIndexOpti
485
492
  * index already in place (another process finished first) discards its own.
486
493
  */
487
494
  readonly force?: boolean
495
+ /** Build the schema only and index no log; a later sync fills it. Opening on demand uses it. */
496
+ readonly empty?: boolean
488
497
  }
489
498
 
490
499
  /**
@@ -520,17 +529,52 @@ export class SqliteSessionIndex extends SessionIndexBase {
520
529
  readonly #sink: IndexSink
521
530
  readonly #statements = new Map<string, StatementSync>()
522
531
  #open = true
523
- /** The catch-up started by `syncInBackground`; reads wait on it. */
532
+ /** The catch-up started by `syncInBackground`, or on the first read under `syncOnDemand`; reads wait on it. */
524
533
  #catchUp: Promise<void> | undefined
534
+ /** The home a first read catches up with, kept only while the catch-up has not started. */
535
+ #pendingHome: string | undefined
536
+
537
+ /** True while opening promised a catch-up that no read has started yet. */
538
+ get syncPending(): boolean {
539
+ return this.#pendingHome !== undefined
540
+ }
541
+
542
+ /** True while a catch-up is reading the logs. */
543
+ get syncing(): boolean {
544
+ return this.#catchUp !== undefined && !this.#caughtUp
545
+ }
546
+ #caughtUp = false
525
547
 
526
548
  #startBackgroundSync(home: string): void {
527
- this.#catchUp = this.syncNow(home).catch(() => {
528
- // A failed catch-up (the index closed, a log vanished mid-read) leaves the
529
- // rows the last sync wrote; the next open syncs again.
530
- })
549
+ this.#pendingHome = undefined
550
+ this.#catchUp = this.syncNow(home)
551
+ .catch(() => {
552
+ // A failed catch-up (the index closed, a log vanished mid-read) leaves the
553
+ // rows the last sync wrote; the next open syncs again.
554
+ })
555
+ .then(() => {
556
+ this.#caughtUp = true
557
+ })
531
558
  }
532
559
 
533
560
  protected override async settled(): Promise<void> {
561
+ if (this.#pendingHome !== undefined) this.#startBackgroundSync(this.#pendingHome)
562
+ await this.#catchUp
563
+ }
564
+
565
+ /**
566
+ * A read about one session before any catch-up has started: bring that session's
567
+ * rows current from its own log and leave the other logs unread. A session with
568
+ * no row yet has no known log, so that read waits for the whole catch-up.
569
+ */
570
+ protected override async settledFor(sessionId: SessionId | undefined): Promise<void> {
571
+ if (this.#pendingHome === undefined || sessionId === undefined) return this.settled()
572
+ const row = this.readSession(sessionId)
573
+ if (row === undefined) return this.settled()
574
+ await this.refreshNow({ sessionId, slug: row.slug, logPath: row.logPath })
575
+ }
576
+
577
+ protected override async settledForWrite(): Promise<void> {
534
578
  await this.#catchUp
535
579
  }
536
580
 
@@ -740,7 +784,9 @@ export class SqliteSessionIndex extends SessionIndexBase {
740
784
  try {
741
785
  configure(db)
742
786
  db.exec(`BEGIN IMMEDIATE; ${SCHEMA} COMMIT;`)
743
- for (const log of await discoverSessionLogs(options.home)) await index.refresh(log)
787
+ if (options.empty !== true) {
788
+ for (const log of await discoverSessionLogs(options.home)) await index.refresh(log)
789
+ }
744
790
  } finally {
745
791
  index.close()
746
792
  }
@@ -764,7 +810,9 @@ export class SqliteSessionIndex extends SessionIndexBase {
764
810
  if (indexVersion(options.path) !== SESSION_INDEX_VERSION) {
765
811
  // Not forced: if another process renames a current index into place
766
812
  // first, this one discards its own and opens that one.
767
- await SqliteSessionIndex.rebuild(options)
813
+ await SqliteSessionIndex.rebuild(
814
+ options.syncOnDemand === true ? { ...options, empty: true } : options,
815
+ )
768
816
  } else {
769
817
  await sweepAbandonedRebuilds(options.path)
770
818
  }
@@ -780,7 +828,8 @@ export class SqliteSessionIndex extends SessionIndexBase {
780
828
  throw error
781
829
  }
782
830
  const index = new SqliteSessionIndex(db, options.path)
783
- if (options.syncInBackground === true) index.#startBackgroundSync(options.home)
831
+ if (options.syncOnDemand === true) index.#pendingHome = options.home
832
+ else if (options.syncInBackground === true) index.#startBackgroundSync(options.home)
784
833
  else await index.sync(options.home)
785
834
  return index
786
835
  }
@@ -885,7 +934,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
885
934
  }
886
935
 
887
936
  async listTurns(sessionId: SessionId): Promise<IndexedTurn[]> {
888
- await this.settled()
937
+ await this.settledFor(sessionId)
889
938
  return this.#all(
890
939
  'SELECT * FROM turns WHERE session_id = ? ORDER BY started_at, id',
891
940
  sessionId,
@@ -893,7 +942,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
893
942
  }
894
943
 
895
944
  async listChildren(sessionId: SessionId): Promise<ChildSessionSummary[]> {
896
- await this.settled()
945
+ await this.settledFor(sessionId)
897
946
  return this.#all(
898
947
  'SELECT * FROM children WHERE session_id = ? ORDER BY spawned_at, child_id',
899
948
  sessionId,
@@ -906,7 +955,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
906
955
  async listPendingDecisions(
907
956
  options: { sessionId?: SessionId } = {},
908
957
  ): Promise<IndexedPendingDecision[]> {
909
- await this.settled()
958
+ await this.settledFor(options.sessionId)
910
959
  const rows =
911
960
  options.sessionId === undefined
912
961
  ? this.#all('SELECT * FROM pending_decisions ORDER BY session_id, decision_id')
@@ -934,7 +983,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
934
983
  }
935
984
 
936
985
  async listExternalRefs(sessionId: SessionId): Promise<ExternalRefTarget[]> {
937
- await this.settled()
986
+ await this.settledFor(sessionId)
938
987
  return this.#all(
939
988
  'SELECT * FROM external_refs WHERE session_id = ? ORDER BY protocol, kind, external_id',
940
989
  sessionId,
@@ -942,7 +991,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
942
991
  }
943
992
 
944
993
  async batches(options: { sessionId?: SessionId } = {}): Promise<IndexedBatch[]> {
945
- await this.settled()
994
+ await this.settledFor(options.sessionId)
946
995
  const rows =
947
996
  options.sessionId === undefined
948
997
  ? this.#all('SELECT * FROM batches ORDER BY session_id, batch_id')
@@ -954,7 +1003,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
954
1003
  }
955
1004
 
956
1005
  async searchEvidence(options: EvidenceSearchOptions): Promise<EvidenceHit[]> {
957
- await this.settled()
1006
+ await this.settledFor(options.sessionId)
958
1007
  const match = evidenceMatcher(options)
959
1008
  const narrowing = ftsMatchExpression(options)
960
1009
  const limit = options.limit ?? 100
@@ -44,6 +44,34 @@ function flag(value: unknown): true | undefined {
44
44
  return value === true ? true : undefined
45
45
  }
46
46
 
47
+ /** The person's own words are kept whole well past an ordinary field's bound. */
48
+ const MAX_ANSWER_TEXT = 20_000
49
+
50
+ function answerText(value: unknown): string | undefined {
51
+ return typeof value === 'string' && value.length <= MAX_ANSWER_TEXT ? value : undefined
52
+ }
53
+
54
+ /**
55
+ * The person's own words, cut rather than dropped past the bound: a dropped
56
+ * field would leave an answered row with nothing after its arrow. The model
57
+ * already has the whole text in the tool result; this is what is drawn.
58
+ */
59
+ function ownWords(value: unknown): string | undefined {
60
+ if (typeof value !== 'string') return undefined
61
+ return value.length <= MAX_ANSWER_TEXT ? value : `${value.slice(0, MAX_ANSWER_TEXT - 1)}…`
62
+ }
63
+
64
+ function labels(value: unknown): readonly string[] | undefined {
65
+ if (!Array.isArray(value) || value.length > 50) return undefined
66
+ const out: string[] = []
67
+ for (const item of value) {
68
+ const label = answerText(item)
69
+ if (label === undefined) return undefined
70
+ out.push(label)
71
+ }
72
+ return out
73
+ }
74
+
47
75
  function pick<T extends object>(entries: Record<string, unknown>): T {
48
76
  const out: Record<string, unknown> = {}
49
77
  for (const [key, value] of Object.entries(entries)) if (value !== undefined) out[key] = value
@@ -210,6 +238,42 @@ export function admitToolFacts(value: unknown): ToolFacts | undefined {
210
238
  generatedImage: generated === undefined ? undefined : { prompt: generated },
211
239
  })
212
240
  }
241
+ case 'questions': {
242
+ const outcome =
243
+ value.outcome === 'discussed'
244
+ ? 'discussed'
245
+ : value.outcome === 'answered'
246
+ ? 'answered'
247
+ : undefined
248
+ if (outcome === undefined || !Array.isArray(value.questions)) return undefined
249
+ if (value.questions.length === 0 || value.questions.length > 8) return undefined
250
+ const questions: {
251
+ question: string
252
+ header?: string
253
+ options?: readonly string[]
254
+ picked?: readonly string[]
255
+ freeText?: string
256
+ answered: boolean
257
+ }[] = []
258
+ for (const entry of value.questions) {
259
+ if (!isRecord(entry)) return undefined
260
+ const question = answerText(entry.question)
261
+ if (question === undefined || typeof entry.answered !== 'boolean') return undefined
262
+ const header = answerText(entry.header)
263
+ const options = labels(entry.options)
264
+ const picked = labels(entry.picked)
265
+ const freeText = ownWords(entry.freeText)
266
+ questions.push({
267
+ question,
268
+ ...(header === undefined ? {} : { header }),
269
+ ...(options === undefined ? {} : { options }),
270
+ ...(picked === undefined ? {} : { picked }),
271
+ ...(freeText === undefined ? {} : { freeText }),
272
+ answered: entry.answered,
273
+ })
274
+ }
275
+ return { kind: 'questions', outcome, questions }
276
+ }
213
277
  case 'failure': {
214
278
  const reason = FAILURE_REASONS.find((candidate) => candidate === value.reason)
215
279
  if (reason === undefined) return undefined
@@ -657,6 +657,10 @@ export const GrepTool = defineTool({
657
657
  if ((endState?.ignoredDirectories ?? 0) > 0 && offset === 0) {
658
658
  summary = `${summary}\n${ignoredHint(endState?.ignoredDirectories ?? 0)}`
659
659
  }
660
+ // An empty result a line break in the pattern forced is not evidence that
661
+ // the text is absent, so the pattern is named rather than left to read so.
662
+ const breakHint = totalMatches === 0 ? lineBreakHint(input.pattern, multiline) : undefined
663
+ if (breakHint !== undefined) summary = `${summary}\n${breakHint}`
660
664
  } else if (mode === 'files_with_matches') {
661
665
  body = `Found ${page.length} ${page.length === 1 ? 'file' : 'files'}${paging ? ` (${paging})` : ''}\n${page.join('\n')}`
662
666
  } else if (mode === 'count') {
@@ -721,6 +725,54 @@ function byPath(a: string, b: string): number {
721
725
  return a < b ? -1 : a > b ? 1 : 0
722
726
  }
723
727
 
728
+ /**
729
+ * Whether a pattern is written to match a line break: one in the pattern
730
+ * itself, or an escape that names one, `\n` and `\r` among them. A pattern
731
+ * like that cannot be found inside a single line, and every line is tested on
732
+ * its own while `multiline` is off.
733
+ */
734
+ function patternNeedsLineBreak(pattern: string): boolean {
735
+ for (let index = 0; index < pattern.length; index += 1) {
736
+ const char = pattern[index]
737
+ if (char === '\n' || char === '\r' || char === '\u2028' || char === '\u2029') return true
738
+ if (char === '[' && pattern[index + 1] === '^') {
739
+ // A negated class such as `[^\n]` excludes a line break; it does not ask for one.
740
+ index = skipNegatedClass(pattern, index + 2)
741
+ continue
742
+ }
743
+ if (char !== '\\') continue
744
+ const next = pattern[index + 1]
745
+ // An escaped backslash and the `n` after it are a literal `\n` in the
746
+ // text being searched, so the two are stepped over together.
747
+ if (next === '\\') {
748
+ index += 1
749
+ continue
750
+ }
751
+ if (next === 'n' || next === 'r') return true
752
+ if (next === 'u' && ['2028', '2029'].includes(pattern.slice(index + 2, index + 6))) return true
753
+ }
754
+ return false
755
+ }
756
+
757
+ /** The index of the `]` that closes a negated class whose body starts at `from`, or the end of the pattern. */
758
+ function skipNegatedClass(pattern: string, from: number): number {
759
+ for (let index = from; index < pattern.length; index += 1) {
760
+ if (pattern[index] === '\\') index += 1
761
+ else if (pattern[index] === ']') return index
762
+ }
763
+ return pattern.length
764
+ }
765
+
766
+ /**
767
+ * A sentence for the emptiest of evidence: a pattern that needs a line break,
768
+ * searched one line at a time, can only come back with nothing. Naming the
769
+ * pattern and the flag that changes that is worth more than "no matches".
770
+ */
771
+ function lineBreakHint(pattern: string, multiline: boolean): string | undefined {
772
+ if (multiline || !patternNeedsLineBreak(pattern)) return undefined
773
+ return `The pattern ${JSON.stringify(pattern)} contains a line break, and multiline is off: each line is tested on its own, so a match that spans lines cannot be found. Pass multiline: true to search across lines.`
774
+ }
775
+
724
776
  /**
725
777
  * Newest modification first; ties by path. A file that cannot be stat'ed, and
726
778
  * every file in a sandbox (which reports no modification time), sorts as