@north-light/crouter 0.3.174 → 0.3.176

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 (64) hide show
  1. package/dist/api/dto/nodes.d.ts +7 -1
  2. package/dist/api/dto/profiles.d.ts +3 -0
  3. package/dist/clients/attach/render/crtr-output.d.ts +3 -3
  4. package/dist/clients/attach/render/crtr-output.js +25 -13
  5. package/dist/clients/attach/viewer.js +531 -561
  6. package/dist/commands/memory/write.js +13 -12
  7. package/dist/commands/node/create.js +7 -3
  8. package/dist/commands/profile/list.js +3 -1
  9. package/dist/commands/profile/new.js +4 -1
  10. package/dist/commands/profile/project.js +23 -9
  11. package/dist/commands/profile/show.js +3 -1
  12. package/dist/commands/profile.js +2 -2
  13. package/dist/commands/sys/logs.js +4 -2
  14. package/dist/core/__tests__/branded-host-concurrency.test.js +1 -1
  15. package/dist/core/__tests__/on-read-crouter-home-fence.test.js +1 -1
  16. package/dist/core/__tests__/on-read-dedup-resume.test.js +1 -1
  17. package/dist/core/canvas/extensions.d.ts +1 -1
  18. package/dist/core/canvas/extensions.js +7 -1
  19. package/dist/core/command-plugins/transport/http-invoke.js +10 -2
  20. package/dist/core/command.js +3 -1
  21. package/dist/core/config.js +4 -27
  22. package/dist/core/exclusive-lock.d.ts +14 -0
  23. package/dist/core/exclusive-lock.js +124 -0
  24. package/dist/core/human/claim.js +2 -1
  25. package/dist/core/human/convention.d.ts +0 -10
  26. package/dist/core/human/convention.js +1 -123
  27. package/dist/core/io.d.ts +23 -0
  28. package/dist/core/io.js +60 -0
  29. package/dist/core/preview-registry.d.ts +10 -5
  30. package/dist/core/preview-registry.js +136 -2537
  31. package/dist/core/profiles/manifest.d.ts +12 -1
  32. package/dist/core/profiles/manifest.js +57 -48
  33. package/dist/core/review/store.d.ts +4 -1
  34. package/dist/core/review/store.js +10 -0
  35. package/dist/core/runtime/branded-host.js +6 -84
  36. package/dist/core/runtime/broker-extension-render.js +1 -1
  37. package/dist/core/runtime/canvas-extensions.d.ts +1 -0
  38. package/dist/core/runtime/canvas-extensions.js +2 -0
  39. package/dist/core/runtime/tmux-bindings.js +1 -1
  40. package/dist/core/runtime/warm-pool.d.ts +9 -8
  41. package/dist/core/runtime/warm-pool.js +58 -62
  42. package/dist/core/substrate/index.d.ts +2 -1
  43. package/dist/core/substrate/index.js +2 -1
  44. package/dist/core/substrate/on-read-node.d.ts +7 -0
  45. package/dist/core/substrate/on-read-node.js +37 -0
  46. package/dist/core/substrate/on-read.d.ts +7 -5
  47. package/dist/core/substrate/on-read.js +15 -23
  48. package/dist/core/termrender/termrender.js +16 -96
  49. package/dist/core/worktree.js +11 -100
  50. package/dist/daemon/api/handlers/nodes.js +32 -9
  51. package/dist/daemon/api/handlers/review-comments.js +5 -44
  52. package/dist/daemon/api/handlers/reviews.js +5 -53
  53. package/dist/daemon/api/handlers/validate.d.ts +22 -0
  54. package/dist/daemon/api/handlers/validate.js +59 -0
  55. package/dist/daemon/api/map.js +1 -0
  56. package/dist/daemon/review/finish.js +1 -10
  57. package/dist/pi-extensions/canvas-doc-substrate.js +1 -1
  58. package/dist/pi-extensions/canvas-preview-result.d.ts +22 -0
  59. package/dist/pi-extensions/canvas-preview-result.js +60 -0
  60. package/dist/types.d.ts +4 -0
  61. package/package.json +1 -1
  62. package/runtime.lock.json +2 -2
  63. package/dist/core/substrate/on-read-pure.d.ts +0 -7
  64. package/dist/core/substrate/on-read-pure.js +0 -272
@@ -9,23 +9,24 @@ import { MEMORY_KINDS, MEMORY_SCOPES, VISIBILITY_RUNGS, resolveWriteTarget, memo
9
9
  export const writeLeaf = defineLeaf({
10
10
  name: 'write',
11
11
  description: 'create or update a memory document',
12
- whenToUse: 'you are recording a new knowledge document or preference — or revising one that already exists. Writes memory/<name>.md at the resolved scope from the frontmatter flags plus a body piped on stdin. Identity is path-derived: if <name> already exists at the scope it is updated in place, otherwise it is created.',
12
+ whenToUse: 'you are recording a new knowledge document or preference, or revising one that already exists — an existing <name> at the resolved scope is updated in place, so revision is also this leaf.',
13
13
  help: {
14
14
  name: 'memory write',
15
15
  summary: 'create or update memory/<name>.md at the resolved scope from frontmatter flags + a stdin body',
16
- guide: 'The body is the easy part; the craft is routing — every frontmatter flag decides who sees this doc, when, and at what context cost. Each rung up is paid by every future agent at every boot or read, forever, so default each rung down.\n\n' +
16
+ guide: 'Every frontmatter flag decides who sees this doc, when, and at what context cost. Each rung up is paid by every future agent at every boot or read, so default each rung down.\n\n' +
17
17
  'Pick the kind. knowledge is consulted for facts or procedures; preference directs behavior. The kind choice is about how the doc is used, not about how long it is.\n\n' +
18
- 'Store reusable current truth, not session notes. Useful memories are non-obvious procedures, gotchas, durable preferences, cross-repo conventions, and amendments to plans/specs that future agents must honor. Put plan/spec amendments under path names like `projects/<topic>/...`; add `projects/<topic>/INDEX.md` with `name` visibility so the topic is discoverable without loading the whole body. Do not store chat summaries, implementation history, or facts already recorded in the repo.\n\n' +
19
- 'Set both visibility rungs explicitly on create. There is no kind default. `none`, `name`, `preview`, and `content` move from least to most loaded: `none` keeps the doc out of auto-load and on-read surfaces, `name` is the bare doc tag only, `preview` is the name + envelope + routing line (`when-and-why-to-read`), and `content` inlines the whole body when the body is short enough to justify it. Each axis is independent; usually one carries a real rung and the other is `none`. When a doc is short enough to state in a single sentence — a one-line preference, or a knowledge fact that fits in a sentence — skip `preview` and use `name` or `content` directly: the routing line would run longer than the doc itself, so a `preview` rung just adds words. Sentence-length `content` docs are not just acceptable, they are correct. Never pad a memory to be more verbose than the rule or fact it carries.\n\n' +
20
- 'Choose the scope. `project` is for facts any agent in one repo needs. `user` is for person-wide facts and preferences that should follow the user everywhere. `profile` is for the profile’s bundle of dirs: cross-repo conventions, how the pieces relate, or the user’s stance toward that body of work. `node` is the narrowest — the this-node store (`nodes/<CRTR_NODE_ID>/context/memory/`), scratch memory only this running node sees; it rides straight into this node’s knowledge block and dies with the node. When unsure, choose the narrowest scope that will still reach the next agent who needs it.\n\n' +
21
- 'A project root INDEX is the workspace front door. Name the physical doc INDEX, target the exact project with --dir, and use kind knowledge, system-prompt-visibility none, file-read-visibility content, and applies-to ".". The `.` route surfaces the full operating guide in first-message context whenever cwd or a selected profile mounts that project store; its envelope name comes from the owning project directory unless the document already carries an explicit name. It is a front door, not a manual — keep only the project constraints, key commands, architecture orientation, and conventions that differ from defaults. `crtr memory lint` validates this exact contract for every project managed by the selected profile.\n\n' +
22
- 'Choose the hook — boot vs file context. System-prompt visibility is the boot catalog. Every non-none file-read rung also requires at least one explicit applies-to route: `.` means project workspace/profile mount and is evaluated during first-message assembly; every other value is a glob evaluated only after a matching file is actually read. There is no positional fallback from where the memory file lives. Put code-specific knowledge in the owning project store, give it the narrowest real file glob, and keep it out of boot when the file read is the useful trigger. Knowledge about a person or process usually has no file boundary, so set file-read-visibility none and route it through boot instead.\n\n' +
23
- 'Write the routing line (--when-and-why-to-read) first, before storing anything: "When <circumstance>, this <kind> should be read because <broader downstream payoff>." WHY is the READER’s payoff — the consequence they secure for the task in front of them by spending the read — never what the document says, its rule, or why it should be obeyed. The trap most authors fall into is the DISGUISED restatement: a because-clause that reads like a benefit but is just the doc’s own thesis reworded as an outcome. It still fails. The test: if you could derive the because-clause by paraphrasing the doc’s advice, it is a restatement, not a payoff — a real payoff names a consequence in the reader’s world that the document itself never asserts. Bad (naked restatement): "because only genuine first principles belong in taste memory." Bad (restatement in benefit’s clothing): "because keeping the test loop fast and free of speculative tests protects the development pace" — that is the doc’s rule in outcome costume, derivable straight from its advice. Good: "because identifying throughlines in user taste lets future decisions be made faster and with less re-litigation." The stranger test: someone mid-task who has NOT read the doc must be able to decide from this one line alone whether the read is worth it. If you cannot name the concrete situation that triggers it, you do not yet understand the memory — ask the user one sharp question instead of improvising.\n\n' +
18
+ 'Store reusable current truth, not session notes. Useful memories are non-obvious procedures, gotchas, durable preferences, and cross-repo conventions. Do not store chat summaries, implementation history, or facts already recorded in the repo.\n\n' +
19
+ 'The visibility rungs `none`, `name`, `preview`, and `content` move from least to most loaded: `none` keeps the doc out of auto-load and on-read surfaces, `name` is the bare doc tag only, `preview` is the name + envelope + routing line (`when-and-why-to-read`), and `content` inlines the whole body when the body is short enough to justify it. Each axis is independent; usually one carries a real rung and the other is `none`. When a doc fits in a single sentence — a one-line preference or a one-sentence knowledge fact — skip `preview` and use `name` or `content` directly: the routing line would run longer than the doc itself. Sentence-length `content` docs are correct; never pad a memory to be more verbose than the rule or fact it carries.\n\n' +
20
+ 'Choose the scope. `project` is for facts any agent in one repo needs. `user` is for person-wide facts and preferences that should follow the user everywhere. `profile` is for the profile’s bundle of dirs: cross-repo conventions, how the pieces relate, or the user’s stance toward that body of work. `node` is scratch memory only this running node sees; it rides into this node’s knowledge block and dies with the node. When unsure, choose the narrowest scope that will still reach the next agent who needs it.\n\n' +
21
+ 'A project root INDEX is the workspace front door. Name the physical doc INDEX, target the exact project with --dir, and use kind knowledge, system-prompt-visibility none, file-read-visibility content, and applies-to ".". Its envelope name comes from the owning project directory unless the document already carries an explicit name. Keep only the project constraints, key commands, architecture orientation, and conventions that differ from defaults. `crtr memory lint` validates this exact contract for every project managed by the selected profile.\n\n' +
22
+ 'Choose the hook — boot vs file context. System-prompt visibility is the boot catalog; file-read visibility fires on the applies-to routes. Put code-specific knowledge in the owning project store, give it the narrowest real file glob, and keep it out of boot when the file read is the useful trigger. Knowledge about a person or process usually has no file boundary, so set file-read-visibility none and route it through boot instead.\n\n' +
23
+ 'Write the routing line (--when-and-why-to-read) first, before storing anything. The test for its because-clause: if it can be derived by paraphrasing the doc’s advice, it is a restatement, not a payoff — a real payoff names a consequence in the reader’s world that the document itself never asserts. Bad: "because only genuine first principles belong in taste memory." Bad: "because keeping the test loop fast and free of speculative tests protects the development pace" — the doc’s rule as an outcome, derivable straight from its advice. Good: "because identifying throughlines in user taste lets future decisions be made faster and with less re-litigation." Someone mid-task who has not read the doc must be able to decide from this line alone whether the read is worth it. If you cannot name the concrete situation that triggers it, you do not yet understand the memory — ask the user one sharp question instead of improvising.\n\n' +
24
24
  'Gate and read-when share the same predicate language: a field map is AND-ed across fields; dotted fields resolve nested values; field matchers may be scalar, array, or object. Scalar matchers do exact equality, with arrays matching any element. Array matchers do membership or intersection. Object matchers accept `eq`, `ne`, `in`, `nin`, `exists`, `contains`, `containsAll`, `containsAny`, `matches`, `imatches`, `gt`, `gte`, `lt`, and `lte`. Combinators are `all`, `any`, and `not`; sibling field matchers next to them are AND-ed in. An empty condition is inert. An unknown op never matches.\n\n' +
25
25
  'Link related docs with `[[canonical/name]]`. A doc link in any body is a first-class cross-reference to another memory document by its exact canonical name — the same identifier `crtr memory read` takes (a directory INDEX is linked by its bare directory name). Links are pointers, never transclusion: the linked body is loaded only when a reader follows it, so a link costs nothing until needed. `crtr memory lint` fails on a link that resolves to no document, and `crtr memory read` lists a doc’s resolvable links alongside its body. There is no alias or label form.\n\n' +
26
- 'When a doc grows long or information-rich, nest it into a graph instead of letting it become a scroll. The main doc at the topic’s path keeps the high-level, most load-bearing information, most important first; depth splits into reference docs under the topic’s directory (`area/topic/...`), each pointed at with a `[[link]]`. Split by subject: a leaf earns its link by covering a different subject a task might need on its own; a leaf of offloaded “further evidence”, examples, or references is never followed, so supporting material either sits in the main doc next to the point it supports or gets cut. The main doc is the entry point a reader can act from alone; a reference leaf is loaded only when the task needs that depth. Save reference leaves at `none` visibility on both axes — the link from the main doc is how they are found, so any higher rung just double-charges every boot or read for depth the graph already routes. This is the same layering the visibility rungs apply to boot cost, applied to the body itself. Keep every doc as short as its job allows; `crtr memory lint` caps body length by rung and its findings carry the split guidance.\n\n' +
27
- 'Find before write. Prefer slightly expanding an existing document, nesting genuinely separate depth under its topic, and updating the existing `when-and-why-to-read` (plus its INDEX router when present) over creating another similar memory. A new document earns its own identity only when it has a distinct read trigger and a coherent body that would make the existing document harder to route or use. Group related docs with path names (area/topic). Do not store what is already recorded or what only matters to this conversation. Body is for current truth, not history. Provenance is automatic on create and preserved on update. Run `crtr memory lint` — the frontmatter validator — after authoring.\n\n' +
28
- '--rationale is the gap this doc exists to close — the observed agent failure that prompted it, captured from user signal (a correction, a mistake you watched happen) rather than inferred from the doc’s own content. The bar: if the rationale is guessable from reading the doc, it is not the real one — a guessable gap is one agents do not actually fall into, so a merely-plausible-sounding reason is not worth recording. It is maintainer-facing only and NEVER ships in a delivered surface (boot render, on-read injection, `memory read` content) — it lives in frontmatter, visible only via `memory read --frontmatter`. Omit it when you have no such gap to record; omitting the flag on an update always preserves whatever rationale already exists.',
26
+ 'When a doc grows long or information-rich, nest it into a graph instead of letting it become a scroll. The main doc at the topic’s path keeps the high-level, most load-bearing information, most important first; depth splits into reference docs under the topic’s directory (`area/topic/...`), each pointed at with a `[[link]]`. Split by subject: a leaf earns its link by covering a different subject a task might need on its own; a leaf of offloaded “further evidence”, examples, or references is never followed, so supporting material either sits in the main doc next to the point it supports or gets cut. The main doc is the entry point a reader can act from alone; a reference leaf is loaded only when the task needs that depth. Save reference leaves at `none` visibility on both axes — the link from the main doc is how they are found, so any higher rung just double-charges every boot or read for depth the graph already routes. Keep every doc as short as its job allows; `crtr memory lint` caps body length by rung and its findings carry the split guidance.\n\n' +
27
+ 'A directory INDEX earns existence only where the aggregate view beats the sum of per-file rungs. Two shapes pass: synthesis — an operating guide or the cluster’s mechanics, ordering, and relationships, content no single child can carry — and aggregated routing — one preview line covering a large cluster with one shared routing condition, children dropped to `name` or `none`. Otherwise skip the INDEX and let each doc’s own rung route it: frontmatter routing lines are self-maintaining, while an INDEX body describing its children is a hand-maintained copy that drifts. Never write an INDEX that restates child names, paraphrases their routing lines, fronts a small directory of sharply named docs, or summarizes children a reader should open.\n\n' +
28
+ 'Find before write. Prefer slightly expanding an existing document, nesting genuinely separate depth under its topic, and updating the existing `when-and-why-to-read` (plus its INDEX router when present) over creating another similar memory. A new document earns its own identity only when it has a distinct read trigger and a coherent body whose merge into the existing document would make it harder to route or use. Group related docs with path names (area/topic). Provenance is automatic on create and preserved on update. Run `crtr memory lint` after authoring.\n\n' +
29
+ '--rationale is the gap this doc exists to close — the observed agent failure that prompted it, captured from user signal (a correction, a mistake you watched happen) rather than inferred from the doc’s own content. If the rationale is guessable from reading the doc, it is not the real one — a guessable gap is one agents do not actually fall into. Omit the flag when you have no observed gap to record.',
29
30
  params: [
30
31
  { kind: 'positional', name: 'name', required: true, constraint: 'Path-derived identity: one segment, or several joined with `/` to nest the document under a directory and group it with related docs → memory/<name>.md at the resolved scope. Updated in place if it already exists, otherwise created.' },
31
32
  { kind: 'flag', name: 'kind', type: 'enum', choices: [...MEMORY_KINDS], required: true, constraint: 'Document kind.' },
@@ -34,7 +35,7 @@ export const writeLeaf = defineLeaf({
34
35
  { kind: 'flag', name: 'system-prompt-visibility', type: 'enum', choices: [...VISIBILITY_RUNGS], required: false, constraint: 'Rung controlling how much of this document auto-loads into the system prompt / CLI help. Required when creating — there is no kind default; pick a rung explicitly.' },
35
36
  { kind: 'flag', name: 'file-read-visibility', type: 'enum', choices: [...VISIBILITY_RUNGS], required: false, constraint: 'Rung controlling how much surfaces through file context. Required when creating — there is no kind default. Every value except none also requires at least one applies-to route in the resulting document.' },
36
37
  { kind: 'flag', name: 'gate', type: 'string', required: false, constraint: 'Frontmatter gate — YAML/JSON object predicate over node config using the same field/matcher vocabulary described in the guide.' },
37
- { kind: 'flag', name: 'applies-to', type: 'string', required: false, repeatable: true, constraint: 'One explicit file-context route per occurrence. In a project store, `.` fires when cwd/profile mounts that workspace during first-message assembly. Any other value is a glob matched after an actual file read against the absolute path, basename, and path relative to the owning project root. Required whenever file-read-visibility is not none.' },
38
+ { kind: 'flag', name: 'applies-to', type: 'string', required: false, repeatable: true, constraint: 'One explicit file-context route per occurrence. In a project store, `.` fires when cwd/profile mounts that workspace during first-message assembly. Any other value is a glob matched after an actual file read against the absolute path, basename, and path relative to the owning project root. There is no positional fallback from where the memory file lives. Required whenever file-read-visibility is not none.' },
38
39
  { kind: 'flag', name: 'read-when', type: 'string', required: false, constraint: 'Frontmatter read-when — YAML/JSON object predicate over a read file’s own frontmatter using the same field/matcher vocabulary described in the guide.' },
39
40
  { kind: 'flag', name: 'slash', type: 'bool', required: false, default: false, constraint: 'Presence flags this doc invocable as a pi slash command (`/<name>`, `/` in a nested name rendered as `:`) — the doc body becomes the command’s injected prompt. Default false: most docs are consulted, not invoked.' },
40
41
  { kind: 'flag', name: 'rationale', type: 'string', required: false, constraint: 'Frontmatter rationale — the observed agent failure that made this doc necessary. Maintainer-facing only: never ships in any delivered surface (boot render, on-read injection, `memory read` content), visible only via `memory read --frontmatter`. Omitting this flag on an update PRESERVES an existing rationale unchanged.' },
@@ -71,7 +71,7 @@ function nodeNewParams() {
71
71
  { kind: 'stdin', name: 'prompt', required: false, constraint: 'First user message. Required unless --no-kickoff is given.' },
72
72
  { kind: 'flag', name: 'kind', type: 'string', required: false, default: 'general', constraint: 'Persona kind. The <kinds> list below names every top-level installable kind.' },
73
73
  { kind: 'flag', name: 'mode', type: 'enum', choices: ['base', 'orchestrator'], required: false, default: 'base', constraint: 'Persona mode. base for hands-on work; orchestrator when the unit itself needs decomposition across children.' },
74
- { kind: 'flag', name: 'cwd', type: 'path', required: false, constraint: 'Directory the node is pinned to. Defaults to the caller cwd.' },
74
+ { kind: 'flag', name: 'cwd', type: 'path', required: false, constraint: 'Pin the node to this directory. Defaults to the spawner\u2019s directory for a managed child, and to the profile home for a root (`crtr profile show <profile>`).' },
75
75
  { kind: 'flag', name: 'name', type: 'string', required: false, constraint: 'Display name. Defaults to the kind.' },
76
76
  { kind: 'flag', name: 'parent', type: 'string', required: false, constraint: 'Parent node id. Defaults to the calling node.' },
77
77
  { kind: 'flag', name: 'node-id', type: 'string', required: false, constraint: 'Exact id for the new node; lowercase letters, digits, and hyphens only, at most 128 characters. Rejected if already present.' },
@@ -106,7 +106,7 @@ async function runNodeCreation(input) {
106
106
  }
107
107
  const kind = input['kind'] ?? 'general';
108
108
  const mode = (input['mode'] ?? 'base');
109
- const cwd = input['cwd'] ?? process.cwd();
109
+ const pinCwd = input['cwd']?.trim();
110
110
  const name = input['name'];
111
111
  const parent = input['parent'];
112
112
  const root = input['root'] === true;
@@ -140,7 +140,11 @@ async function runNodeCreation(input) {
140
140
  const detail = await cliClient().createNode({
141
141
  kind,
142
142
  mode,
143
- cwd,
143
+ // The caller's directory is the profile-SELECTION context; where the node
144
+ // actually lands is resolved server-side (pin > spawner's cwd > profile
145
+ // home). Only `--cwd` pins.
146
+ cwd: process.cwd(),
147
+ ...(pinCwd !== undefined && pinCwd !== '' ? { pin_cwd: pinCwd } : {}),
144
148
  ...(name !== undefined ? { name } : {}),
145
149
  prompt,
146
150
  ...(root ? { root: true } : { parent: parentId ?? null }),
@@ -4,7 +4,7 @@ import { listProfiles } from '../../core/profiles/manifest.js';
4
4
  export const listLeaf = defineLeaf({
5
5
  name: 'list',
6
6
  description: 'inventory every profile',
7
- whenToUse: 'browse every profile that exists — one line each with its id, name, project count, and last-used time. Reach for `profile show` once you have picked one, for its full project list.',
7
+ whenToUse: 'browse every profile that exists — one line each with its id, name, project count, home directory, and last-used time. Reach for `profile show` once you have picked one, for its full project list.',
8
8
  help: {
9
9
  name: 'profile list',
10
10
  summary: 'every profile as JSONL, one line each, sorted by name then profile_id',
@@ -12,6 +12,7 @@ export const listLeaf = defineLeaf({
12
12
  { name: 'profile_id', type: 'string', required: true, constraint: 'Stable directory id.' },
13
13
  { name: 'name', type: 'string', required: true, constraint: 'Manifest name.' },
14
14
  { name: 'projects_count', type: 'int', required: true, constraint: 'Number of project directories on the manifest.' },
15
+ { name: 'home', type: 'string | null', required: true, constraint: 'Directory the profile\u2019s nodes are pinned to, or null when it owns no projects.' },
15
16
  { name: 'last_used_at', type: 'string | null', required: true, constraint: 'ISO 8601 timestamp of the most recent selection, or null if never selected.' },
16
17
  ],
17
18
  outputKind: 'jsonl',
@@ -27,6 +28,7 @@ export const listLeaf = defineLeaf({
27
28
  profile_id: profileId,
28
29
  name: manifest.name,
29
30
  projects_count: manifest.projects.length,
31
+ home: manifest.home,
30
32
  last_used_at: manifest.last_used_at,
31
33
  });
32
34
  }
@@ -28,7 +28,7 @@ export const newLeaf = defineLeaf({
28
28
  name: 'project',
29
29
  type: 'path',
30
30
  required: false,
31
- constraint: 'One initial project directory. Must already exist and be a directory; resolved to its absolute real path before storing. Singular — add more with `crtr profile project add` after creation.',
31
+ constraint: "One initial project directory. Must already exist and be a directory; resolved to its absolute real path before storing. Also becomes the profile's home — where its nodes are pinned. Singular — add more with `crtr profile project add` after creation.",
32
32
  },
33
33
  ],
34
34
  output: [
@@ -36,6 +36,7 @@ export const newLeaf = defineLeaf({
36
36
  { name: 'name', type: 'string', required: true, constraint: 'The manifest name as given.' },
37
37
  { name: 'path', type: 'string', required: true, constraint: 'Absolute path to the profile directory.' },
38
38
  { name: 'projects', type: 'string[]', required: true, constraint: 'Resolved absolute project directories, in manifest order. Empty when --project was omitted.' },
39
+ { name: 'home', type: 'string | null', required: true, constraint: 'Directory the profile\u2019s nodes are pinned to — the initial project, or null when none was given.' },
39
40
  { name: 'created_at', type: 'string', required: true, constraint: 'ISO 8601 creation timestamp.' },
40
41
  { name: 'follow_up', type: 'string', required: true, constraint: 'Concrete next commands.' },
41
42
  ],
@@ -56,6 +57,7 @@ export const newLeaf = defineLeaf({
56
57
  name: manifest.name,
57
58
  path: profileRoot(profileId),
58
59
  projects: manifest.projects,
60
+ home: manifest.home,
59
61
  created_at: manifest.created_at,
60
62
  follow_up: `Root profile ensured. Spawn nodes under it with \`--profile ${profileId}\`, or widen its purview with \`crtr profile project add ${profileId} --dir <path>\`.`,
61
63
  };
@@ -68,6 +70,7 @@ export const newLeaf = defineLeaf({
68
70
  name: manifest.name,
69
71
  path: profileRoot(profileId),
70
72
  projects: manifest.projects,
73
+ home: manifest.home,
71
74
  created_at: manifest.created_at,
72
75
  follow_up: `Show it with \`crtr profile show ${profileId}\`, add another project with \`crtr profile project add ${profileId} --dir <path>\`, or list every profile with \`crtr profile list\`.`,
73
76
  };
@@ -1,13 +1,14 @@
1
1
  // `crtr profile project` — the project-purview sub-noun of `profile`. A
2
- // profile's `projects` list is what it can SEE (memory + config resolution).
3
- // These two verbs widen or narrow that list after creation; `crtr profile
4
- // show` reads it back.
2
+ // profile's `projects` list is what it can SEE (memory + config resolution),
3
+ // and its `home` — one of those dirs — is where its nodes actually run. These
4
+ // two verbs widen or narrow that list after creation and re-point the home;
5
+ // `crtr profile show` reads both back.
5
6
  import { defineLeaf, defineBranch } from '../../core/command.js';
6
7
  import { addProfileProject, removeProfileProject, loadProfileManifest } from '../../core/profiles/manifest.js';
7
8
  const addLeaf = defineLeaf({
8
9
  name: 'add',
9
10
  description: "add a project directory to a profile's purview",
10
- whenToUse: "a profile needs to see (memory + config from) another project directory — extend its purview after creation, including mid-session from a node already running under that profile.",
11
+ whenToUse: "a profile needs to see (memory + config from) another project directory — extend its purview after creation, including mid-session from a node already running under that profile. Also the way to re-point the profile's home, with --home.",
11
12
  help: {
12
13
  name: 'profile project add',
13
14
  summary: "append a project directory to a profile's manifest, deduped by real path",
@@ -25,21 +26,32 @@ const addLeaf = defineLeaf({
25
26
  required: true,
26
27
  constraint: 'Directory to add. Must exist and be a directory; resolved to its absolute real path before storing. A path already on the manifest is a no-op, not an error.',
27
28
  },
29
+ {
30
+ kind: 'flag',
31
+ name: 'home',
32
+ type: 'bool',
33
+ required: false,
34
+ constraint: "Also make this directory the profile's home — where every node under it is pinned unless the create passes an explicit --cwd. Defaults to the first project dir; pass this on an already-listed dir to re-point it.",
35
+ },
28
36
  ],
29
37
  output: [
30
38
  { name: 'profile_id', type: 'string', required: true, constraint: 'Stable directory id.' },
31
39
  { name: 'projects', type: 'string[]', required: true, constraint: 'The updated, deduped project list in manifest order.' },
40
+ { name: 'home', type: 'string | null', required: true, constraint: "The profile's home directory after the change." },
32
41
  { name: 'follow_up', type: 'string', required: true, constraint: 'Concrete next commands.' },
33
42
  ],
34
43
  outputKind: 'object',
35
- effects: ["Appends to the profile manifest's `projects` array. Invalidates the process scope cache."],
44
+ effects: ["Appends to the profile manifest's `projects` array, and rewrites `home` when --home is given. Invalidates the process scope cache."],
36
45
  },
37
46
  run: async (input) => {
38
47
  const { profileId } = loadProfileManifest(input['profile']);
39
- const { manifest } = addProfileProject(profileId, input['dir']);
48
+ const { manifest } = addProfileProject(profileId, input['dir'], {
49
+ home: input['home'] === true,
50
+ });
40
51
  return {
41
52
  profile_id: profileId,
42
53
  projects: manifest.projects,
54
+ home: manifest.home,
43
55
  follow_up: `Show the full manifest with \`crtr profile show ${profileId}\`.`,
44
56
  };
45
57
  },
@@ -63,16 +75,17 @@ const removeLeaf = defineLeaf({
63
75
  name: 'dir',
64
76
  type: 'path',
65
77
  required: true,
66
- constraint: 'Directory to remove, matched by its resolved real path against the manifest. Does not require the directory to still exist on disk.',
78
+ constraint: 'Directory to remove, matched by its resolved real path against the manifest. Does not require the directory to still exist on disk. Removing the home dir re-points the home at the first remaining project.',
67
79
  },
68
80
  ],
69
81
  output: [
70
82
  { name: 'profile_id', type: 'string', required: true, constraint: 'Stable directory id.' },
71
83
  { name: 'projects', type: 'string[]', required: true, constraint: 'The updated project list in manifest order.' },
84
+ { name: 'home', type: 'string | null', required: true, constraint: "The profile's home directory after the change." },
72
85
  { name: 'follow_up', type: 'string', required: true, constraint: 'Concrete next commands.' },
73
86
  ],
74
87
  outputKind: 'object',
75
- effects: ["Removes an entry from the profile manifest's `projects` array. Invalidates the process scope cache."],
88
+ effects: ["Removes an entry from the profile manifest's `projects` array, re-pointing `home` when that entry was it. Invalidates the process scope cache."],
76
89
  },
77
90
  run: async (input) => {
78
91
  const { profileId } = loadProfileManifest(input['profile']);
@@ -80,6 +93,7 @@ const removeLeaf = defineLeaf({
80
93
  return {
81
94
  profile_id: profileId,
82
95
  projects: manifest.projects,
96
+ home: manifest.home,
83
97
  follow_up: `Show the full manifest with \`crtr profile show ${profileId}\`.`,
84
98
  };
85
99
  },
@@ -91,7 +105,7 @@ export const projectBranch = defineBranch({
91
105
  help: {
92
106
  name: 'profile project',
93
107
  summary: "manage a profile's project purview — the directories it resolves memory and config from",
94
- model: "A profile's `projects` list is the set of directories it inherits memory and config from. `add` widens that purview by one directory (deduped by real path); `remove` narrows it. Read the current list with `crtr profile show`. Purview is independent of a per-cwd default pin (`crtr profile default`) — widening purview never changes which profile a directory defaults to.",
108
+ model: "A profile's `projects` list is the set of directories it inherits memory and config from, and its `home` — the first project unless `add --home` says otherwise — is the directory its nodes are pinned to. `add` widens that purview by one directory (deduped by real path) and optionally re-points the home; `remove` narrows it, re-pointing the home when it removed it. Read both back with `crtr profile show`. Purview is independent of a per-cwd default pin (`crtr profile default`) — widening purview never changes which profile a directory defaults to.",
95
109
  },
96
110
  children: [addLeaf, removeLeaf],
97
111
  });
@@ -6,7 +6,7 @@ import { CONFIG_FILE } from '../../types.js';
6
6
  export const showLeaf = defineLeaf({
7
7
  name: 'show',
8
8
  description: "one profile's manifest in full",
9
- whenToUse: "you need a profile's full project list, id, and timestamps — after `profile list` narrows to a name, or to inspect what a node's bearings named as its profile.",
9
+ whenToUse: "you need a profile's full project list, home directory, id, and timestamps — after `profile list` narrows to a name, to find where its nodes will run, or to inspect what a node's bearings named as its profile.",
10
10
  help: {
11
11
  name: 'profile show',
12
12
  summary: "print one profile's manifest plus its on-disk path and config.json location",
@@ -22,6 +22,7 @@ export const showLeaf = defineLeaf({
22
22
  { name: 'profile_id', type: 'string', required: true, constraint: 'Stable directory id.' },
23
23
  { name: 'name', type: 'string', required: true, constraint: 'Manifest name.' },
24
24
  { name: 'projects', type: 'string[]', required: true, constraint: 'Absolute project directories, in manifest order.' },
25
+ { name: 'home', type: 'string | null', required: true, constraint: 'The directory every node under this profile is pinned to unless its create passes an explicit --cwd. Defaults to the first project; re-point it with `profile project add --home`. Null when the profile owns no projects (the root profile), in which case nodes fall back to the creating directory.' },
25
26
  { name: 'created_at', type: 'string', required: true, constraint: 'ISO 8601 creation timestamp.' },
26
27
  { name: 'last_used_at', type: 'string | null', required: true, constraint: 'ISO 8601 timestamp of the most recent selection, or null if never selected.' },
27
28
  { name: 'path', type: 'string', required: true, constraint: 'Absolute path to the profile directory.' },
@@ -39,6 +40,7 @@ export const showLeaf = defineLeaf({
39
40
  profile_id: profileId,
40
41
  name: manifest.name,
41
42
  projects: manifest.projects,
43
+ home: manifest.home,
42
44
  created_at: manifest.created_at,
43
45
  last_used_at: manifest.last_used_at,
44
46
  path: profileRoot(profileId),
@@ -23,14 +23,14 @@ export function registerProfile() {
23
23
  return defineBranch({
24
24
  name: 'profile',
25
25
  rootEntry: {
26
- concept: 'an agent identity defined at the user root — a manifest naming project directories plus its own memory store',
26
+ concept: 'an agent identity defined at the user root — a manifest naming project directories and the home its nodes run in, plus its own memory store',
27
27
  desc: 'create, inspect, and manage profiles',
28
28
  useWhen: 'creating a new agent identity, inspecting or listing existing ones, changing a profile\u2019s project purview, pinning which profile a directory defaults to at startup, or managing a profile\u2019s stored env vars. Selecting a profile for a one-off run (`--profile`) lives elsewhere.',
29
29
  },
30
30
  help: {
31
31
  name: 'profile',
32
32
  summary: 'create, inspect, and manage profiles \u2014 agent identities with their own project purview and memory store',
33
- model: '`new` creates one from a name (+ at most one initial `--project`). `list` inventories every profile as JSONL. `show` prints one manifest in full. `rename` changes only the manifest name \u2014 the profile_id is stable across a rename. `delete` removes a profile\u2019s directory (manifest + its own memory store) entirely and does not touch the project directories it pointed at. `project` widens/narrows a profile\u2019s project purview (the dirs it resolves memory + config from). `default` pins which profile a directory defaults to at startup so the chooser stops asking \u2014 directory-scoped, independent of purview. `env` manages a profile-scoped 0600 store of env vars injected directly into every broker launched under that profile \u2014 set on stdin, list names only (never values), or remove one; no `spawnEnv.allow` entry needed. Every manifest verb but `new`/`list` takes <profile> as an exact id or a unique manifest name; an ambiguous name fails listing every matching id.',
33
+ model: 'A profile owns a `home` — the first of its project dirs unless `project add --home` re-points it — and every node created under the profile is pinned there, so cwd selects the profile and the profile then supplies where its nodes run. Only `node new --cwd` (or inheriting a spawner already elsewhere, notably inside a managed worktree) overrides that; the root profile has no home, so nodes under it stay in the directory that created them. `new` creates one from a name (+ at most one initial `--project`, which becomes its home). `list` inventories every profile as JSONL. `show` prints one manifest in full. `rename` changes only the manifest name \u2014 the profile_id is stable across a rename. `delete` removes a profile\u2019s directory (manifest + its own memory store) entirely and does not touch the project directories it pointed at. `project` widens/narrows a profile\u2019s project purview (the dirs it resolves memory + config from). `default` pins which profile a directory defaults to at startup so the chooser stops asking \u2014 directory-scoped, independent of purview. `env` manages a profile-scoped 0600 store of env vars injected directly into every broker launched under that profile \u2014 set on stdin, list names only (never values), or remove one; no `spawnEnv.allow` entry needed. Every manifest verb but `new`/`list` takes <profile> as an exact id or a unique manifest name; an ambiguous name fails listing every matching id.',
34
34
  },
35
35
  children: [newLeaf, listLeaf, showLeaf, renameLeaf, deleteLeaf, projectBranch, defaultBranch, envBranch],
36
36
  });
@@ -3,7 +3,7 @@ import { isSafeNodeId } from '../../core/canvas/paths.js';
3
3
  import { usage } from '../../core/errors.js';
4
4
  import { validateOperationId } from '../../core/events/operation-id.js';
5
5
  import { readLogSnapshot } from '../../core/events/read.js';
6
- import { emitLine, isJsonOutput } from '../../core/io.js';
6
+ import { emitLine, isJsonOutput, recordPreviewLine } from '../../core/io.js';
7
7
  const ISO_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u;
8
8
  const MAX_PATTERN_BYTES = 4_096;
9
9
  function invalidFlag(flag, received, expected) {
@@ -116,8 +116,10 @@ export const sysLogsLeaf = defineLeaf({
116
116
  if (item.kind === 'event') {
117
117
  if (json)
118
118
  emitLine({ ...item.envelope });
119
- else
119
+ else {
120
+ recordPreviewLine({ ...item.envelope });
120
121
  process.stdout.write(`${renderEvent(item.envelope)}\n`);
122
+ }
121
123
  }
122
124
  else if (!json) {
123
125
  process.stdout.write(`RAW ${item.source} ${new Date(item.effectiveTsMs).toISOString()} ${JSON.stringify(item.content)}\n`);
@@ -35,7 +35,7 @@ test('concurrent processes reconcile one coherent branded host tuple', async ()
35
35
  assert.ok(deadOwner !== undefined);
36
36
  const abandonedLock = join(home, '.crouter', 'host.lock');
37
37
  mkdirSync(abandonedLock);
38
- writeFileSync(join(abandonedLock, 'owner.json'), JSON.stringify({ pid: deadOwner, token: 'abandoned' }));
38
+ writeFileSync(join(abandonedLock, `owner.${deadOwner}.abandoned`), '');
39
39
  try {
40
40
  const moduleUrl = pathToFileURL(join(process.cwd(), 'src/core/runtime/branded-host.ts')).href;
41
41
  const results = await Promise.all(Array.from({ length: 4 }, () => reconcileInChild(home, moduleUrl)));
@@ -13,7 +13,7 @@ import { join } from 'node:path';
13
13
  import { closeDb } from '../canvas/db.js';
14
14
  import { resetScopeCache } from '../scope.js';
15
15
  import { spawnNode } from '../runtime/nodes.js';
16
- import { renderOnReadDocs } from '../substrate/on-read.js';
16
+ import { renderOnReadDocs } from '../substrate/on-read-node.js';
17
17
  let canvasHome;
18
18
  let fakeHome;
19
19
  let prevHomeEnv;
@@ -13,7 +13,7 @@ import { join } from 'node:path';
13
13
  import { closeDb } from '../canvas/db.js';
14
14
  import { resetScopeCache } from '../scope.js';
15
15
  import { spawnNode } from '../runtime/nodes.js';
16
- import { renderOnReadDocs } from '../substrate/on-read.js';
16
+ import { renderOnReadDocs } from '../substrate/on-read-node.js';
17
17
  import { loadInjectedDocs, saveInjectedDocs, clearInjectedDocs, } from '../substrate/injected-store.js';
18
18
  const FIXTURE_BODY = 'Fixture body that must surface exactly once.';
19
19
  let home;
@@ -1,4 +1,4 @@
1
- export declare const CANVAS_EXTENSION_NAMES: readonly ["canvas-inbox-watcher", "canvas-review-boundary", "canvas-stophook", "canvas-recap", "canvas-goal-capture", "canvas-passive-context", "canvas-context-intro", "canvas-tool-guide", "canvas-doc-substrate", "canvas-structured-output", "canvas-bash-valve"];
1
+ export declare const CANVAS_EXTENSION_NAMES: readonly ["canvas-inbox-watcher", "canvas-review-boundary", "canvas-stophook", "canvas-recap", "canvas-goal-capture", "canvas-passive-context", "canvas-context-intro", "canvas-tool-guide", "canvas-doc-substrate", "canvas-structured-output", "canvas-bash-valve", "canvas-preview-result"];
2
2
  /** Structural shipped-hook identity: a canvas-hook stem directly under a
3
3
  * `pi-extensions` directory. A user's own extension elsewhere may share the
4
4
  * stem and is not shipped. */
@@ -7,9 +7,15 @@ export const CANVAS_EXTENSION_NAMES = [
7
7
  'canvas-inbox-watcher', 'canvas-review-boundary', 'canvas-stophook', 'canvas-recap',
8
8
  'canvas-goal-capture', 'canvas-passive-context', 'canvas-context-intro',
9
9
  'canvas-tool-guide', 'canvas-doc-substrate', 'canvas-structured-output',
10
- 'canvas-bash-valve',
10
+ 'canvas-bash-valve', 'canvas-preview-result',
11
11
  ];
12
12
  const HISTORICAL_CANVAS_EXTENSION_PREFIXES = [
13
+ [
14
+ 'canvas-inbox-watcher', 'canvas-review-boundary', 'canvas-stophook', 'canvas-recap',
15
+ 'canvas-goal-capture', 'canvas-passive-context', 'canvas-context-intro',
16
+ 'canvas-tool-guide', 'canvas-doc-substrate', 'canvas-structured-output',
17
+ 'canvas-bash-valve',
18
+ ],
13
19
  [
14
20
  'canvas-inbox-watcher', 'canvas-stophook', 'canvas-recap',
15
21
  'canvas-goal-capture', 'canvas-passive-context', 'canvas-review-boundary',
@@ -17,7 +17,7 @@ import { request as httpRequest } from 'node:http';
17
17
  import { request as httpsRequest } from 'node:https';
18
18
  import { validateDeclaredResult } from './exec-invoke.js';
19
19
  import { CrtrError } from '../../errors.js';
20
- import { diag, writeStdout } from '../../io.js';
20
+ import { diag, recordPreviewError, recordPreviewJsonLine, writeStdout } from '../../io.js';
21
21
  import { ExitCode } from '../../../types.js';
22
22
  // ---------------------------------------------------------------------------
23
23
  // Constants
@@ -420,6 +420,7 @@ async function requestStreaming(spec, plan) {
420
420
  if (line.trim() === '')
421
421
  continue; // drop blank records
422
422
  framesEmitted = true;
423
+ recordPreviewJsonLine(line);
423
424
  const ok = await writeStdout(line + '\n');
424
425
  if (!ok) {
425
426
  // Consumer closed the pipe (EPIPE) — stop cleanly, nothing to report.
@@ -434,6 +435,7 @@ async function requestStreaming(spec, plan) {
434
435
  // backend sent no trailing delimiter, so none is added).
435
436
  if (partial.trim() !== '') {
436
437
  framesEmitted = true;
438
+ recordPreviewJsonLine(partial);
437
439
  await writeStdout(partial);
438
440
  }
439
441
  return; // clean EOF → SUCCESS
@@ -444,7 +446,13 @@ async function requestStreaming(spec, plan) {
444
446
  if (framesEmitted) {
445
447
  // After a frame has been emitted: one concise stderr diagnostic + NETWORK
446
448
  // exit, and DO NOT throw (that would append an <error> to stdout).
447
- diag(`crtr: ${label(spec)}: stream interrupted (${detail})`);
449
+ const message = `${label(spec)}: stream interrupted (${detail})`;
450
+ diag(`crtr: ${message}`);
451
+ recordPreviewError({
452
+ error: 'stream_interrupted',
453
+ message,
454
+ next: 'Retry the command to begin a fresh stream.',
455
+ });
448
456
  process.exitCode = ExitCode.NETWORK;
449
457
  return;
450
458
  }
@@ -5,7 +5,7 @@
5
5
  // A plain array walk + a small flag parser is ~120 lines and has no surprising
6
6
  // edge cases.
7
7
  import { renderRoot, renderBranch, renderLeafArgv } from './help.js';
8
- import { readStdinRaw, peekStdinRaw, emit, handle, setJsonOutput, isJsonOutput } from './io.js';
8
+ import { beginPreview, publishPreviewResult, readStdinRaw, peekStdinRaw, emit, handle, setJsonOutput, isJsonOutput } from './io.js';
9
9
  import { renderResult } from './render.js';
10
10
  import { CrtrError } from './errors.js';
11
11
  import { operationIdContext } from './events/operation-id.js';
@@ -614,6 +614,7 @@ export async function runCli(root, argv) {
614
614
  // below: `node` is now a reassignable `let` (the §5.1 retry re-walks it),
615
615
  // which TS re-widens to the node union across an `await`.
616
616
  const leaf = node;
617
+ beginPreview(path.join(' '));
617
618
  const params = leaf.help.params !== undefined ? leaf.help.params : [];
618
619
  let providedParams = new Set();
619
620
  let contextFilePaths = new Map();
@@ -628,6 +629,7 @@ export async function runCli(root, argv) {
628
629
  });
629
630
  const context = { providedParams, contextFilePaths };
630
631
  const result = await operationIdContext.fresh(() => leaf.run(input, context));
632
+ publishPreviewResult(result);
631
633
  if (result !== undefined && result !== null) {
632
634
  if (isJsonOutput()) {
633
635
  emit(result);
@@ -1,4 +1,3 @@
1
- import { mkdirSync, rmSync } from 'node:fs';
2
1
  import { dirname, join } from 'node:path';
3
2
  import { isDeepStrictEqual } from 'node:util';
4
3
  import { CONFIG_FILE, STATE_FILE, CONDENSED_HISTORY_MODES, MOUSE_MODE_DEFAULTS, DEFAULT_WHIP_MESSAGES, defaultScopeConfig, defaultScopeState, defaultModelLaddersConfig, defaultKindsConfig, defaultRemoteCanvasConfig } from '../types.js';
@@ -7,6 +6,7 @@ import { emitEvent } from './events/emit.js';
7
6
  import { atomicWriteJson, readJsonIfExists, writeJson, ensureDir } from './fs-utils.js';
8
7
  import { scopeRoot, requireScopeRoot, findProjectScopeRoots } from './scope.js';
9
8
  import { profileRoot } from './profiles/manifest.js';
9
+ import { withExclusiveDirectoryLock } from './exclusive-lock.js';
10
10
  import { SCOPE_CONFIG_KEYS } from './user-settings.js';
11
11
  import { normalizeWorkingGerunds } from '../shared/working-activity.js';
12
12
  function configPathFor(root) {
@@ -54,34 +54,11 @@ export function readState(scope) {
54
54
  activeCanvas: existing.activeCanvas ?? null,
55
55
  };
56
56
  }
57
- const CONFIG_LOCK_TIMEOUT_MS = 5000;
58
- const CONFIG_LOCK_POLL_MS = 25;
59
- function sleepSync(ms) {
60
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
61
- }
62
57
  function withConfigPathLock(path, run) {
63
58
  ensureDir(dirname(path));
64
- const lockPath = `${path}.lock`;
65
- const deadline = Date.now() + CONFIG_LOCK_TIMEOUT_MS;
66
- for (;;) {
67
- try {
68
- mkdirSync(lockPath);
69
- break;
70
- }
71
- catch (error) {
72
- if (error.code !== 'EEXIST')
73
- throw error;
74
- if (Date.now() > deadline)
75
- throw new Error(`timed out waiting for config lock: ${path}`);
76
- sleepSync(CONFIG_LOCK_POLL_MS);
77
- }
78
- }
79
- try {
80
- return run(path);
81
- }
82
- finally {
83
- rmSync(lockPath, { recursive: true, force: true });
84
- }
59
+ return withExclusiveDirectoryLock(`${path}.lock`, () => run(path), {
60
+ timeoutError: () => new Error(`timed out waiting for config lock: ${path}`),
61
+ });
85
62
  }
86
63
  function withConfigLock(scope, run) {
87
64
  const root = requireScopeRoot(scope);
@@ -0,0 +1,14 @@
1
+ export interface ExclusiveLockOptions {
2
+ /** Grace before a lock that names no owner at all is cleared. */
3
+ staleMs?: number;
4
+ timeoutMs?: number;
5
+ /** The error thrown when the wait runs out, so callers keep their own remediation. */
6
+ timeoutError?: () => Error;
7
+ }
8
+ /**
9
+ * Run a short filesystem transition under a token-checked, crash-reclaimable
10
+ * directory lock. A holder that dies releases immediately — the next contender
11
+ * sees a dead pid in the marker name — while a live holder is never stolen from,
12
+ * however long its operation runs.
13
+ */
14
+ export declare function withExclusiveDirectoryLock<T>(path: string, operation: () => T, options?: ExclusiveLockOptions): T;