@namzu/sdk 71.0.0 → 71.1.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.
- package/CHANGELOG.md +100 -0
- package/dist/authorization/readonly-commands.d.ts +9 -1
- package/dist/authorization/readonly-commands.d.ts.map +1 -1
- package/dist/authorization/readonly-commands.js +70 -4
- package/dist/authorization/readonly-commands.js.map +1 -1
- package/dist/authorization/shell-paths.d.ts.map +1 -1
- package/dist/authorization/shell-paths.js +68 -16
- package/dist/authorization/shell-paths.js.map +1 -1
- package/dist/compaction/model-summary.d.ts.map +1 -1
- package/dist/compaction/model-summary.js +44 -5
- package/dist/compaction/model-summary.js.map +1 -1
- package/dist/config/registry.d.ts +2 -0
- package/dist/config/registry.d.ts.map +1 -1
- package/dist/config/registry.js +76 -5
- package/dist/config/registry.js.map +1 -1
- package/dist/connector/mcp/adapter.d.ts +8 -0
- package/dist/connector/mcp/adapter.d.ts.map +1 -1
- package/dist/connector/mcp/adapter.js +131 -1
- package/dist/connector/mcp/adapter.js.map +1 -1
- package/dist/connector/mcp/stdio.d.ts +12 -0
- package/dist/connector/mcp/stdio.d.ts.map +1 -1
- package/dist/connector/mcp/stdio.js +49 -5
- package/dist/connector/mcp/stdio.js.map +1 -1
- package/dist/constants/mcp/index.d.ts +29 -0
- package/dist/constants/mcp/index.d.ts.map +1 -1
- package/dist/constants/mcp/index.js +29 -0
- package/dist/constants/mcp/index.js.map +1 -1
- package/dist/manager/agent/lifecycle.d.ts +18 -1
- package/dist/manager/agent/lifecycle.d.ts.map +1 -1
- package/dist/manager/agent/lifecycle.js +52 -7
- package/dist/manager/agent/lifecycle.js.map +1 -1
- package/dist/plugin/index.d.ts +1 -1
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js.map +1 -1
- package/dist/plugin/shell-hook.d.ts +44 -2
- package/dist/plugin/shell-hook.d.ts.map +1 -1
- package/dist/plugin/shell-hook.js +74 -5
- package/dist/plugin/shell-hook.js.map +1 -1
- package/dist/public-runtime.d.ts +2 -2
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +1 -1
- package/dist/public-runtime.js.map +1 -1
- package/dist/public-types.d.ts +2 -2
- package/dist/public-types.d.ts.map +1 -1
- package/dist/runtime/query/path-escalation.d.ts.map +1 -1
- package/dist/runtime/query/path-escalation.js +90 -17
- package/dist/runtime/query/path-escalation.js.map +1 -1
- package/dist/runtime/query/steering.d.ts +15 -0
- package/dist/runtime/query/steering.d.ts.map +1 -1
- package/dist/runtime/query/steering.js +27 -3
- package/dist/runtime/query/steering.js.map +1 -1
- package/dist/session/workspace/driver.d.ts +12 -0
- package/dist/session/workspace/driver.d.ts.map +1 -1
- package/dist/session/workspace/git-worktree.d.ts +16 -0
- package/dist/session/workspace/git-worktree.d.ts.map +1 -1
- package/dist/session/workspace/git-worktree.js +35 -0
- package/dist/session/workspace/git-worktree.js.map +1 -1
- package/dist/session/workspace/holds.d.ts +78 -0
- package/dist/session/workspace/holds.d.ts.map +1 -0
- package/dist/session/workspace/holds.js +150 -0
- package/dist/session/workspace/holds.js.map +1 -0
- package/dist/session/workspace/index.d.ts +3 -1
- package/dist/session/workspace/index.d.ts.map +1 -1
- package/dist/session/workspace/index.js +2 -1
- package/dist/session/workspace/index.js.map +1 -1
- package/dist/store/config/index.d.ts +3 -0
- package/dist/store/config/index.d.ts.map +1 -1
- package/dist/store/config/index.js +3 -0
- package/dist/store/config/index.js.map +1 -1
- package/dist/store/session-index/index.d.ts +5 -0
- package/dist/store/session-index/index.d.ts.map +1 -1
- package/dist/store/session-index/index.js +5 -1
- package/dist/store/session-index/index.js.map +1 -1
- package/dist/store/session-index/rebuild.d.ts +18 -0
- package/dist/store/session-index/rebuild.d.ts.map +1 -1
- package/dist/store/session-index/rebuild.js +79 -5
- package/dist/store/session-index/rebuild.js.map +1 -1
- package/dist/store/session-index/sqlite.d.ts +8 -0
- package/dist/store/session-index/sqlite.d.ts.map +1 -1
- package/dist/store/session-index/sqlite.js +23 -1
- package/dist/store/session-index/sqlite.js.map +1 -1
- package/dist/tools/builtins/grep.d.ts.map +1 -1
- package/dist/tools/builtins/grep.js +57 -0
- package/dist/tools/builtins/grep.js.map +1 -1
- package/dist/tools/builtins/lsp.d.ts.map +1 -1
- package/dist/tools/builtins/lsp.js +41 -4
- package/dist/tools/builtins/lsp.js.map +1 -1
- package/dist/types/code-navigation/index.d.ts +34 -4
- package/dist/types/code-navigation/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/authorization/readonly-commands.ts +72 -4
- package/src/authorization/shell-paths.ts +75 -18
- package/src/compaction/model-summary.ts +45 -5
- package/src/config/registry.ts +87 -5
- package/src/connector/mcp/adapter.ts +137 -1
- package/src/connector/mcp/stdio.ts +56 -5
- package/src/constants/mcp/index.ts +31 -0
- package/src/manager/agent/lifecycle.ts +57 -12
- package/src/plugin/index.ts +3 -0
- package/src/plugin/shell-hook.ts +131 -6
- package/src/public-runtime.ts +5 -0
- package/src/public-types.ts +7 -0
- package/src/runtime/query/path-escalation.ts +102 -16
- package/src/runtime/query/steering.ts +38 -3
- package/src/session/workspace/driver.ts +12 -0
- package/src/session/workspace/git-worktree.ts +49 -0
- package/src/session/workspace/holds.ts +201 -0
- package/src/session/workspace/index.ts +13 -1
- package/src/store/config/index.ts +6 -0
- package/src/store/session-index/index.ts +10 -1
- package/src/store/session-index/rebuild.ts +81 -5
- package/src/store/session-index/sqlite.ts +30 -1
- package/src/tools/builtins/grep.ts +52 -0
- package/src/tools/builtins/lsp.ts +47 -4
- package/src/types/code-navigation/index.ts +48 -4
|
@@ -120,6 +120,28 @@ export class SteeringBinding implements SteeringChannel {
|
|
|
120
120
|
*/
|
|
121
121
|
export const JOB_NOTICE_INLINE_OUTPUT_MAX_BYTES = 2048
|
|
122
122
|
|
|
123
|
+
/**
|
|
124
|
+
* The most of a job's command line an exit notice quotes. The notice is
|
|
125
|
+
* carried into every later session that learns the job ended, so an unbounded
|
|
126
|
+
* command would be pasted into each of them; the whole line stays in the job's
|
|
127
|
+
* own record, which the job tool lists.
|
|
128
|
+
*/
|
|
129
|
+
export const JOB_NOTICE_COMMAND_MAX_CHARS = 300
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* A job's command as its exit notice quotes it: the whole of it when it fits
|
|
133
|
+
* {@link JOB_NOTICE_COMMAND_MAX_CHARS}, otherwise its first and last stretch
|
|
134
|
+
* with the number of characters left out between them — the same head-and-tail
|
|
135
|
+
* summary a value is cut with elsewhere in the kernel. The full line is not
|
|
136
|
+
* lost, only the notice does not carry it.
|
|
137
|
+
*/
|
|
138
|
+
export function boundJobNoticeCommand(
|
|
139
|
+
command: string,
|
|
140
|
+
max: number = JOB_NOTICE_COMMAND_MAX_CHARS,
|
|
141
|
+
): string {
|
|
142
|
+
return cutMiddle(command, max, inlineCutMarker)
|
|
143
|
+
}
|
|
144
|
+
|
|
123
145
|
/**
|
|
124
146
|
* One job's exit as the text the model reads. The output is inlined only when
|
|
125
147
|
* the whole of it fits {@link JOB_NOTICE_INLINE_OUTPUT_MAX_BYTES} and none was
|
|
@@ -145,7 +167,7 @@ export function formatJobExitNotice(
|
|
|
145
167
|
? ` after ${formatMonitorDuration(Math.max(0, job.exitedAt - job.startedAt))}`
|
|
146
168
|
: ''
|
|
147
169
|
const saved = job.outputFile === undefined ? '' : ` Its output is saved to ${job.outputFile}.`
|
|
148
|
-
const head = `Background job ${job.id} (${job.command}) ${outcome}${endedAt}${ran}.${saved}`
|
|
170
|
+
const head = `Background job ${job.id} (${boundJobNoticeCommand(job.command)}) ${outcome}${endedAt}${ran}.${saved}`
|
|
149
171
|
if (
|
|
150
172
|
output === undefined ||
|
|
151
173
|
output.chunk.length === 0 ||
|
|
@@ -334,9 +356,22 @@ export function capMonitorContent(
|
|
|
334
356
|
return text.length <= max ? text : cutMiddle(text, max)
|
|
335
357
|
}
|
|
336
358
|
|
|
337
|
-
|
|
359
|
+
/** The cut a multi-line block gets: the marker stands on a line of its own. */
|
|
360
|
+
function multilineCutMarker(omitted: number): string {
|
|
361
|
+
return `\n...[${omitted} characters omitted]...\n`
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The cut a value inside a line gets: no newline, so the line stays one line. */
|
|
365
|
+
function inlineCutMarker(omitted: number): string {
|
|
366
|
+
return `…[${omitted} characters omitted]…`
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function cutMiddle(
|
|
370
|
+
text: string,
|
|
371
|
+
max: number,
|
|
372
|
+
marker: (omitted: number) => string = multilineCutMarker,
|
|
373
|
+
): string {
|
|
338
374
|
if (text.length <= max) return text
|
|
339
|
-
const marker = (omitted: number) => `\n...[${omitted} characters omitted]...\n`
|
|
340
375
|
// Reserve room for the marker itself so the result never exceeds `max`.
|
|
341
376
|
const room = Math.max(0, max - marker(text.length).length)
|
|
342
377
|
const head = Math.ceil(room / 2)
|
|
@@ -69,6 +69,18 @@ export interface WorkspaceBackendDriver {
|
|
|
69
69
|
branch(source: WorkspaceRef, params: BranchWorkspaceParams): Promise<WorkspaceRef>
|
|
70
70
|
dispose(ref: WorkspaceRef): Promise<void>
|
|
71
71
|
inspect(ref: WorkspaceRef): Promise<WorkspaceInspection>
|
|
72
|
+
/**
|
|
73
|
+
* The child that worked in `ref` has ended: let go of whatever claim this
|
|
74
|
+
* driver still makes on that checkout, whether or not the checkout is kept.
|
|
75
|
+
*
|
|
76
|
+
* A checkout provisioned with `retain`, or with `retain-changed` when the
|
|
77
|
+
* child left something behind, is never passed to {@link dispose}, so without
|
|
78
|
+
* this the backend would go on reporting a checkout as in use by a session
|
|
79
|
+
* that has already finished. A driver that claims nothing can leave it out.
|
|
80
|
+
*
|
|
81
|
+
* Called on every terminal path of a child, before the retention decision.
|
|
82
|
+
*/
|
|
83
|
+
release?(ref: WorkspaceRef): Promise<void>
|
|
72
84
|
}
|
|
73
85
|
|
|
74
86
|
export type { WorkspaceBackendKind } from '../../types/workspace/ref.js'
|
|
@@ -31,6 +31,12 @@ import type {
|
|
|
31
31
|
WorkspaceBackendDriver,
|
|
32
32
|
WorkspaceInspection,
|
|
33
33
|
} from './driver.js'
|
|
34
|
+
import {
|
|
35
|
+
DiskWorkspaceHoldStore,
|
|
36
|
+
type WorkspaceHold,
|
|
37
|
+
type WorkspaceHoldStore,
|
|
38
|
+
WorkspaceInUseError,
|
|
39
|
+
} from './holds.js'
|
|
34
40
|
|
|
35
41
|
const execFileAsync = promisify(execFile)
|
|
36
42
|
|
|
@@ -75,6 +81,12 @@ export interface GitWorktreeDriverConfig {
|
|
|
75
81
|
branchPrefix?: string
|
|
76
82
|
/** Test-seam: inject a stub `execFile` implementation. */
|
|
77
83
|
execFile?: ExecFile
|
|
84
|
+
/**
|
|
85
|
+
* Who is working in a checkout right now. `dispose` asks it before removing
|
|
86
|
+
* anything and refuses a path a live session or subagent still has. Absent,
|
|
87
|
+
* the machine's own hold directory is read.
|
|
88
|
+
*/
|
|
89
|
+
holds?: WorkspaceHoldStore
|
|
78
90
|
}
|
|
79
91
|
|
|
80
92
|
const DEFAULT_BRANCH_PREFIX = 'namzu'
|
|
@@ -97,12 +109,14 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
|
|
|
97
109
|
private readonly log: Logger
|
|
98
110
|
private readonly exec: ExecFile
|
|
99
111
|
private readonly branchPrefix: string
|
|
112
|
+
private readonly holds: WorkspaceHoldStore
|
|
100
113
|
|
|
101
114
|
constructor(config: GitWorktreeDriverConfig) {
|
|
102
115
|
this.repoRoot = resolve(config.repoRoot)
|
|
103
116
|
this.worktreesDir = resolve(config.worktreesDir ?? defaultWorktreesDir(config.repoRoot))
|
|
104
117
|
this.log = config.logger.child({ [SCOPE_ATTRIBUTE]: 'session/workspace/git-worktree' })
|
|
105
118
|
this.exec = config.execFile ?? defaultExecFile
|
|
119
|
+
this.holds = config.holds ?? new DiskWorkspaceHoldStore()
|
|
106
120
|
const prefix = config.branchPrefix ?? DEFAULT_BRANCH_PREFIX
|
|
107
121
|
if (!isBranchPrefix(prefix)) {
|
|
108
122
|
throw new Error(
|
|
@@ -221,6 +235,20 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
|
|
|
221
235
|
return
|
|
222
236
|
}
|
|
223
237
|
|
|
238
|
+
// A checkout another live process has open is not this call's to remove:
|
|
239
|
+
// `worktree remove --force` would take that process's uncommitted files
|
|
240
|
+
// with it. The refusal names the folder asked for and every folder its
|
|
241
|
+
// holders work in, so a person can see which session to close.
|
|
242
|
+
const holders = await this.liveHolders(owned.worktreePath)
|
|
243
|
+
if (holders.length > 0) {
|
|
244
|
+
this.log.info('git-worktree kept; another session has it', {
|
|
245
|
+
[NAMZU.SESSION_ID]: ref.id,
|
|
246
|
+
'namzu.session.path': owned.worktreePath,
|
|
247
|
+
'namzu.session.holder_count': holders.length,
|
|
248
|
+
})
|
|
249
|
+
throw new WorkspaceInUseError(owned.worktreePath, holders)
|
|
250
|
+
}
|
|
251
|
+
|
|
224
252
|
// Tolerate missing directories per roadmap Risk #3 mitigation: the
|
|
225
253
|
// broadcast-rollback compensating step calls dispose on partially
|
|
226
254
|
// provisioned refs and must not propagate "already gone" errors. The
|
|
@@ -276,6 +304,27 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
|
|
|
276
304
|
}
|
|
277
305
|
}
|
|
278
306
|
|
|
307
|
+
/**
|
|
308
|
+
* Who is working in `worktreePath` right now.
|
|
309
|
+
*
|
|
310
|
+
* A hold store that cannot be read is not a "nobody": answering that on a
|
|
311
|
+
* guess is how an in-use checkout gets deleted, so it refuses the removal
|
|
312
|
+
* and says what it could not read.
|
|
313
|
+
*/
|
|
314
|
+
private async liveHolders(worktreePath: string): Promise<readonly WorkspaceHold[]> {
|
|
315
|
+
try {
|
|
316
|
+
return await this.holds.holders(worktreePath)
|
|
317
|
+
} catch (cause) {
|
|
318
|
+
throw new WorkspaceBackendError({
|
|
319
|
+
op: 'dispose:holders',
|
|
320
|
+
kind: this.kind,
|
|
321
|
+
cause: new Error(
|
|
322
|
+
`The worktree ${worktreePath} was not removed: Namzu could not read who is working in it (${cause instanceof Error ? cause.message : String(cause)}).`,
|
|
323
|
+
),
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
279
328
|
/**
|
|
280
329
|
* Did the worktree arrive despite the command reporting failure?
|
|
281
330
|
*
|
|
@@ -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 {
|
|
@@ -211,6 +211,11 @@ export interface OpenSessionIndexOptions {
|
|
|
211
211
|
readonly path?: string
|
|
212
212
|
/** `auto` (the default) uses SQLite when `node:sqlite` loads, the scan index otherwise. */
|
|
213
213
|
readonly backend?: 'auto' | 'sqlite' | 'scan'
|
|
214
|
+
/**
|
|
215
|
+
* SQLite only: return once the index is open and current in version, and
|
|
216
|
+
* catch up with the logs in the background; every read waits for it.
|
|
217
|
+
*/
|
|
218
|
+
readonly syncInBackground?: boolean
|
|
214
219
|
}
|
|
215
220
|
|
|
216
221
|
/**
|
|
@@ -225,7 +230,11 @@ export async function openSessionIndex(
|
|
|
225
230
|
if (backend === 'scan' || (backend === 'auto' && !sqliteAvailable())) {
|
|
226
231
|
return ScanSessionIndex.load(home)
|
|
227
232
|
}
|
|
228
|
-
return SqliteSessionIndex.open({
|
|
233
|
+
return SqliteSessionIndex.open({
|
|
234
|
+
home,
|
|
235
|
+
path: options.path ?? join(home, 'index.sqlite'),
|
|
236
|
+
...(options.syncInBackground === true ? { syncInBackground: true } : {}),
|
|
237
|
+
})
|
|
229
238
|
}
|
|
230
239
|
|
|
231
240
|
export { EvidenceQueryError, evidenceMatcher, evidenceTexts, ftsMatchExpression } from './fts.js'
|
|
@@ -204,7 +204,46 @@ export async function discoverSessionLogs(home: string): Promise<SessionLogLocat
|
|
|
204
204
|
await collectLogs(join(projects, entry.name), entry.name, found, 0)
|
|
205
205
|
}
|
|
206
206
|
found.sort((a, b) => (a.logPath < b.logPath ? -1 : a.logPath > b.logPath ? 1 : 0))
|
|
207
|
-
return found
|
|
207
|
+
return await onePerSession(found)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The index keys a row by session id, so two logs with one id (a session
|
|
212
|
+
* folder copied into another project) would each overwrite the other's row on
|
|
213
|
+
* every sync and never settle. One log speaks for an id: the one written last,
|
|
214
|
+
* the first by path on a tie. A pure function of the files, so a rebuild and an
|
|
215
|
+
* incremental sync agree and a second sync of an unchanged home reads nothing;
|
|
216
|
+
* the copy that is written to next becomes the one listed.
|
|
217
|
+
*/
|
|
218
|
+
async function onePerSession(found: SessionLogLocation[]): Promise<SessionLogLocation[]> {
|
|
219
|
+
const byId = new Map<string, SessionLogLocation[]>()
|
|
220
|
+
for (const log of found) {
|
|
221
|
+
const group = byId.get(log.sessionId)
|
|
222
|
+
if (group === undefined) byId.set(log.sessionId, [log])
|
|
223
|
+
else group.push(log)
|
|
224
|
+
}
|
|
225
|
+
if (byId.size === found.length) return found
|
|
226
|
+
const chosen = new Set<SessionLogLocation>()
|
|
227
|
+
for (const group of byId.values()) {
|
|
228
|
+
let best = group[0] as SessionLogLocation
|
|
229
|
+
if (group.length > 1) {
|
|
230
|
+
let bestWritten = -1
|
|
231
|
+
for (const log of group) {
|
|
232
|
+
let written = -1
|
|
233
|
+
try {
|
|
234
|
+
written = (await stat(log.logPath)).mtimeMs
|
|
235
|
+
} catch {
|
|
236
|
+
// Gone since the walk; it loses to any log that is still there.
|
|
237
|
+
}
|
|
238
|
+
if (written > bestWritten) {
|
|
239
|
+
best = log
|
|
240
|
+
bestWritten = written
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
chosen.add(best)
|
|
245
|
+
}
|
|
246
|
+
return found.filter((log) => chosen.has(log))
|
|
208
247
|
}
|
|
209
248
|
|
|
210
249
|
// ─── rows ──────────────────────────────────────────────────────────────────
|
|
@@ -701,12 +740,37 @@ export abstract class SessionIndexBase implements SessionIndex {
|
|
|
701
740
|
abstract searchEvidence(options: EvidenceSearchOptions): Promise<EvidenceHit[]>
|
|
702
741
|
abstract close(): void
|
|
703
742
|
|
|
743
|
+
/** Resolves once the index reflects the logs. A backend that syncs after opening overrides it. */
|
|
744
|
+
protected settled(): Promise<void> {
|
|
745
|
+
return Promise.resolve()
|
|
746
|
+
}
|
|
747
|
+
|
|
704
748
|
async getSession(sessionId: SessionId): Promise<IndexedSession | undefined> {
|
|
749
|
+
await this.settled()
|
|
750
|
+
return this.sessionNow(sessionId)
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/**
|
|
754
|
+
* {@link getSession} without waiting for the catch-up. Anything the catch-up
|
|
755
|
+
* itself calls must read this way: waiting there would wait on itself.
|
|
756
|
+
*/
|
|
757
|
+
protected sessionNow(sessionId: SessionId): IndexedSession | undefined {
|
|
705
758
|
const row = this.readSession(sessionId)
|
|
706
759
|
return row === undefined ? undefined : sessionView(row)
|
|
707
760
|
}
|
|
708
761
|
|
|
762
|
+
/**
|
|
763
|
+
* Writes wait for a background catch-up as reads do: a catch-up that reads a
|
|
764
|
+
* log while its first record is being written finds no intact record and
|
|
765
|
+
* clears the row, so a write that ran beside it could be undone.
|
|
766
|
+
*/
|
|
709
767
|
async indexSession(input: SessionLogInput): Promise<IndexedSession | undefined> {
|
|
768
|
+
await this.settled()
|
|
769
|
+
return this.indexSessionNow(input)
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/** {@link indexSession} without waiting for the catch-up; the catch-up's own path. */
|
|
773
|
+
protected async indexSessionNow(input: SessionLogInput): Promise<IndexedSession | undefined> {
|
|
710
774
|
const location = { slug: input.slug, logPath: input.logPath }
|
|
711
775
|
let batch: IndexableRecord[] = []
|
|
712
776
|
let first = true
|
|
@@ -789,12 +853,12 @@ export abstract class SessionIndexBase implements SessionIndex {
|
|
|
789
853
|
batch.push(item)
|
|
790
854
|
if (batch.length >= RECORDS_PER_TRANSACTION && !flush()) {
|
|
791
855
|
// Another writer advanced this session past us; its rows are the same records'.
|
|
792
|
-
return this.
|
|
856
|
+
return this.sessionNow(sessionId)
|
|
793
857
|
}
|
|
794
858
|
}
|
|
795
859
|
// A final batch that stands down leaves the other writer's rows, which are the answer.
|
|
796
860
|
flush()
|
|
797
|
-
return sessionId === undefined ? undefined : this.
|
|
861
|
+
return sessionId === undefined ? undefined : this.sessionNow(sessionId)
|
|
798
862
|
}
|
|
799
863
|
|
|
800
864
|
async staleness(location: SessionLogLocation): Promise<SessionStaleness> {
|
|
@@ -818,6 +882,12 @@ export abstract class SessionIndexBase implements SessionIndex {
|
|
|
818
882
|
}
|
|
819
883
|
|
|
820
884
|
async refresh(location: SessionLogLocation): Promise<SessionStaleness> {
|
|
885
|
+
await this.settled()
|
|
886
|
+
return this.refreshNow(location)
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** {@link refresh} without waiting for the catch-up; the catch-up's own path. */
|
|
890
|
+
protected async refreshNow(location: SessionLogLocation): Promise<SessionStaleness> {
|
|
821
891
|
const state = await this.staleness(location)
|
|
822
892
|
if (state === 'fresh') return state
|
|
823
893
|
if (state === 'missing') {
|
|
@@ -829,7 +899,7 @@ export abstract class SessionIndexBase implements SessionIndex {
|
|
|
829
899
|
row === undefined
|
|
830
900
|
? undefined
|
|
831
901
|
: { offset: row.logBytes, seq: row.headSeq, sha256: row.headSha256 }
|
|
832
|
-
const indexed = await this.
|
|
902
|
+
const indexed = await this.indexSessionNow({
|
|
833
903
|
slug: location.slug,
|
|
834
904
|
logPath: location.logPath,
|
|
835
905
|
records: readIndexableRecords(location.logPath, from),
|
|
@@ -842,11 +912,17 @@ export abstract class SessionIndexBase implements SessionIndex {
|
|
|
842
912
|
}
|
|
843
913
|
|
|
844
914
|
async sync(home: string): Promise<void> {
|
|
915
|
+
await this.settled()
|
|
916
|
+
return this.syncNow(home)
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** {@link sync} without waiting for the catch-up; the catch-up itself. */
|
|
920
|
+
protected async syncNow(home: string): Promise<void> {
|
|
845
921
|
const logs = await discoverSessionLogs(home)
|
|
846
922
|
const present = new Set<string>()
|
|
847
923
|
for (const log of logs) {
|
|
848
924
|
present.add(log.sessionId)
|
|
849
|
-
await this.
|
|
925
|
+
await this.refreshNow(log)
|
|
850
926
|
}
|
|
851
927
|
const gone = this.indexedSessionIds().filter((id) => !present.has(id))
|
|
852
928
|
if (gone.length > 0) {
|
|
@@ -470,6 +470,13 @@ export interface SqliteSessionIndexOptions {
|
|
|
470
470
|
readonly path: string
|
|
471
471
|
/** The home whose logs the index describes. */
|
|
472
472
|
readonly home: string
|
|
473
|
+
/**
|
|
474
|
+
* Return once the index is open and its version is current, and catch up
|
|
475
|
+
* with the logs in the background. Every read waits for that catch-up, so
|
|
476
|
+
* a listing, a search or a lookup still sees the synced index; opening no
|
|
477
|
+
* longer waits on a home with thousands of logs.
|
|
478
|
+
*/
|
|
479
|
+
readonly syncInBackground?: boolean
|
|
473
480
|
}
|
|
474
481
|
|
|
475
482
|
export interface RebuildSqliteSessionIndexOptions extends SqliteSessionIndexOptions {
|
|
@@ -513,6 +520,19 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
513
520
|
readonly #sink: IndexSink
|
|
514
521
|
readonly #statements = new Map<string, StatementSync>()
|
|
515
522
|
#open = true
|
|
523
|
+
/** The catch-up started by `syncInBackground`; reads wait on it. */
|
|
524
|
+
#catchUp: Promise<void> | undefined
|
|
525
|
+
|
|
526
|
+
#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
|
+
})
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
protected override async settled(): Promise<void> {
|
|
534
|
+
await this.#catchUp
|
|
535
|
+
}
|
|
516
536
|
|
|
517
537
|
/** Wraps an open database whose schema is current. Use {@link SqliteSessionIndex.open}. */
|
|
518
538
|
private constructor(db: DatabaseSync, path?: string) {
|
|
@@ -760,7 +780,8 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
760
780
|
throw error
|
|
761
781
|
}
|
|
762
782
|
const index = new SqliteSessionIndex(db, options.path)
|
|
763
|
-
|
|
783
|
+
if (options.syncInBackground === true) index.#startBackgroundSync(options.home)
|
|
784
|
+
else await index.sync(options.home)
|
|
764
785
|
return index
|
|
765
786
|
}
|
|
766
787
|
|
|
@@ -848,6 +869,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
848
869
|
}
|
|
849
870
|
|
|
850
871
|
async listSessions(options: ListSessionsOptions = {}): Promise<IndexedSession[]> {
|
|
872
|
+
await this.settled()
|
|
851
873
|
const where: string[] = []
|
|
852
874
|
const values: SQLInputValue[] = []
|
|
853
875
|
if (options.slug !== undefined) {
|
|
@@ -863,6 +885,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
863
885
|
}
|
|
864
886
|
|
|
865
887
|
async listTurns(sessionId: SessionId): Promise<IndexedTurn[]> {
|
|
888
|
+
await this.settled()
|
|
866
889
|
return this.#all(
|
|
867
890
|
'SELECT * FROM turns WHERE session_id = ? ORDER BY started_at, id',
|
|
868
891
|
sessionId,
|
|
@@ -870,6 +893,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
870
893
|
}
|
|
871
894
|
|
|
872
895
|
async listChildren(sessionId: SessionId): Promise<ChildSessionSummary[]> {
|
|
896
|
+
await this.settled()
|
|
873
897
|
return this.#all(
|
|
874
898
|
'SELECT * FROM children WHERE session_id = ? ORDER BY spawned_at, child_id',
|
|
875
899
|
sessionId,
|
|
@@ -882,6 +906,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
882
906
|
async listPendingDecisions(
|
|
883
907
|
options: { sessionId?: SessionId } = {},
|
|
884
908
|
): Promise<IndexedPendingDecision[]> {
|
|
909
|
+
await this.settled()
|
|
885
910
|
const rows =
|
|
886
911
|
options.sessionId === undefined
|
|
887
912
|
? this.#all('SELECT * FROM pending_decisions ORDER BY session_id, decision_id')
|
|
@@ -897,6 +922,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
897
922
|
kind: ExternalRefKind,
|
|
898
923
|
externalId: string,
|
|
899
924
|
): Promise<ExternalRefTarget | undefined> {
|
|
925
|
+
await this.settled()
|
|
900
926
|
this.#reopenIfReplaced()
|
|
901
927
|
const row = this.#db
|
|
902
928
|
.prepare(
|
|
@@ -908,6 +934,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
908
934
|
}
|
|
909
935
|
|
|
910
936
|
async listExternalRefs(sessionId: SessionId): Promise<ExternalRefTarget[]> {
|
|
937
|
+
await this.settled()
|
|
911
938
|
return this.#all(
|
|
912
939
|
'SELECT * FROM external_refs WHERE session_id = ? ORDER BY protocol, kind, external_id',
|
|
913
940
|
sessionId,
|
|
@@ -915,6 +942,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
915
942
|
}
|
|
916
943
|
|
|
917
944
|
async batches(options: { sessionId?: SessionId } = {}): Promise<IndexedBatch[]> {
|
|
945
|
+
await this.settled()
|
|
918
946
|
const rows =
|
|
919
947
|
options.sessionId === undefined
|
|
920
948
|
? this.#all('SELECT * FROM batches ORDER BY session_id, batch_id')
|
|
@@ -926,6 +954,7 @@ export class SqliteSessionIndex extends SessionIndexBase {
|
|
|
926
954
|
}
|
|
927
955
|
|
|
928
956
|
async searchEvidence(options: EvidenceSearchOptions): Promise<EvidenceHit[]> {
|
|
957
|
+
await this.settled()
|
|
929
958
|
const match = evidenceMatcher(options)
|
|
930
959
|
const narrowing = ftsMatchExpression(options)
|
|
931
960
|
const limit = options.limit ?? 100
|