@north-light/crouter 0.3.221 → 0.3.223

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 (169) hide show
  1. package/dist/api/client.d.ts +21 -1
  2. package/dist/api/client.js +34 -0
  3. package/dist/api/dto/chat-inventory.d.ts +13 -0
  4. package/dist/api/dto/human-requests.d.ts +88 -0
  5. package/dist/api/dto/human-requests.js +4 -0
  6. package/dist/api/dto/human.d.ts +3 -0
  7. package/dist/api/dto/reviews.d.ts +2 -0
  8. package/dist/api/index.d.ts +1 -0
  9. package/dist/api/index.js +1 -0
  10. package/dist/api/routes.d.ts +7 -0
  11. package/dist/api/routes.js +10 -0
  12. package/dist/builtin-memory/00-runtime-base/00-authoring.md +31 -0
  13. package/dist/builtin-memory/00-runtime-base/01-escalation.md +14 -0
  14. package/dist/builtin-memory/{insights/listen.md → 00-runtime-base/02-insight-capture.md} +1 -0
  15. package/dist/builtin-memory/02-turn-lifecycle/00-ending-a-turn.md +27 -0
  16. package/dist/builtin-memory/{02-lifecycle/01-resident.md → 02-turn-lifecycle/02-resident.md} +5 -0
  17. package/dist/builtin-memory/04-base-worker.md +4 -8
  18. package/dist/builtin-memory/04-orchestration-kernel.md +1 -1
  19. package/dist/builtin-memory/05-kinds/advisor/01-orchestrator.md +1 -0
  20. package/dist/builtin-memory/05-kinds/advisor/advice-contract.md +1 -0
  21. package/dist/builtin-memory/05-kinds/design/00-base.md +2 -1
  22. package/dist/builtin-memory/05-kinds/design/01-orchestrator.md +2 -1
  23. package/dist/builtin-memory/05-kinds/design/design-contract.md +19 -0
  24. package/dist/builtin-memory/05-kinds/developer/00-base.md +1 -0
  25. package/dist/builtin-memory/05-kinds/developer/01-orchestrator.md +1 -0
  26. package/dist/builtin-memory/05-kinds/explore/00-base.md +1 -0
  27. package/dist/builtin-memory/05-kinds/explore/01-orchestrator.md +1 -0
  28. package/dist/builtin-memory/05-kinds/general/00-base.md +1 -0
  29. package/dist/builtin-memory/05-kinds/plan/00-base.md +2 -1
  30. package/dist/builtin-memory/05-kinds/plan/01-orchestrator.md +2 -1
  31. package/dist/builtin-memory/05-kinds/plan/plan-contract.md +28 -0
  32. package/dist/builtin-memory/05-kinds/plan/reviewers/architecture-fit.md +1 -0
  33. package/dist/builtin-memory/05-kinds/plan/reviewers/code-smells.md +1 -0
  34. package/dist/builtin-memory/05-kinds/plan/reviewers/lens-contract.md +1 -0
  35. package/dist/builtin-memory/05-kinds/plan/reviewers/pattern-consistency.md +1 -0
  36. package/dist/builtin-memory/05-kinds/plan/reviewers/requirements-coverage.md +1 -0
  37. package/dist/builtin-memory/05-kinds/plan/reviewers/security.md +1 -0
  38. package/dist/builtin-memory/05-kinds/review/00-base.md +1 -0
  39. package/dist/builtin-memory/05-kinds/review/01-orchestrator.md +1 -0
  40. package/dist/builtin-memory/05-kinds/review/companion/00-base.md +1 -0
  41. package/dist/builtin-memory/05-kinds/review/security-findings.md +1 -0
  42. package/dist/builtin-memory/05-kinds/spec/00-base.md +4 -3
  43. package/dist/builtin-memory/05-kinds/spec/01-orchestrator.md +1 -0
  44. package/dist/builtin-memory/05-kinds/spec/requirements.md +1 -0
  45. package/dist/builtin-memory/design/guide.md +35 -0
  46. package/dist/builtin-memory/design/roadmap.md +21 -0
  47. package/dist/builtin-memory/insights/capture.md +1 -1
  48. package/dist/builtin-memory/internal/memory-loading.md +4 -4
  49. package/dist/builtin-memory/internal/plugins.md +10 -1
  50. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  51. package/dist/builtin-memory/plan/roadmap.md +6 -28
  52. package/dist/builtin-memory/spec/guide.md +19 -8
  53. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +28 -15
  54. package/dist/clients/attach/render/markdown-source.js +106 -1
  55. package/dist/clients/attach/session/file-links.d.ts +13 -4
  56. package/dist/clients/attach/session/file-links.js +54 -58
  57. package/dist/clients/attach/viewer.js +545 -543
  58. package/dist/clients/inbox/controller.js +1 -1
  59. package/dist/clients/inbox/page-adapter.js +2 -1
  60. package/dist/clients/inbox/resolve.d.ts +1 -0
  61. package/dist/clients/inbox/review/review-client.js +3 -1
  62. package/dist/clients/inbox/tui/panel.js +23 -4
  63. package/dist/clients/inbox/tui/render.js +6 -0
  64. package/dist/clients/inbox/tui/types.d.ts +8 -0
  65. package/dist/commands/__tests__/human.test.js +2 -2
  66. package/dist/commands/human/request.d.ts +2 -0
  67. package/dist/commands/human/request.js +281 -0
  68. package/dist/commands/human.js +5 -2
  69. package/dist/commands/memory/shared.d.ts +2 -2
  70. package/dist/commands/memory/shared.js +11 -6
  71. package/dist/commands/pkg/browse/doc-view.js +2 -0
  72. package/dist/commands/sys/config.js +2 -2
  73. package/dist/commands/sys/doctor.js +54 -2
  74. package/dist/core/__tests__/broker-extension-canvas-db-boundary.test.js +7 -4
  75. package/dist/core/__tests__/fixtures/memory-slash-live-probe.d.ts +1 -0
  76. package/dist/core/__tests__/fixtures/memory-slash-live-probe.js +71 -0
  77. package/dist/core/__tests__/human-action-delivery.test.d.ts +1 -0
  78. package/dist/core/__tests__/human-action-delivery.test.js +140 -0
  79. package/dist/core/__tests__/human-actions.test.d.ts +1 -0
  80. package/dist/core/__tests__/human-actions.test.js +116 -0
  81. package/dist/core/__tests__/inline-memory-refs.test.js +1 -1
  82. package/dist/core/__tests__/profile-project-memory-delivery.test.js +70 -3
  83. package/dist/core/__tests__/prospective-inventory-capability-parity.test.d.ts +1 -0
  84. package/dist/core/__tests__/prospective-inventory-capability-parity.test.js +91 -0
  85. package/dist/core/__tests__/seam/memory-slash-node-relative-inventory.test.d.ts +1 -0
  86. package/dist/core/__tests__/seam/memory-slash-node-relative-inventory.test.js +127 -0
  87. package/dist/core/__tests__/seam/prospective-inventory-stdout.test.d.ts +1 -0
  88. package/dist/core/__tests__/seam/prospective-inventory-stdout.test.js +31 -0
  89. package/dist/core/canvas/db.js +23 -0
  90. package/dist/core/canvas/human-deliveries.d.ts +53 -0
  91. package/dist/core/canvas/human-deliveries.js +75 -0
  92. package/dist/core/config.d.ts +13 -1
  93. package/dist/core/config.js +51 -1
  94. package/dist/core/feed/inbox.d.ts +6 -0
  95. package/dist/core/feed/inbox.js +9 -1
  96. package/dist/core/human/action-binding.d.ts +21 -0
  97. package/dist/core/human/action-binding.js +40 -0
  98. package/dist/core/human/completion.d.ts +38 -0
  99. package/dist/core/human/completion.js +27 -0
  100. package/dist/core/human/convention.d.ts +2 -0
  101. package/dist/core/human/convention.js +2 -0
  102. package/dist/core/human/tickets.d.ts +25 -6
  103. package/dist/core/human/tickets.js +19 -13
  104. package/dist/core/human/types.d.ts +5 -0
  105. package/dist/core/human-actions.d.ts +25 -0
  106. package/dist/core/human-actions.js +101 -0
  107. package/dist/core/memory-resolver.js +1 -1
  108. package/dist/core/profiles/select.d.ts +2 -0
  109. package/dist/core/profiles/select.js +21 -4
  110. package/dist/core/runtime/broker/frame-dispatch.js +2 -5
  111. package/dist/core/runtime/broker-inventory.d.ts +1 -2
  112. package/dist/core/runtime/broker-inventory.js +2 -77
  113. package/dist/core/runtime/broker-persona-guidance.js +1 -1
  114. package/dist/core/runtime/broker.js +4 -4
  115. package/dist/core/runtime/chat-inventory-rows.d.ts +8 -0
  116. package/dist/core/runtime/chat-inventory-rows.js +105 -0
  117. package/dist/core/runtime/command-surface.d.ts +8 -3
  118. package/dist/core/runtime/command-surface.js +42 -6
  119. package/dist/core/runtime/launch-target.d.ts +25 -0
  120. package/dist/core/runtime/launch-target.js +54 -0
  121. package/dist/core/runtime/persona.js +3 -3
  122. package/dist/core/runtime/prospective-inventory-cli.d.ts +1 -0
  123. package/dist/core/runtime/prospective-inventory-cli.js +61 -0
  124. package/dist/core/runtime/prospective-inventory.d.ts +10 -0
  125. package/dist/core/runtime/prospective-inventory.js +88 -0
  126. package/dist/core/runtime/spawn.d.ts +3 -1
  127. package/dist/core/runtime/spawn.js +5 -3
  128. package/dist/core/substrate/frontmatter-validation.d.ts +2 -5
  129. package/dist/core/substrate/frontmatter-validation.js +8 -4
  130. package/dist/core/substrate/gate.d.ts +4 -1
  131. package/dist/core/substrate/gate.js +5 -0
  132. package/dist/core/substrate/on-read.js +21 -32
  133. package/dist/core/substrate/render-node.d.ts +3 -2
  134. package/dist/core/substrate/render-node.js +3 -2
  135. package/dist/core/substrate/render.js +64 -37
  136. package/dist/core/substrate/schema.d.ts +17 -8
  137. package/dist/core/substrate/schema.js +14 -10
  138. package/dist/core/substrate/surface-match.d.ts +8 -7
  139. package/dist/core/substrate/surface-match.js +15 -14
  140. package/dist/core/user-settings.d.ts +4 -0
  141. package/dist/core/user-settings.js +1 -0
  142. package/dist/daemon/api/__tests__/profile-launch-gates.test.js +52 -3
  143. package/dist/daemon/api/handlers/human-requests.d.ts +2 -0
  144. package/dist/daemon/api/handlers/human-requests.js +409 -0
  145. package/dist/daemon/api/handlers/human.js +3 -0
  146. package/dist/daemon/api/handlers/inbox.js +3 -0
  147. package/dist/daemon/api/handlers/nodes.d.ts +1 -3
  148. package/dist/daemon/api/handlers/nodes.js +11 -46
  149. package/dist/daemon/api/handlers/prospective-chat-inventory.d.ts +2 -0
  150. package/dist/daemon/api/handlers/prospective-chat-inventory.js +59 -0
  151. package/dist/daemon/api/handlers/reviews.js +10 -2
  152. package/dist/daemon/api/server.js +4 -0
  153. package/dist/daemon/crtrd.js +6 -0
  154. package/dist/daemon/human/deliver-action.d.ts +16 -0
  155. package/dist/daemon/human/deliver-action.js +168 -0
  156. package/dist/daemon/human/finish.d.ts +8 -5
  157. package/dist/daemon/human/finish.js +45 -6
  158. package/dist/daemon/human/sweep.js +4 -1
  159. package/dist/daemon/reconcilers/human-delivery-lane.d.ts +10 -0
  160. package/dist/daemon/reconcilers/human-delivery-lane.js +41 -0
  161. package/dist/daemon/review/finish.d.ts +8 -3
  162. package/dist/daemon/review/finish.js +19 -1
  163. package/dist/types.d.ts +8 -0
  164. package/dist/types.js +1 -0
  165. package/package.json +1 -1
  166. package/runtime.lock.json +2 -2
  167. package/dist/builtin-memory/00-runtime-base.md +0 -55
  168. package/dist/builtin-memory/design.md +0 -55
  169. /package/dist/builtin-memory/{02-lifecycle/00-terminal.md → 02-turn-lifecycle/01-terminal.md} +0 -0
@@ -220,7 +220,7 @@ export class InboxController {
220
220
  async cancelFromInbox(dir) {
221
221
  this.submittingDir = dir;
222
222
  try {
223
- await cancelTicketViaDaemon(dir, { reason: 'Canceled from the inbox.', actor: 'human' });
223
+ await cancelTicketViaDaemon(dir, { reason: 'Canceled from the inbox.', actor: 'human', disposition: 'dismissed' });
224
224
  this.status = 'canceled';
225
225
  }
226
226
  catch (error) {
@@ -12,6 +12,7 @@ export class PageAdapter {
12
12
  this.manifest = opts.ticket.manifest;
13
13
  this.panel = mountPanel({
14
14
  manifest: opts.ticket.manifest,
15
+ document: opts.ticket.document,
15
16
  productKinds: opts.productKinds,
16
17
  initialResponses: opts.ticket.progress,
17
18
  cols: opts.cols,
@@ -46,7 +47,7 @@ export class PageAdapter {
46
47
  }
47
48
  reload(ticket) {
48
49
  this.manifest = ticket.manifest;
49
- this.panel.loadPage(ticket.manifest, { initialResponses: ticket.progress, productKinds: this.opts.productKinds });
50
+ this.panel.loadPage(ticket.manifest, { document: ticket.document, initialResponses: ticket.progress, productKinds: this.opts.productKinds });
50
51
  this.opts.onDirty();
51
52
  }
52
53
  close() { this.panel.unmount(); }
@@ -4,6 +4,7 @@ export declare function resolveTicketPage(dir: string, responses: PageResponses)
4
4
  export declare function cancelTicketViaDaemon(dir: string, opts: {
5
5
  reason: string;
6
6
  actor: string;
7
+ disposition?: 'canceled' | 'dismissed';
7
8
  }): Promise<void>;
8
9
  export declare function daemonErrorMessage(err: unknown): string;
9
10
  export type ResolveFailure = 'unreachable' | 'already_resolved' | 'delivery_failed' | 'other';
@@ -67,7 +67,9 @@ export function createReviewClient(opts = {}) {
67
67
  };
68
68
  },
69
69
  async cancel(reviewId, reason) {
70
- await request(() => cliClient().cancelReview(reviewId, { reason, actor: 'human' }));
70
+ // The recipient surface: closing a review here is a dismissal, never the
71
+ // requester withdrawing it.
72
+ await request(() => cliClient().cancelReview(reviewId, { reason, actor: 'human', disposition: 'dismissed' }));
71
73
  },
72
74
  };
73
75
  }
@@ -1,13 +1,32 @@
1
+ import { projectPageDisplayMarkdown } from '../../../core/human/page-markdown.js';
1
2
  import { handleKeypress } from './input.js';
2
3
  import { clampItemReviewScroll, renderFinal, renderItemReview, renderOverview } from './render.js';
3
4
  import { pageComplete, slotAnswered } from './slots.js';
4
- function buildInitialState(manifest, initialResponses, productKinds, editorAvailable, wrapWidth) {
5
+ /** Same projection the inline chat block reads (page-block.ts) — the authored
6
+ * prose outside slot tags. A malformed or unreadable document just yields no
7
+ * display content here, same as the inline block's own reload() fallback. */
8
+ function displayMarkdownOf(manifest, document) {
9
+ if (manifest.dialect !== 'jsx' || document === undefined)
10
+ return '';
11
+ try {
12
+ return projectPageDisplayMarkdown(document, manifest);
13
+ }
14
+ catch {
15
+ return '';
16
+ }
17
+ }
18
+ function buildInitialState(manifest, document, initialResponses, productKinds, editorAvailable, wrapWidth) {
5
19
  const responses = new Map();
6
20
  const validIds = new Set(manifest.slots.flatMap((slot) => slot.id === undefined ? [] : [slot.id]));
7
21
  for (const [id, response] of Object.entries(initialResponses ?? {}))
8
22
  if (validIds.has(id))
9
23
  responses.set(id, response);
10
- const state = { phase: manifest.slots.length === 1 ? 'item-review' : 'overview', currentIndex: 0, manifest, slots: manifest.slots, responses, productKinds, inputMode: null, selectedAction: 0, bodyMode: 'question', scrollOffset: 0, bodyScrollOffsets: { question: 0 }, hscrollOffset: 0, hscrollMax: 0, wrapWidth, editorAvailable };
24
+ const displayMarkdown = displayMarkdownOf(manifest, document);
25
+ // Single-slot pages skip straight to item-review to save a step — but only
26
+ // when there is no display prose to show first; otherwise that prose would
27
+ // never be seen.
28
+ const phase = manifest.slots.length === 1 && displayMarkdown === '' ? 'item-review' : 'overview';
29
+ const state = { phase, currentIndex: 0, manifest, displayMarkdown, slots: manifest.slots, responses, productKinds, inputMode: null, selectedAction: 0, bodyMode: 'question', scrollOffset: 0, bodyScrollOffsets: { question: 0 }, hscrollOffset: 0, hscrollMax: 0, wrapWidth, editorAvailable };
11
30
  const first = manifest.slots.findIndex((slot) => slot.id !== undefined && !slotAnswered(state, slot));
12
31
  if (first >= 0)
13
32
  state.currentIndex = first;
@@ -16,7 +35,7 @@ function buildInitialState(manifest, initialResponses, productKinds, editorAvail
16
35
  export function collectResponses(state) { return Object.fromEntries(state.responses); }
17
36
  function rebindPersist(internals) { internals.state.persist = () => internals.callbacks.onProgress?.(collectResponses(internals.state)); }
18
37
  export function mountPanel(opts) {
19
- const internals = { state: buildInitialState(opts.manifest, opts.initialResponses, opts.productKinds ?? [], opts.onEditorRequest !== undefined, opts.cols), cols: opts.cols, rows: opts.rows, mounted: true, callbacks: { onProgress: opts.onProgress, onComplete: opts.onComplete, onExit: opts.onExit, onDirty: opts.onDirty, onEditorRequest: opts.onEditorRequest } };
38
+ const internals = { state: buildInitialState(opts.manifest, opts.document, opts.initialResponses, opts.productKinds ?? [], opts.onEditorRequest !== undefined, opts.cols), cols: opts.cols, rows: opts.rows, mounted: true, callbacks: { onProgress: opts.onProgress, onComplete: opts.onComplete, onExit: opts.onExit, onDirty: opts.onDirty, onEditorRequest: opts.onEditorRequest } };
20
39
  rebindPersist(internals);
21
40
  const renderLines = () => {
22
41
  if (internals.state.phase === 'overview')
@@ -51,7 +70,7 @@ export function mountPanel(opts) {
51
70
  return;
52
71
  const prior = collectResponses(internals.state);
53
72
  const merged = { ...(loadOpts?.initialResponses ?? {}), ...prior };
54
- internals.state = buildInitialState(manifest, merged, loadOpts?.productKinds ?? internals.state.productKinds, internals.callbacks.onEditorRequest !== undefined, internals.cols);
73
+ internals.state = buildInitialState(manifest, loadOpts?.document, merged, loadOpts?.productKinds ?? internals.state.productKinds, internals.callbacks.onEditorRequest !== undefined, internals.cols);
55
74
  rebindPersist(internals);
56
75
  },
57
76
  canAcceptHostKeys: () => internals.mounted && internals.state.inputMode === null,
@@ -29,10 +29,16 @@ function commentLabel(slot, anchor) {
29
29
  }
30
30
  export function renderOverview(state, cols, rows) {
31
31
  const maxW = Math.min(Math.max(20, cols - 4), 120);
32
+ const paneW = Math.max(20, cols - 4);
32
33
  const lines = ['', ` ${BOLD}${CYAN}${sanitize(state.manifest.title)}${RESET}`];
33
34
  if (state.manifest.subtitle)
34
35
  for (const line of wrap(sanitize(state.manifest.subtitle), maxW))
35
36
  lines.push(` ${DIM}${line}${RESET}`);
37
+ if (state.displayMarkdown !== '') {
38
+ lines.push('');
39
+ for (const line of mdLines(state.displayMarkdown, maxW, paneW))
40
+ lines.push(` ${line}`);
41
+ }
36
42
  const hasBody = state.slots.length > 0;
37
43
  if (hasBody)
38
44
  lines.push(` ${DIM}${hline(maxW)}${RESET}`, '');
@@ -20,6 +20,10 @@ export interface TuiState {
20
20
  phase: Phase;
21
21
  currentIndex: number;
22
22
  manifest: PageManifest;
23
+ /** The authored display JSX (headings, paragraphs, prose outside slots),
24
+ * projected to markdown — same projection the inline chat block uses.
25
+ * Empty when the page has none, or its document was unavailable. */
26
+ displayMarkdown: string;
23
27
  slots: PageSlot[];
24
28
  responses: Map<string, SlotResponse>;
25
29
  productKinds: ProductPageComponents;
@@ -39,6 +43,9 @@ export interface TuiState {
39
43
  }
40
44
  export interface MountedPanelOpts {
41
45
  manifest: PageManifest;
46
+ /** The raw page document — needed only to project display markdown; a jsx
47
+ * page without one just shows no display content, same as a read failure. */
48
+ document?: string;
42
49
  productKinds?: ProductPageComponents;
43
50
  initialResponses?: PageResponses | null;
44
51
  cols: number;
@@ -55,6 +62,7 @@ export interface MountedPanel {
55
62
  handleResize(cols: number, rows: number): string[];
56
63
  unmount(): void;
57
64
  loadPage(manifest: PageManifest, opts?: {
65
+ document?: string;
58
66
  initialResponses?: PageResponses | null;
59
67
  productKinds?: ProductPageComponents;
60
68
  }): void;
@@ -101,11 +101,11 @@ test('human help carries the page authoring model and follows the page-surface s
101
101
  test('page_surface removes the terminal-only human surfaces from the tree', () => {
102
102
  const names = () => registerHuman().children.map((child) => child.name);
103
103
  withPageSurface(false, () => {
104
- assert.deepEqual(names(), ['components', 'send', 'review', 'feedback', 'show', 'cancel', 'list', 'resolve']);
104
+ assert.deepEqual(names(), ['components', 'send', 'review', 'feedback', 'show', 'request', 'cancel', 'list', 'resolve']);
105
105
  });
106
106
  withPageSurface(true, () => {
107
107
  const children = names();
108
- assert.deepEqual(children, ['components', 'send', 'feedback', 'cancel', 'list', 'resolve']);
108
+ assert.deepEqual(children, ['components', 'send', 'feedback', 'request', 'cancel', 'list', 'resolve']);
109
109
  const human = registerHuman();
110
110
  assert.doesNotMatch(human.help.model ?? '', /`review`|`show`/);
111
111
  assert.doesNotMatch(human.rootEntry?.useWhen ?? '', /review a document|live display/);
@@ -0,0 +1,2 @@
1
+ import type { BranchDef } from '../../core/command.js';
2
+ export declare const humanRequestBranch: BranchDef;
@@ -0,0 +1,281 @@
1
+ // `crtr human request` — the command-line face of the durable programmatic
2
+ // request contract. A request is an ordinary page ticket in the human inbox
3
+ // whose creator may exit immediately: there is no reply bridge, the terminal
4
+ // result is durable, and an optional named action carries the completion
5
+ // document to a local command. Every leaf is a thin typed call on crtrd; the
6
+ // daemon owns validation, settlement, and delivery.
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { defineBranch, defineLeaf } from '../../core/command.js';
9
+ import { InputError } from '../../core/io.js';
10
+ import { cliClient, rethrowAsCliError } from '../api-client.js';
11
+ // ---------------------------------------------------------------------------
12
+ // shared input helpers
13
+ // ---------------------------------------------------------------------------
14
+ function readJsonFile(path, field, shape) {
15
+ if (!existsSync(path)) {
16
+ throw new InputError({ error: 'not_found', message: `no such file: ${path}`, field, next: `Pass --${field} PATH pointing at a JSON file holding ${shape}.` });
17
+ }
18
+ let raw;
19
+ try {
20
+ raw = readFileSync(path, 'utf8');
21
+ }
22
+ catch (error) {
23
+ throw new InputError({ error: 'unreadable_file', message: `could not read ${path}: ${String(error)}`, field, next: 'Pass a readable JSON file.' });
24
+ }
25
+ let parsed;
26
+ try {
27
+ parsed = JSON.parse(raw);
28
+ }
29
+ catch (error) {
30
+ throw new InputError({ error: 'invalid_json', message: `${path} is not valid JSON: ${String(error)}`, field, next: `Write ${shape} into the file as JSON.` });
31
+ }
32
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
33
+ throw new InputError({ error: 'invalid_field', message: `${path} must hold a JSON object`, field, next: `Write ${shape} into the file as a JSON object.` });
34
+ }
35
+ return parsed;
36
+ }
37
+ /** The page crosses the wire inline, so the CLI reads the authored file and
38
+ * derives its dialect from the extension — the same rule page authoring uses. */
39
+ function readPageFile(path) {
40
+ const html = /\.html?$/i.test(path);
41
+ if (!html && !path.endsWith('.tsx')) {
42
+ throw new InputError({ error: 'invalid_field', message: `page source file must be .tsx, .html, or .htm: ${path}`, field: 'page', next: 'Author the page as a .tsx module or a complete .html document.' });
43
+ }
44
+ if (!existsSync(path)) {
45
+ throw new InputError({ error: 'not_found', message: `page source file does not exist: ${path}`, field: 'page', next: 'Pass --page PATH pointing at the authored page.' });
46
+ }
47
+ return { dialect: html ? 'html' : 'jsx', source: readFileSync(path, 'utf8') };
48
+ }
49
+ function requestId(input) {
50
+ const id = typeof input['request_id'] === 'string' ? input['request_id'].trim() : '';
51
+ if (id === '') {
52
+ throw new InputError({ error: 'missing_request_id', message: 'a request id is required', field: 'request_id', next: 'Pass the request_id returned by `crtr human request create`.' });
53
+ }
54
+ return id;
55
+ }
56
+ /** The one projection of a request record onto leaf output. Absent fields stay
57
+ * absent: a dismissal or a withdrawal has no responses to report. */
58
+ function requestResult(dto) {
59
+ return {
60
+ request_id: dto.request_id,
61
+ state: dto.state,
62
+ title: dto.title,
63
+ ...(dto.subtitle === undefined ? {} : { subtitle: dto.subtitle }),
64
+ source: dto.source,
65
+ emitted_at: dto.emitted_at,
66
+ ...(dto.settled_at === undefined ? {} : { settled_at: dto.settled_at }),
67
+ ...(dto.responses === undefined ? {} : { responses: dto.responses }),
68
+ ...(dto.reason === undefined ? {} : { reason: dto.reason }),
69
+ ...(dto.actor === undefined ? {} : { actor: dto.actor }),
70
+ ...(dto.action === undefined ? {} : { action: dto.action }),
71
+ ...(dto.delivery === undefined ? {} : { delivery: dto.delivery }),
72
+ };
73
+ }
74
+ const RECORD_OUTPUT = [
75
+ { name: 'request_id', type: 'string', required: true, constraint: 'The request — the same 64-hex id the human inbox lists it under.' },
76
+ { name: 'state', type: 'pending | answered | dismissed | canceled', required: true, constraint: 'answered: the person (or an authorized responder) submitted the typed responses. dismissed: the recipient surface closed it unanswered. canceled: the requester withdrew it.' },
77
+ { name: 'title', type: 'string', required: true, constraint: 'Page title as currently published.' },
78
+ { name: 'subtitle', type: 'string', required: false, constraint: 'Page subtitle when the page carries one.' },
79
+ { name: 'source', type: 'object', required: true, constraint: 'Stored provenance from the request creator: sessionName?, askedBy?, emittedAt?, profileName?, nodeId?.' },
80
+ { name: 'emitted_at', type: 'string', required: true, constraint: 'UTC ISO instant of creation; a replace never changes it.' },
81
+ { name: 'settled_at', type: 'string', required: false, constraint: 'UTC ISO instant of the terminal result. Absent while pending.' },
82
+ { name: 'responses', type: 'object', required: false, constraint: 'The typed slot map, keyed by response-bearing component id. Present only when state is answered.' },
83
+ { name: 'reason', type: 'string', required: false, constraint: 'Note recorded by the dismissal or the withdrawal.' },
84
+ { name: 'actor', type: 'string', required: false, constraint: 'Who settled it, when the settling surface named itself.' },
85
+ { name: 'action', type: 'object', required: false, constraint: '{name, payload} frozen at creation; an omitted payload is frozen as null. Absent when no action is bound.' },
86
+ { name: 'delivery', type: 'object', required: false, constraint: 'Completion-delivery state for the bound action: {state: none | pending | running | accepted | permanent_failed, attempt, next_attempt_at?, accepted_at?, permanent_failed_at?, last_failure?}. Absent when no action is bound.' },
87
+ ];
88
+ // ---------------------------------------------------------------------------
89
+ // create
90
+ // ---------------------------------------------------------------------------
91
+ const createLeaf = defineLeaf({
92
+ name: 'create',
93
+ description: 'create a durable request from a JSON request file',
94
+ whenToUse: 'a script or backend needs a human decision that must survive its own exit, rather than an answer routed back to a live node.',
95
+ help: {
96
+ name: 'human request create',
97
+ summary: 'create one durable human request from the typed create object',
98
+ params: [
99
+ {
100
+ kind: 'flag',
101
+ name: 'request-file',
102
+ type: 'path',
103
+ required: true,
104
+ constraint: 'JSON file holding the create object: {"page":{"dialect":"jsx"|"html","source":"<the authored page text, inline>"}, "delivery"?:{"placement":"inline"|"panel"}, "source"?:{"sessionName"?,"askedBy"?,"emittedAt"?,"profileName"?,"nodeId"?}, "creator_cwd"?:"<absolute dir>", "action"?:{"name":"<declared action>","payload":<any JSON, null when omitted>}}. The page text is inline, never a path — the request must stay readable after the creating process is gone. creator_cwd defaults to this directory and is the scope the action name resolves from. delivery.inbox and delivery.reply are pinned: a programmatic request is always answerable from the inbox and never routes to an agent bridge. Unknown fields are rejected.',
105
+ },
106
+ ],
107
+ output: [
108
+ { name: 'request_id', type: 'string', required: true, constraint: 'The created request — pass it to get/replace/respond/cancel. Stable, and the deduplication key every completion destination keys on.' },
109
+ { name: 'state', type: 'string', required: true, constraint: 'Always "pending": creation never settles.' },
110
+ { name: 'action', type: 'object', required: false, constraint: '{name} of the frozen action binding. Absent when the request carries no action.' },
111
+ { name: 'delivery_state', type: 'string', required: true, constraint: 'Always "none" at creation: delivery is enqueued at settlement, not before.' },
112
+ ],
113
+ outputKind: 'object',
114
+ effects: [
115
+ 'Publishes one durable page ticket into the human inbox. It has no reply bridge and outlives this process.',
116
+ 'An action name is resolved from the humanActions map in scope config (project ancestors, then user) BEFORE anything is written — an unknown or unusable name is rejected and leaves no inbox row for a person to answer.',
117
+ 'A resolved action is frozen onto the ticket: name, payload, resolved argv, and cwd. replace can never change it; a different effect needs a cancel and a new request.',
118
+ ],
119
+ },
120
+ run: async (input) => {
121
+ const path = input['requestFile'];
122
+ const body = readJsonFile(path, 'request-file', 'the create object');
123
+ if (body['creator_cwd'] === undefined)
124
+ body['creator_cwd'] = process.cwd();
125
+ try {
126
+ const created = await cliClient().createHumanRequest(body);
127
+ return {
128
+ request_id: created.request_id,
129
+ state: created.state,
130
+ ...(created.action === undefined ? {} : { action: created.action }),
131
+ delivery_state: created.delivery_state,
132
+ };
133
+ }
134
+ catch (error) {
135
+ rethrowAsCliError(error);
136
+ }
137
+ },
138
+ });
139
+ // ---------------------------------------------------------------------------
140
+ // get
141
+ // ---------------------------------------------------------------------------
142
+ const getLeaf = defineLeaf({
143
+ name: 'get',
144
+ description: 'read one request, its terminal result, and its delivery state',
145
+ whenToUse: 'you need the current state of a request you created — including the answers, once someone has settled it.',
146
+ help: {
147
+ name: 'human request get',
148
+ summary: 'read one durable request',
149
+ params: [{ kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' }],
150
+ output: [...RECORD_OUTPUT],
151
+ outputKind: 'object',
152
+ effects: ['None. Read-only.'],
153
+ },
154
+ run: async (input) => {
155
+ try {
156
+ return requestResult(await cliClient().getHumanRequest(requestId(input)));
157
+ }
158
+ catch (error) {
159
+ rethrowAsCliError(error);
160
+ }
161
+ },
162
+ });
163
+ // ---------------------------------------------------------------------------
164
+ // replace
165
+ // ---------------------------------------------------------------------------
166
+ const replaceLeaf = defineLeaf({
167
+ name: 'replace',
168
+ description: 'revise a pending request\'s page in place',
169
+ whenToUse: 'what you are asking changed while the request is still pending, and the same request should keep its identity and its frozen action.',
170
+ help: {
171
+ name: 'human request replace',
172
+ summary: 'republish a pending request\'s page',
173
+ params: [
174
+ { kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' },
175
+ { kind: 'flag', name: 'page', type: 'path', required: true, constraint: 'The revised page: a .tsx module or a complete .html/.htm document. Read here and sent inline.' },
176
+ ],
177
+ output: [...RECORD_OUTPUT],
178
+ outputKind: 'object',
179
+ effects: [
180
+ 'Rewrites the page and its typed response contract in place; open surfaces reload it without a second request.',
181
+ 'Identity is untouched: request id, provenance, emitted time, delivery, and the frozen action binding all survive verbatim.',
182
+ 'Refused with already_settled once the request has a terminal result — a settled request is revised by cancelling and creating a new one.',
183
+ ],
184
+ },
185
+ run: async (input) => {
186
+ const id = requestId(input);
187
+ const body = { page: readPageFile(input['page']) };
188
+ try {
189
+ return requestResult(await cliClient().replaceHumanRequest(id, body));
190
+ }
191
+ catch (error) {
192
+ rethrowAsCliError(error);
193
+ }
194
+ },
195
+ });
196
+ // ---------------------------------------------------------------------------
197
+ // respond
198
+ // ---------------------------------------------------------------------------
199
+ const respondLeaf = defineLeaf({
200
+ name: 'respond',
201
+ description: 'settle a pending request with typed answers',
202
+ whenToUse: 'an authorized host is submitting the answers on the person\'s behalf, rather than the person answering in their inbox.',
203
+ help: {
204
+ name: 'human request respond',
205
+ summary: 'answer a pending request',
206
+ params: [
207
+ { kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' },
208
+ {
209
+ kind: 'flag',
210
+ name: 'response-file',
211
+ type: 'path',
212
+ required: true,
213
+ constraint: 'JSON file holding the respond object: {"responses":{"<component_id>":{...}}, "actor"?:"<who answered>"}. One typed response per response-bearing component; the daemon validates the complete map against the currently published page.',
214
+ },
215
+ ],
216
+ output: [...RECORD_OUTPUT],
217
+ outputKind: 'object',
218
+ effects: [
219
+ 'Settles the request as answered and drops it from the human inbox.',
220
+ 'Competes with the person\'s own answer, a recipient dismissal, and a requester cancel through one first-writer-wins store: a losing attempt returns already_settled and changes nothing.',
221
+ 'When an action is bound, the winning settlement enqueues one at-least-once completion delivery keyed on the request id.',
222
+ ],
223
+ },
224
+ run: async (input) => {
225
+ const id = requestId(input);
226
+ const body = readJsonFile(input['responseFile'], 'response-file', 'the respond object');
227
+ try {
228
+ return requestResult(await cliClient().respondHumanRequest(id, body));
229
+ }
230
+ catch (error) {
231
+ rethrowAsCliError(error);
232
+ }
233
+ },
234
+ });
235
+ // ---------------------------------------------------------------------------
236
+ // cancel
237
+ // ---------------------------------------------------------------------------
238
+ const cancelLeaf = defineLeaf({
239
+ name: 'cancel',
240
+ description: 'withdraw a pending request',
241
+ whenToUse: 'the decision you asked for stopped mattering, or the effect must change — the action binding is immutable, so a new effect needs a new request.',
242
+ help: {
243
+ name: 'human request cancel',
244
+ summary: 'withdraw a pending request',
245
+ params: [
246
+ { kind: 'positional', name: 'request_id', type: 'string', required: true, constraint: 'request_id returned by `human request create`.' },
247
+ { kind: 'flag', name: 'reason', type: 'string', required: false, constraint: 'Short note recorded on the terminal result and carried in the completion document.' },
248
+ ],
249
+ output: [...RECORD_OUTPUT],
250
+ outputKind: 'object',
251
+ effects: [
252
+ 'Settles the request as canceled and drops it from the human inbox — the person is no longer asked.',
253
+ 'Races the person\'s answer through the same first-writer-wins store; whoever lands first is authoritative and the loser returns already_settled.',
254
+ 'When an action is bound, the winning settlement enqueues one completion delivery carrying the canceled event.',
255
+ ],
256
+ },
257
+ run: async (input) => {
258
+ const id = requestId(input);
259
+ const reason = typeof input['reason'] === 'string' && input['reason'] !== '' ? input['reason'] : undefined;
260
+ try {
261
+ return requestResult(await cliClient().cancelHumanRequest(id, reason === undefined ? {} : { reason }));
262
+ }
263
+ catch (error) {
264
+ rethrowAsCliError(error);
265
+ }
266
+ },
267
+ });
268
+ // ---------------------------------------------------------------------------
269
+ // Registration
270
+ // ---------------------------------------------------------------------------
271
+ export const humanRequestBranch = defineBranch({
272
+ name: 'request',
273
+ description: 'durable requests that outlive the process that made them',
274
+ whenToUse: 'a script or backend needs a human decision whose outcome must survive its own exit, instead of an answer pushed back to a live node.',
275
+ help: {
276
+ name: 'human request',
277
+ summary: 'durable programmatic human requests — create, read, revise, and settle',
278
+ model: 'A request is the same page ticket `human send` publishes, minus the agent bridge: nothing waits on it, and the outcome is read with `get` or carried to a local command by a named action. Reach for it when the caller will be gone before the person answers; when a live node should receive the answer, use `crtr human send` instead.\n\nThe page and its typed response contract stay revisable with `replace` while pending. The action binding does not: name, payload, resolved argv, and cwd are frozen at creation, so a different effect means `cancel` plus a new request. An action is a name declared in the humanActions map of scope config — there is no command, shell string, or callback URL anywhere in this surface.\n\nA request ends exactly once. `respond` (an authorized host answering), the person answering in their own inbox, a recipient dismissal, and `cancel` all compete through one first-writer-wins settlement; the loser gets already_settled and no second delivery. Only the winner enqueues the completion document, delivered at least once — the receiving command must deduplicate on the request id.',
279
+ },
280
+ children: [createLeaf, getLeaf, replaceLeaf, respondLeaf, cancelLeaf],
281
+ });
@@ -9,6 +9,7 @@ import { humanList, humanResolve, humanCancel } from './human/queue.js';
9
9
  import { humanReviewBranch } from './human/review.js';
10
10
  import { humanFeedbackBranch } from './human/feedback.js';
11
11
  import { humanComponents } from './human/components.js';
12
+ import { humanRequestBranch } from './human/request.js';
12
13
  import { pageHelpText } from './human/shared.js';
13
14
  export function registerHuman() {
14
15
  // `page_surface` marks a host whose human surface is a rendered page product
@@ -21,9 +22,10 @@ export function registerHuman() {
21
22
  const concept = pageSurface
22
23
  ? 'human-in-the-loop decisions and structured pages'
23
24
  : 'human-in-the-loop decisions, document review, and live display';
25
+ const durableRequests = '`request` publishes the same page with no bridge at all, for a caller that will have exited before the answer arrives: its outcome is read back or carried to a named local action.';
24
26
  const ticketModel = pageSurface
25
- ? 'Tickets queue in the human inbox; nothing opens on screen. `send` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not.'
26
- : 'Tickets queue in the human inbox; nothing opens on screen. `send` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not. `review` is for live document review with anchored comments; `show` is a passive tmux live-watch rather than a ticket.';
27
+ ? `Tickets queue in the human inbox; nothing opens on screen. \`send\` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not. ${durableRequests}`
28
+ : `Tickets queue in the human inbox; nothing opens on screen. \`send\` routes completion back when the page carries response-bearing components, and publishes a standalone announcement when it does not. ${durableRequests} \`review\` is for live document review with anchored comments; \`show\` is a passive tmux live-watch rather than a ticket.`;
27
29
  return defineBranch({
28
30
  name: 'human',
29
31
  rootEntry: {
@@ -48,6 +50,7 @@ export function registerHuman() {
48
50
  ...(pageSurface ? [] : [humanReviewBranch]),
49
51
  humanFeedbackBranch,
50
52
  ...(pageSurface ? [] : [humanShow]),
53
+ humanRequestBranch,
51
54
  humanCancel,
52
55
  humanList,
53
56
  humanResolve,
@@ -105,8 +105,8 @@ export declare function overlayParam(name: string, overrides?: Partial<FlagParam
105
105
  * `--doc-rationale`, because `--rationale` there means why THIS REVISION is
106
106
  * happening. Same field, same prose, two flag names that cannot be confused. */
107
107
  export declare const DOC_RATIONALE_CONSTRAINT = "Frontmatter rationale \u2014 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 the flag preserves an existing rationale unchanged.";
108
- export declare const GUIDE_SURFACES = "Every doc appears in its directory\u2019s listing by default (suppress with --unlisted); everything beyond the listing is explicit `surfaces` routing \u2014 entries declaring WHEN the doc delivers and how much. Events: `boot` delivers in the boot catalog every agent sees; `workspace-open` delivers in first-message context when cwd/profile mounts the doc\u2019s project store (project stores only); `read` fires when the agent reads a matching file (globs vs the file\u2019s absolute path and basename, `./`-anchored globs vs its path relative to the store\u2019s owning repo dir, `match-frontmatter` predicates over the read file\u2019s own YAML frontmatter); `memory-read` fires when another memory doc is read (globs vs that doc\u2019s canonical name, `./` anchored to this doc\u2019s own name directory); `command` fires when a matching shell command runs (globs vs the whole command string, `*` crossing `/`). `at` sets how much delivers: `name` the bare tag, `preview` the routing line, `content` the whole body. Each entry is paid by every future agent it fires on, so default down: no surfaces at all is correct for reference depth reached through listings and [[links]], and when a doc fits in a single sentence, deliver `content` directly \u2014 a `preview` 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.";
108
+ export declare const GUIDE_SURFACES = "Every doc appears in its directory\u2019s listing by default (suppress with --unlisted); everything beyond the listing is explicit `surfaces` routing \u2014 entries declaring WHEN the doc delivers and how much. Events: `boot` delivers in the boot catalog every agent sees; `workspace-open` delivers in first-message context when cwd/profile mounts the doc\u2019s project store (project stores only); `read` fires when the agent reads a matching file (globs vs the file\u2019s absolute path and basename, `./`-anchored globs vs its path relative to the store\u2019s owning repo dir, `match-frontmatter` predicates over the read file\u2019s own YAML frontmatter); `memory-read` fires when another memory doc is read (globs vs that doc\u2019s canonical name, `./` anchored to this doc\u2019s own name directory); `command` fires when a matching shell command runs (globs vs the whole command string, `*` crossing `/`). An entry may also carry `gate`, a node-config predicate using the same vocabulary as the document-level `gate`: event constraints and entry gate both must match, then all participating entries fold to the highest `at` (`content` > `preview` > `name`), with no cross-entry deny precedence. The document-level `gate` remains the hard eligibility check: when it fails, no automatic surface can deliver the document. `at` sets how much delivers: `name` the bare tag, `preview` the routing line, `content` the whole body. Explicit `memory read` and listings remain deliberate access and ignore gates/rungs; only companion docs routed by their `memory-read` entries use entry gates. Each entry is paid by every future agent it fires on, so default down: no surfaces at all is correct for reference depth reached through listings and [[links]], and when a doc fits in a single sentence, deliver `content` directly \u2014 a `preview` 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.";
109
109
  export declare const GUIDE_ROUTING_LINE = "The routing line (--when-and-why-to-read) is the only text an agent reads before deciding to load the doc. The test for its when-clause: it names an observable circumstance in the reader\u2019s current work, not the doc\u2019s topic reworded as an activity. If the WHEN can be inferred from the title alone, it is not a real trigger. Bad on a todo list: \"When planning or prioritizing work across this profile.\" Good: \"When the user mentions something from their todos, or asks what is still outstanding across this profile.\" The test for its because-clause: if it can be derived by paraphrasing the doc\u2019s advice, it is a restatement, not a payoff \u2014 a real payoff names a consequence in the reader\u2019s 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\" \u2014 the doc\u2019s 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 \u2014 ask the user one sharp question instead of improvising.";
110
- export declare const GUIDE_PREDICATE_VOCABULARY = "Gate and match-frontmatter 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.";
110
+ export declare const GUIDE_PREDICATE_VOCABULARY = "Document gates, surface-entry gates, and match-frontmatter 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.";
111
111
  export declare const GUIDE_DOC_LINKS = "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 \u2014 the same identifier `crtr memory read` takes. A bare directory name is a valid link too: following it returns that directory\u2019s listing, a browse entrance rather than a doc. 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 or directory, and `crtr memory read` lists a doc\u2019s resolvable links alongside its body. There is no alias or label form.";
112
112
  export {};
@@ -164,7 +164,7 @@ export function coerceGate(raw) {
164
164
  return result;
165
165
  }
166
166
  // The frontmatter keys one `surfaces` entry may carry.
167
- const SURFACE_ENTRY_KEYS = new Set(['on', 'match', 'match-frontmatter', 'at']);
167
+ const SURFACE_ENTRY_KEYS = new Set(['on', 'match', 'match-frontmatter', 'gate', 'at']);
168
168
  /** Coerce one `--surface` value into a validated surfaces entry. Strict where
169
169
  * the runtime parser is tolerant: a flag that would be silently dropped or
170
170
  * trimmed at render time is an authoring mistake and fails HERE. The entry is
@@ -173,13 +173,13 @@ const SURFACE_ENTRY_KEYS = new Set(['on', 'match', 'match-frontmatter', 'at']);
173
173
  export function coerceSurface(raw) {
174
174
  const parsed = yamlParse(raw);
175
175
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
176
- throw usage(`--surface must be a YAML/JSON object entry {on, at, match?, match-frontmatter?}, got ${JSON.stringify(parsed)}. ` +
176
+ throw usage(`--surface must be a YAML/JSON object entry {on, at, match?, match-frontmatter?, gate?}, got ${JSON.stringify(parsed)}. ` +
177
177
  `Example: --surface '{on: read, match: "src/**", at: content}'`);
178
178
  }
179
179
  const rec = parsed;
180
180
  for (const key of Object.keys(rec)) {
181
181
  if (!SURFACE_ENTRY_KEYS.has(key)) {
182
- throw usage(`--surface: unknown key \`${key}\` (an entry carries only on, match, match-frontmatter, at)`);
182
+ throw usage(`--surface: unknown key \`${key}\` (an entry carries only on, match, match-frontmatter, gate, at)`);
183
183
  }
184
184
  }
185
185
  const on = rec['on'];
@@ -223,10 +223,15 @@ export function coerceSurface(raw) {
223
223
  if ((on === 'read' || on === 'memory-read' || on === 'command') && match === undefined && matchFrontmatter === undefined) {
224
224
  throw usage(`--surface: a \`${on}\` entry requires \`match\`${on === 'read' ? ' or `match-frontmatter`' : ''}`);
225
225
  }
226
+ const gate = rec['gate'];
227
+ if (gate !== undefined && (gate === null || typeof gate !== 'object' || Array.isArray(gate))) {
228
+ throw usage(`--surface: invalid \`gate\`: ${JSON.stringify(gate)} (expected a field→matcher object)`);
229
+ }
226
230
  return {
227
231
  on,
228
232
  ...(match !== undefined ? { match } : {}),
229
233
  ...(matchFrontmatter !== undefined ? { 'match-frontmatter': matchFrontmatter } : {}),
234
+ ...(gate !== undefined ? { gate } : {}),
230
235
  at,
231
236
  };
232
237
  }
@@ -503,7 +508,7 @@ export const FRONTMATTER_OVERLAY_PARAMS = {
503
508
  'when-and-why-to-read': { kind: 'flag', name: 'when-and-why-to-read', type: 'string', required: false, constraint: 'ONE routing sentence: "When <circumstance>, this <kind> should be read because <broader downstream payoff>." WHY is the reader\u2019s payoff \u2014 the consequence they secure for their task by reading \u2014 NEVER the doc summary, its rule, or that rule reworded as an outcome (a benefit-shaped restatement still fails). Rendered verbatim as the preview.' },
504
509
  'short-form': { kind: 'flag', name: 'short-form', type: 'string', required: false, constraint: 'Frontmatter short-form \u2014 a very abbreviated version of the content, the hook shown in `crtr memory list`.' },
505
510
  'unlisted': { kind: 'flag', name: 'unlisted', type: 'bool', required: false, default: false, constraint: 'Suppress this doc from directory listings. Suppression only — explicit reads, [[links]], and surfaces entries still work.' },
506
- 'surface': { kind: 'flag', name: 'surface', type: 'string', required: false, repeatable: true, constraint: 'One routing entry per occurrence, as a YAML/JSON object `{on, at, match?, match-frontmatter?}`; the flag set replaces the document’s whole surfaces list. `on` is boot|workspace-open|read|memory-read|command; `at` is name|preview|content. `match` holds the event’s globs — required on read/memory-read/command (a read entry may carry `match-frontmatter`, a predicate over the read file’s own frontmatter, instead), meaningless on boot/workspace-open. A `./`-anchored glob is relative: for `read` to the store’s owning repo dir, for `memory-read` to the doc’s own name directory. Constraints within one entry AND together; entries OR together.' },
511
+ 'surface': { kind: 'flag', name: 'surface', type: 'string', required: false, repeatable: true, constraint: 'One routing entry per occurrence, as a YAML/JSON object `{on, at, match?, match-frontmatter?, gate?}`; the flag set replaces the document’s whole surfaces list. `on` is boot|workspace-open|read|memory-read|command; `at` is name|preview|content. `match` holds the event’s globs — required on read/memory-read/command (a read entry may carry `match-frontmatter`, a predicate over the read file’s own frontmatter, instead), meaningless on boot/workspace-open. Optional entry `gate` is a node-config predicate using the same vocabulary as the document gate; its event constraints and gate both match before it participates. A `./`-anchored glob is relative: for `read` to the store’s owning repo dir, for `memory-read` to the doc’s own name directory. Participating entries fold to their highest `at`; there is no cross-entry deny precedence.' },
507
512
  'gate': { kind: 'flag', name: 'gate', type: 'string', required: false, constraint: 'Frontmatter gate \u2014 YAML/JSON object predicate over node config using the same field/matcher vocabulary described in the guide.' },
508
513
  'slash': { 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 `:`) \u2014 the doc body becomes the command\u2019s injected prompt. Default false: most docs are consulted, not invoked.' },
509
514
  };
@@ -521,7 +526,7 @@ export function overlayParam(name, overrides = {}, extraConstraint) {
521
526
  * `--doc-rationale`, because `--rationale` there means why THIS REVISION is
522
527
  * happening. Same field, same prose, two flag names that cannot be confused. */
523
528
  export const DOC_RATIONALE_CONSTRAINT = 'Frontmatter rationale \u2014 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 the flag preserves an existing rationale unchanged.';
524
- export const GUIDE_SURFACES = 'Every doc appears in its directory’s listing by default (suppress with --unlisted); everything beyond the listing is explicit `surfaces` routing — entries declaring WHEN the doc delivers and how much. Events: `boot` delivers in the boot catalog every agent sees; `workspace-open` delivers in first-message context when cwd/profile mounts the doc’s project store (project stores only); `read` fires when the agent reads a matching file (globs vs the file’s absolute path and basename, `./`-anchored globs vs its path relative to the store’s owning repo dir, `match-frontmatter` predicates over the read file’s own YAML frontmatter); `memory-read` fires when another memory doc is read (globs vs that doc’s canonical name, `./` anchored to this doc’s own name directory); `command` fires when a matching shell command runs (globs vs the whole command string, `*` crossing `/`). `at` sets how much delivers: `name` the bare tag, `preview` the routing line, `content` the whole body. Each entry is paid by every future agent it fires on, so default down: no surfaces at all is correct for reference depth reached through listings and [[links]], and when a doc fits in a single sentence, deliver `content` directly — a `preview` 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.';
529
+ export const GUIDE_SURFACES = 'Every doc appears in its directory’s listing by default (suppress with --unlisted); everything beyond the listing is explicit `surfaces` routing — entries declaring WHEN the doc delivers and how much. Events: `boot` delivers in the boot catalog every agent sees; `workspace-open` delivers in first-message context when cwd/profile mounts the doc’s project store (project stores only); `read` fires when the agent reads a matching file (globs vs the file’s absolute path and basename, `./`-anchored globs vs its path relative to the store’s owning repo dir, `match-frontmatter` predicates over the read file’s own YAML frontmatter); `memory-read` fires when another memory doc is read (globs vs that doc’s canonical name, `./` anchored to this doc’s own name directory); `command` fires when a matching shell command runs (globs vs the whole command string, `*` crossing `/`). An entry may also carry `gate`, a node-config predicate using the same vocabulary as the document-level `gate`: event constraints and entry gate both must match, then all participating entries fold to the highest `at` (`content` > `preview` > `name`), with no cross-entry deny precedence. The document-level `gate` remains the hard eligibility check: when it fails, no automatic surface can deliver the document. `at` sets how much delivers: `name` the bare tag, `preview` the routing line, `content` the whole body. Explicit `memory read` and listings remain deliberate access and ignore gates/rungs; only companion docs routed by their `memory-read` entries use entry gates. Each entry is paid by every future agent it fires on, so default down: no surfaces at all is correct for reference depth reached through listings and [[links]], and when a doc fits in a single sentence, deliver `content` directly — a `preview` 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.';
525
530
  export const GUIDE_ROUTING_LINE = 'The routing line (--when-and-why-to-read) is the only text an agent reads before deciding to load the doc. The test for its when-clause: it names an observable circumstance in the reader\u2019s current work, not the doc\u2019s topic reworded as an activity. If the WHEN can be inferred from the title alone, it is not a real trigger. Bad on a todo list: "When planning or prioritizing work across this profile." Good: "When the user mentions something from their todos, or asks what is still outstanding across this profile." The test for its because-clause: if it can be derived by paraphrasing the doc\u2019s advice, it is a restatement, not a payoff \u2014 a real payoff names a consequence in the reader\u2019s 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" \u2014 the doc\u2019s 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 \u2014 ask the user one sharp question instead of improvising.';
526
- export const GUIDE_PREDICATE_VOCABULARY = 'Gate and match-frontmatter 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.';
531
+ export const GUIDE_PREDICATE_VOCABULARY = 'Document gates, surface-entry gates, and match-frontmatter 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.';
527
532
  export const GUIDE_DOC_LINKS = '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 \u2014 the same identifier `crtr memory read` takes. A bare directory name is a valid link too: following it returns that directory\u2019s listing, a browse entrance rather than a doc. 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 or directory, and `crtr memory read` lists a doc\u2019s resolvable links alongside its body. There is no alias or label form.';
@@ -32,6 +32,8 @@ export function renderDocView(doc, width) {
32
32
  parts.push(entry.match.join(", "));
33
33
  if (entry.matchFrontmatter !== undefined)
34
34
  parts.push(JSON.stringify(entry.matchFrontmatter));
35
+ if (entry.gate !== undefined)
36
+ parts.push(JSON.stringify(entry.gate));
35
37
  out.push(...field(entry.on, parts.join(" "), viewWidth));
36
38
  }
37
39
  if (doc.unlisted)
@@ -181,7 +181,7 @@ const configSet = defineLeaf({
181
181
  name: 'sys config set',
182
182
  summary: 'write a config value by dotted key',
183
183
  params: [
184
- { kind: 'positional', name: 'key', type: 'string', required: true, constraint: `Dotted key path. User-scope scalar settings: ${SCALAR_SETTING_HELP}. Also supported: working_gerunds and whip_messages (non-empty JSON string arrays), brokerThresholds.warning and brokerThresholds.automaticReviveCap (user scope; integer >= 1), modelLadders.defaultProvider, and modelLadders.<anthropic|openai>.<ultra|strong|medium|light>. Keybindings are edited only through sys settings.` },
184
+ { kind: 'positional', name: 'key', type: 'string', required: true, constraint: `Dotted key path. User-scope scalar settings: ${SCALAR_SETTING_HELP}. Also supported: working_gerunds and whip_messages (non-empty JSON string arrays), brokerThresholds.warning and brokerThresholds.automaticReviveCap (user scope; integer >= 1), modelLadders.defaultProvider, and modelLadders.<anthropic|openai>.<ultra|strong|medium|light>. Keybindings are edited only through sys settings. humanActions is an object map edited directly in ~/.crouter/config.json or <repo>/.crouter/config.json.` },
185
185
  { kind: 'flag', name: 'value', type: 'string', required: true, constraint: 'value VALUE — string, required. working_gerunds and whip_messages accept JSON arrays; other values are stored as-is if quoted and coerced to number or boolean when unambiguous.' },
186
186
  { kind: 'flag', name: 'scope', type: 'enum', choices: ['user', 'project'], required: false, constraint: 'Scope to write to. Default: user. Project scope is supported only for modelLadders.' },
187
187
  ],
@@ -261,7 +261,7 @@ export const configBranch = defineBranch({
261
261
  whenToUse: 'inspecting crtr settings, changing supported scalar values, or locating config.json. Keybinding changes belong in sys settings.',
262
262
  help: {
263
263
  name: 'sys config',
264
- summary: 'read and write crtr configuration, including model ladders',
264
+ summary: 'read and write crtr configuration, including model ladders; edit humanActions maps directly in ~/.crouter/config.json or <repo>/.crouter/config.json',
265
265
  },
266
266
  children: [configGet, configSet, configPath],
267
267
  });