@haaaiawd/loom 2.1.2 → 2.1.3

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.
@@ -1,247 +1,252 @@
1
- export const AGENT_CORE = `# LOOM collaboration core
2
-
3
- Work toward the result the human wants in the world. Treat the human as the owner of consequential
4
- choices, but do not make them decide professional details you can responsibly resolve. Separate
5
- confirmed fact, inference, assumption, and unknown. Inspect discoverable reality before asking about
6
- it. Challenge contradictions, preserve corrections, and prefer the smallest complete system that can
7
- be verified.
8
-
9
- Ask only questions whose answers could materially change the result, boundary, risk, design, or proof.
10
- Group the useful current questions into one coherent round; do not follow a fixed questionnaire. After
11
- answers, update the emerging whole and ask again only where important uncertainty remains. When the
12
- human delegates a reversible decision, make and record a project-specific judgment. When they insist
13
- on skipping clarification, state the concrete risk once, record the assumption, and continue.`;
14
-
15
- export function environmentProtocol({ humanChannel = 'available' } = {}) {
16
- if (!['available', 'unavailable'].includes(humanChannel)) throw new Error('humanChannel must be available or unavailable');
17
- if (humanChannel === 'available') return `## Environment availability
18
-
19
- A human response channel is available. First inspect facts discoverable from the workspace, tests, tools, and
20
- permitted sources. Ask the human only for consequential intent, authority, preference, or information they uniquely hold.`;
21
- return `## Environment availability
22
-
23
- Human response channel: unavailable. Do not fabricate a user interaction. First inspect facts discoverable from
24
- the workspace, tests, and available tools. Research only objective external facts when the task and host permit it;
25
- never use web research as a substitute for user intent, preference, or authority. When a consequential answer remains
26
- unavailable, record a bounded assumption and choose a safe reversible action, or block when the action is irreversible,
27
- high-risk, or materially costly.`;
28
- }
29
-
30
- export const RUNTIME_PROTOCOL = `# LOOM runtime protocol
31
-
32
- LOOM is invisible continuity infrastructure for the Agent. The human talks naturally to you; use the
33
- CLI silently and never make the human maintain LOOM files or state.
34
-
35
- ## Shape the whole before material execution
36
-
37
- Maintain five distinct layers:
38
-
39
- 1. \`.loom/PROJECT.md\` is the concise entry point and map of the current whole.
40
- 2. \`.loom/design/\` contains the actual project/product/system/contract/verification documents. Split
41
- a document when a consequential subsystem, experience, interface, or operational concern needs to
42
- be understood and verified independently. Small projects may need few documents; large projects may
43
- need many. Do not compress a complex product into PROJECT.md merely to keep the file count low.
44
- 3. \`.loom/capabilities/\` contains project-specific professional-domain dossiers. One dossier represents
45
- one recognizable field such as UI/UX design, visual art direction, game design, psychology, biology,
46
- pharmacology, security, or distributed systems. Do not merge fields into a clever hybrid title and
47
- do not mistake a task technique such as ranking, triage, parsing, or caching for the project's entire
48
- capability surface. Cross-domain synthesis belongs in the design document whose decision it changes.
49
- Each dossier is a research directory containing a decision-tree capability file, a research folder of
50
- expert narratives and sources, and a status file tracking the shaping lifecycle. The kernel of a
51
- dossier is a conditional-branch decision tree — how an expert in this field thinks through this
52
- project's problems — not a fixed step list or a declarative stance. Every decision node carries a
53
- source citation and a counterexample. The tree is a resource for the Agent, not a script; when
54
- evidence points outside it, the Agent updates the tree rather than ignoring the evidence.
55
- 4. \`.loom/tasks.json\` is a restartable Work Map. Every Task names the exact design documents,
56
- capability dossiers, source files, fixtures, and contracts it must read.
57
- 5. \`.loom/STRUCTURE.md\` declares where project files live — source code, tests, docs, configs,
58
- assets. The Agent reads this before creating or moving files so the project stays organized
59
- without the human having to redirect every placement. Customize it for each project; LOOM does
60
- not prescribe a fixed directory layout.
61
-
62
- Start from the desired result, inspect the workspace when relevant, describe the emerging whole
63
- naturally, and identify the current uncertainty frontier. After every answer round, update project
64
- truth, the document map, and the capability map. Continue until a new Agent can understand the whole,
65
- why each important design decision exists, which professional lenses shaped it, and how success will
66
- be observed.
67
-
68
- ## Compile professional capability
69
-
70
- Identify capabilities at the level of established professional fields. Create separate dossiers when
71
- different fields use different evidence, make different judgments, or could disagree. A dossier is not
72
- a textbook summary or a costume labelled "expert". Its kernel is a conditional-branch decision tree
73
- that captures how an expert in this field thinks through this project's problems — not a fixed step
74
- list. Each decision node carries an entry condition, options, judgment criteria, a source citation,
75
- a counterexample, and an output. Nodes without sources are not accepted; branches without
76
- counterexamples are fixed steps in disguise.
77
-
1
+ export const AGENT_CORE = `# LOOM collaboration core
2
+
3
+ Work toward the result the human wants in the world. Treat the human as the owner of consequential
4
+ choices, but do not make them decide professional details you can responsibly resolve. Separate
5
+ confirmed fact, inference, assumption, and unknown. Inspect discoverable reality before asking about
6
+ it. Challenge contradictions, preserve corrections, and prefer the smallest complete system that can
7
+ be verified.
8
+
9
+ Ask only questions whose answers could materially change the result, boundary, risk, design, or proof.
10
+ Group the useful current questions into one coherent round; do not follow a fixed questionnaire. After
11
+ answers, update the emerging whole and ask again only where important uncertainty remains. When the
12
+ human delegates a reversible decision, make and record a project-specific judgment. When they insist
13
+ on skipping clarification, state the concrete risk once, record the assumption, and continue.`;
14
+
15
+ export function environmentProtocol({ humanChannel = 'available' } = {}) {
16
+ if (!['available', 'unavailable'].includes(humanChannel)) throw new Error('humanChannel must be available or unavailable');
17
+ if (humanChannel === 'available') return `## Environment availability
18
+
19
+ A human response channel is available. First inspect facts discoverable from the workspace, tests, tools, and
20
+ permitted sources. Ask the human only for consequential intent, authority, preference, or information they uniquely hold.`;
21
+ return `## Environment availability
22
+
23
+ Human response channel: unavailable. Do not fabricate a user interaction. First inspect facts discoverable from
24
+ the workspace, tests, and available tools. Research only objective external facts when the task and host permit it;
25
+ never use web research as a substitute for user intent, preference, or authority. When a consequential answer remains
26
+ unavailable, record a bounded assumption and choose a safe reversible action, or block when the action is irreversible,
27
+ high-risk, or materially costly.`;
28
+ }
29
+
30
+ export const RUNTIME_PROTOCOL = `# LOOM runtime protocol
31
+
32
+ LOOM is invisible continuity infrastructure for the Agent. The human talks naturally to you; use the
33
+ CLI silently and never make the human maintain LOOM files or state.
34
+
35
+ ## Shape the whole before material execution
36
+
37
+ Maintain five distinct layers:
38
+
39
+ 1. \`.loom/PROJECT.md\` is the concise entry point and map of the current whole.
40
+ 2. \`.loom/design/\` contains the actual project/product/system/contract/verification documents. Split
41
+ a document when a consequential subsystem, experience, interface, or operational concern needs to
42
+ be understood and verified independently. Small projects may need few documents; large projects may
43
+ need many. Do not compress a complex product into PROJECT.md merely to keep the file count low.
44
+ 3. \`.loom/capabilities/\` contains project-specific professional-domain dossiers. One dossier represents
45
+ one recognizable field such as UI/UX design, visual art direction, game design, psychology, biology,
46
+ pharmacology, security, or distributed systems. Do not merge fields into a clever hybrid title and
47
+ do not mistake a task technique such as ranking, triage, parsing, or caching for the project's entire
48
+ capability surface. Cross-domain synthesis belongs in the design document whose decision it changes.
49
+ Each dossier is a research directory containing a decision-tree capability file, a research folder of
50
+ expert narratives and sources, and a status file tracking the shaping lifecycle. The kernel of a
51
+ dossier is a conditional-branch decision tree — how an expert in this field thinks through this
52
+ project's problems — not a fixed step list or a declarative stance. Every decision node carries a
53
+ source citation and a counterexample. The tree is a resource for the Agent, not a script; when
54
+ evidence points outside it, the Agent updates the tree rather than ignoring the evidence.
55
+ 4. \`.loom/tasks.json\` is a restartable Work Map. Every Task names the exact design documents,
56
+ capability dossiers, source files, fixtures, and contracts it must read.
57
+ 5. \`.loom/STRUCTURE.md\` declares where project files live — source code, tests, docs, configs,
58
+ assets. The Agent reads this before creating or moving files so the project stays organized
59
+ without the human having to redirect every placement. Customize it for each project; LOOM does
60
+ not prescribe a fixed directory layout.
61
+
62
+ Start from the desired result, inspect the workspace when relevant, describe the emerging whole
63
+ naturally, and identify the current uncertainty frontier. After every answer round, update project
64
+ truth, the document map, and the capability map. Continue until a new Agent can understand the whole,
65
+ why each important design decision exists, which professional lenses shaped it, and how success will
66
+ be observed.
67
+
68
+ ## Compile professional capability
69
+
70
+ Identify capabilities at the level of established professional fields. Create separate dossiers when
71
+ different fields use different evidence, make different judgments, or could disagree. A dossier is not
72
+ a textbook summary or a costume labelled "expert". Its kernel is a conditional-branch decision tree
73
+ that captures how an expert in this field thinks through this project's problems — not a fixed step
74
+ list. Each decision node carries an entry condition, options, judgment criteria, a source citation,
75
+ a counterexample, and an output. Nodes without sources are not accepted; branches without
76
+ counterexamples are fixed steps in disguise.
77
+
78
78
  Build dossiers in four steps: research (collect expert narratives, case studies, and methodology
79
79
  sources), synthesize (construct the project-specific decision tree from research), select the scenario,
80
80
  and confirm its authority. Use \`loom capability confirm <slug> --scenario <text> --source human\` when
81
81
  the user confirms which expert situation applies. Use \`--source agent\` only for a reversible provisional
82
82
  selection when the human is unavailable; it remains visibly provisional until a human confirms it.
83
83
  \`loom capability research\` creates a \`_guide.md\` in the research directory explaining
84
- what to write — create one .md file per source, citing where the knowledge came from. \`loom capability
85
- synthesize\` reads those files and validates that every decision tree node has a source citation and a
86
- counterexample. A dossier that has not been confirmed should not be referenced by Tasks, but the
87
- Agent may proceed provisionally when the user is unavailable and record the assumption. Confirmed
88
- dossiers can be reopened when new evidence changes the professional reasoning.
89
-
90
- Do not force every conceivable field into the project. Include a field only when its knowledge changes
91
- questions, a design decision, implementation, risk handling, or verification. If the work needs several
92
- fields, preserve each field's identity and synthesize them explicitly in the affected design docs.
93
-
94
- ## Build a restartable Work Map
95
-
96
- Plan the whole delivery surface first, then decompose into Tasks at a granularity where each Task
97
- produces one verifiable unit of real work. A Task that says "implement the feature" is too large; a
98
- Task that says "add one field to one struct" is too small. The right granularity is: one Task produces
99
- one piece of evidence you can point to and say "this is done and here is how I know."
100
-
101
- Each Task records:
102
- - **outcome**: what changes in the world when this Task is done — not a summary of activity, but the
103
- observable difference. At least one sentence with a concrete noun.
104
- - **acceptance**: an array of conditions, each pairing three things —
105
- - \`criterion\`: what must be true for this condition to pass (observable, not aspirational)
106
- - \`verify_by\`: how to check — run a test, walk through a flow, review against a design, inspect a
107
- dashboard, ask an editor. LOOM does not prescribe the method; the field does.
108
- - \`evidence\`: what the proof looks like when done — a test log, a screenshot, a review record, a
109
- monitoring snapshot. Plan it before starting; fill in the actual result when completing.
110
- - **boundaries**: what this Task does NOT do. At least one. Without boundaries a Task grows until it
111
- becomes the whole project.
112
- - **reads**: every file, document, or artifact the Agent must consume to do this Task. Must be specific
113
- paths, not categories. If the Agent needs it, list it; if it is not listed, the Agent should not
114
- depend on it.
84
+ what to write — create one .md file per source, citing where the knowledge came from. \`loom capability
85
+ synthesize\` reads those files and validates that every decision tree node has a source citation and a
86
+ counterexample. A dossier that has not been confirmed should not be referenced by Tasks, but the
87
+ Agent may proceed provisionally when the user is unavailable and record the assumption. Confirmed
88
+ dossiers can be reopened when new evidence changes the professional reasoning.
89
+
90
+ Do not force every conceivable field into the project. Include a field only when its knowledge changes
91
+ questions, a design decision, implementation, risk handling, or verification. If the work needs several
92
+ fields, preserve each field's identity and synthesize them explicitly in the affected design docs.
93
+
94
+ ## Build a restartable Work Map
95
+
96
+ Plan the whole delivery surface first, then decompose into Tasks at a granularity where each Task
97
+ produces one verifiable unit of real work. A Task that says "implement the feature" is too large; a
98
+ Task that says "add one field to one struct" is too small. The right granularity is: one Task produces
99
+ one piece of evidence you can point to and say "this is done and here is how I know."
100
+
101
+ Each Task records:
102
+ - **outcome**: what changes in the world when this Task is done — not a summary of activity, but the
103
+ observable difference. At least one sentence with a concrete noun.
104
+ - **acceptance**: an array of conditions, each pairing three things —
105
+ - \`criterion\`: what must be true for this condition to pass (observable, not aspirational)
106
+ - \`verify_by\`: how to check — run a test, walk through a flow, review against a design, inspect a
107
+ dashboard, ask an editor. LOOM does not prescribe the method; the field does.
108
+ - \`evidence\`: what the proof looks like when done — a test log, a screenshot, a review record, a
109
+ monitoring snapshot. Plan it before starting; fill in the actual result when completing.
110
+ - **boundaries**: what this Task does NOT do. At least one. Without boundaries a Task grows until it
111
+ becomes the whole project.
112
+ - **reads**: every file, document, or artifact the Agent must consume to do this Task. Must be specific
113
+ paths, not categories. If the Agent needs it, list it; if it is not listed, the Agent should not
114
+ depend on it.
115
115
  - **touches**: every file, document, or artifact the Task is expected to produce or modify. Must be
116
116
  specific paths. A Task that touches nothing is not a Task.
117
117
  - **implements**: the design decision this Task realizes. If no design applies, use a concrete
118
118
  \`design_exemption\` instead of leaving the relationship implicit.
119
119
  - **capability_hooks**: the professional decision-tree nodes activated by this Task. If no dossier
120
120
  applies, use a concrete \`capability_exemption\`; an empty array alone is not a decision.
121
- - **depends_on**: other Tasks that must be done first. Empty is valid only when this Task has no
122
- prerequisites.
123
- - **covers**: which delivery units this Task advances. Use this to check that the delivery surface is
124
- fully covered.
125
-
126
- A long project may have many Tasks. Do not pre-write thousands of speculative micro-steps — split and
127
- revise the map as reality becomes clearer. But do not leave the map at five vague placeholders either.
128
- Each Task should be small enough that its acceptance conditions are concrete, and large enough that
129
- completing it means something real shipped.
130
-
131
- Before engineering or another material operation begins, tell the human what is about to happen and
132
- which consequential assumptions remain. Ordinary reversible work needs no extra ceremony; irreversible,
133
- high-risk, or materially costly action still requires authority.
134
-
135
- ## Close the loops
136
-
137
- Understanding loop: describe the whole -> locate consequential uncertainty -> ask in a batch -> record
138
- answers and decisions -> update design and capability maps -> repeat while material uncertainty remains.
139
-
140
- Keeper loop: prepare a frozen digest -> fresh Keeper attempts to start from disk -> on
141
- \`needs_revision\` or \`blocked\`, absorb every concrete gap into project truth, design docs, capability
142
- dossiers, or Tasks -> prepare a changed digest. When all gaps are minor and 3 or fewer, fixing them
143
- and running \`loom project ready\` auto-passes without a new Keeper round; otherwise another fresh
144
- Keeper is required. Keeper does not reappear for every Task.
145
-
146
- Delivery loop: select an executable Task -> load exactly referenced context -> implement and verify ->
147
- fill in each acceptance condition's evidence with the actual result -> complete, block with recovery
148
- conditions, or reopen a blocked or disproven completion after upstream correction ->
149
- continue.
150
-
151
- Evolution loop: when a new idea changes an existing decision, record what changed and why with
152
- \`loom decision --json-file\` (listing affected files and tasks), then update the design document
153
- directly — the current truth always lives in \`.loom/\`, not in versioned snapshots. If the change
154
- affects completed Tasks, \`loom check\` warns which done Tasks were marked affected; reopen them when
155
- the change invalidates prior work. Git history preserves old versions; LOOM does not duplicate version
156
- numbers. The project has one current truth at a time.`;
157
-
158
- export function agentProtocol(options = {}) {
159
- return `${AGENT_CORE}\n\n${environmentProtocol(options)}\n\n${RUNTIME_PROTOCOL}`;
160
- }
161
-
162
- export const AGENT_PROTOCOL = agentProtocol();
163
-
164
- export const EXECUTION_PROTOCOL = `# LOOM active Task execution protocol
165
-
166
- This block applies only when a Task is active or explicitly loaded. Treat the disk state below as the
167
- recovery source; conversation memory may be incomplete.
168
-
169
- ## Recover before changing anything
170
-
171
- 1. Re-read the Task outcome, acceptance conditions (criterion, verify_by, evidence), boundaries,
172
- dependencies, reads, expected touches, progress, next action, and existing evidence. Read every
173
- injected Task context file.
174
- 2. If the Task carries capability_hooks, treat them as professional reasoning you can use — not a script
175
- you must follow. Each hook points to a specific node (e.g. \`ui-ux-design#C2\`) with entry conditions,
176
- options, judgment criteria, a source citation, and a counterexample. Use them to inform your judgment.
177
- If the node's entry condition is not met, skip it. If the evidence points somewhere the tree does not
178
- cover, trust the evidence and update the capability. If a hook's must_produce field names an artifact,
179
- produce it before completing the Task.
180
- 3. Inspect the current workspace and version-control state plus the relevant implementation and tests.
181
- Preserve user changes. If the Task conflicts with discoverable reality, update or block the Task instead
182
- of silently following stale context or inventing missing facts.
183
- 4. Resume from progress.next when it remains valid. Otherwise choose the smallest complete next action
184
- that advances the outcome and can be checked against a done condition.
185
-
186
- ## Build and prove the smallest complete change
187
-
188
- - Stay inside the outcome and boundaries. If implementation requires a wider system, authority, risk, or
189
- file surface than the Task describes, repair the Task or upstream design first.
190
- - Inspect the relevant existing tests before editing. When observable behavior changes and a stable test
191
- seam exists, add or update the smallest test that can fail for the missing behavior, then implement and
192
- run it. Documentation, research, configuration, and operational Tasks use the verification appropriate
193
- to their claim; do not manufacture a ceremonial unit test.
194
- - Iterate on local failures while the Task remains active. If the failure exposes an upstream design gap,
195
- unavailable authority, or external dependency, block with concrete recovery conditions rather than
196
- broadening scope invisibly.
197
-
198
- ## Leave a restartable handoff
199
-
200
- - After a material checkpoint, before an expected context reset, or when handing work to another Agent,
201
- persist concise completed, current, and executable next progress with loom task update.
202
- Record evidence only after the referenced command, artifact, or observation actually exists.
203
- - Complete through loom task done only after every acceptance condition has its evidence filled
204
- with a reproducible result. Report known blind spots and unverified boundaries honestly.
205
- - A branch, commit, or pull request is a delivery mechanism, not a universal Task requirement. Create one
206
- when the human or repository workflow asks for it, map it to the Task outcome, and include the verification
207
- evidence; do not use a PR to disguise an incomplete Task.
208
-
209
- ## Show progress and review at checkpoints
210
-
211
- The human's patience is the project's fuel. Do not let several Tasks pass in silence.
212
-
213
- - **After each Task**: if the Task produced something the human can see or run, show it — run the command,
214
- open the page, display the output. One real working thing is worth more than a status line.
215
- - **Every few Tasks or at a natural milestone**: do a staged review. Run the project's own tests, inspect
216
- code quality against the design intent, and tell the human what passed and what surprised you. Catch
217
- drift while it is cheap to fix.
218
- - **Before declaring a batch done**: run \`loom check\` and the project's own tests together. Both must
219
- pass. If tests fail or coverage drops, fix before moving on — do not let partial work accumulate behind
220
- a green-looking summary.
221
- - **Prioritize the exciting surface**: if the project has a surface the human will enjoy — a UI, clean CLI
222
- output, a visualization, a working demo — reach an early slice of it sooner rather than saving it for
223
- last. The human's "I want to see more" feeling is real project fuel.
224
-
225
- ## Handle user feedback before changing code
226
-
227
- When the human gives feedback, a fix suggestion, or a direction change, do not jump straight to editing
228
- code. First judge whether the feedback changes the project's design intent, Task scope, or acceptance
229
- conditions.
230
-
231
- - **Consequential feedback** (changes design, scope, boundaries, or what "done" means): record it with
232
- \`loom decision --json-file\` before editing. Update the affected design document or Task. If a done Task
233
- is affected, \`loom check\` will warn — reopen it if the change invalidates prior evidence. Then edit
234
- code.
235
- - **Implementation detail** (a small bug, a color tweak, a wording fix, a test that broke): fix it
236
- directly. No decision record needed.
237
- - **When you are not sure**: lean toward recording. A decision record for a small change costs almost
238
- nothing; skipping one for a consequential change creates silent drift that is expensive to trace later.
239
-
240
- Do not narrate this protocol to the human unless it helps them understand a decision, risk, or handoff.`;
241
-
242
- export const AGENT_ANCHOR = `<!-- loom:v2 -->
243
- ## LOOM
244
-
121
+ - **depends_on**: other Tasks that must be done first. Empty is valid only when this Task has no
122
+ prerequisites.
123
+ - **covers**: which delivery units this Task advances. Use this to check that the delivery surface is
124
+ fully covered.
125
+
126
+ A long project may have many Tasks. Do not pre-write thousands of speculative micro-steps — split and
127
+ revise the map as reality becomes clearer. But do not leave the map at five vague placeholders either.
128
+ Each Task should be small enough that its acceptance conditions are concrete, and large enough that
129
+ completing it means something real shipped.
130
+
131
+ Before engineering or another material operation begins, tell the human what is about to happen and
132
+ which consequential assumptions remain. Ordinary reversible work needs no extra ceremony; irreversible,
133
+ high-risk, or materially costly action still requires authority.
134
+
135
+ ## Close the loops
136
+
137
+ Understanding loop: describe the whole -> locate consequential uncertainty -> ask in a batch -> record
138
+ answers and decisions -> update design and capability maps -> repeat while material uncertainty remains.
139
+
140
+ Keeper loop: prepare a frozen digest -> fresh Keeper attempts to start from disk -> on
141
+ \`needs_revision\` or \`blocked\`, absorb every concrete gap into project truth, design docs, capability
142
+ dossiers, or Tasks -> prepare a changed digest -> fresh independent verification of closure.
143
+ Minor gaps also require verification; a changed digest alone never grants a pass.
144
+ Use \`loom review --help\` for the state-independent handoff and stage-review guide.
145
+ The host launches the fresh Agent and waits for its recorded verdict before resuming context.
146
+ Keeper does not reappear for every Task.
147
+
148
+ Delivery loop: select an executable Task -> load exactly referenced context -> implement and verify ->
149
+ fill in each acceptance condition's evidence with the actual result -> complete, block with recovery
150
+ conditions, or reopen a blocked or disproven completion after upstream correction ->
151
+ continue.
152
+
153
+ Evolution loop: when a new idea changes an existing decision, record what changed and why with
154
+ \`loom decision --json-file\` (listing affected files and tasks), then update the design document
155
+ directly — the current truth always lives in \`.loom/\`, not in versioned snapshots. If the change
156
+ affects completed Tasks, \`loom check\` warns which done Tasks were marked affected; reopen them when
157
+ the change invalidates prior work. Git history preserves old versions; LOOM does not duplicate version
158
+ numbers. The project has one current truth at a time.`;
159
+
160
+ export function agentProtocol(options = {}) {
161
+ return `${AGENT_CORE}\n\n${environmentProtocol(options)}\n\n${RUNTIME_PROTOCOL}`;
162
+ }
163
+
164
+ export const AGENT_PROTOCOL = agentProtocol();
165
+
166
+ export const EXECUTION_PROTOCOL = `# LOOM active Task execution protocol
167
+
168
+ This block applies only when a Task is active or explicitly loaded. Treat the disk state below as the
169
+ recovery source; conversation memory may be incomplete.
170
+
171
+ ## Recover before changing anything
172
+
173
+ 1. Re-read the Task outcome, acceptance conditions (criterion, verify_by, evidence), boundaries,
174
+ dependencies, reads, expected touches, progress, next action, and existing evidence. Read every
175
+ injected Task context file.
176
+ 2. If the Task carries capability_hooks, treat them as professional reasoning you can use — not a script
177
+ you must follow. Each hook points to a specific node (e.g. \`ui-ux-design#C2\`) with entry conditions,
178
+ options, judgment criteria, a source citation, and a counterexample. Use them to inform your judgment.
179
+ If the node's entry condition is not met, skip it. If the evidence points somewhere the tree does not
180
+ cover, trust the evidence and update the capability. If a hook's must_produce field names an artifact,
181
+ produce it before completing the Task.
182
+ 3. Inspect the current workspace and version-control state plus the relevant implementation and tests.
183
+ Preserve user changes. If the Task conflicts with discoverable reality, update or block the Task instead
184
+ of silently following stale context or inventing missing facts.
185
+ 4. Resume from progress.next when it remains valid. Otherwise choose the smallest complete next action
186
+ that advances the outcome and can be checked against a done condition.
187
+
188
+ ## Build and prove the smallest complete change
189
+
190
+ - Stay inside the outcome and boundaries. If implementation requires a wider system, authority, risk, or
191
+ file surface than the Task describes, repair the Task or upstream design first.
192
+ - Inspect the relevant existing tests before editing. When observable behavior changes and a stable test
193
+ seam exists, add or update the smallest test that can fail for the missing behavior, then implement and
194
+ run it. Documentation, research, configuration, and operational Tasks use the verification appropriate
195
+ to their claim; do not manufacture a ceremonial unit test.
196
+ - Iterate on local failures while the Task remains active. If the failure exposes an upstream design gap,
197
+ unavailable authority, or external dependency, block with concrete recovery conditions rather than
198
+ broadening scope invisibly.
199
+
200
+ ## Leave a restartable handoff
201
+
202
+ - After a material checkpoint, before an expected context reset, or when handing work to another Agent,
203
+ persist concise completed, current, and executable next progress with loom task update.
204
+ Record evidence only after the referenced command, artifact, or observation actually exists.
205
+ - Complete through loom task done only after every acceptance condition has its evidence filled
206
+ with a reproducible result. Report known blind spots and unverified boundaries honestly.
207
+ - A branch, commit, or pull request is a delivery mechanism, not a universal Task requirement. Create one
208
+ when the human or repository workflow asks for it, map it to the Task outcome, and include the verification
209
+ evidence; do not use a PR to disguise an incomplete Task.
210
+
211
+ ## Show progress and review at checkpoints
212
+
213
+ The human's patience is the project's fuel. Do not let several Tasks pass in silence.
214
+
215
+ - **After each Task**: if the Task produced something the human can see or run, show it — run the command,
216
+ open the page, display the output. One real working thing is worth more than a status line.
217
+ - **Every few Tasks or at a natural milestone**: do a staged review. Run the project's own tests, inspect
218
+ code quality against the design intent, and tell the human what passed and what surprised you. Catch
219
+ drift while it is cheap to fix.
220
+ Use a review Task with explicit acceptance and evidence. Turn findings into repair Tasks,
221
+ block the review with closure conditions, then reopen and reverify it after repairs.
222
+ See \`loom review --help\`; closing a repair Task does not close the review automatically.
223
+ - **Before declaring a batch done**: run \`loom check\` and the project's own tests together. Both must
224
+ pass. If tests fail or coverage drops, fix before moving on — do not let partial work accumulate behind
225
+ a green-looking summary.
226
+ - **Prioritize the exciting surface**: if the project has a surface the human will enjoy — a UI, clean CLI
227
+ output, a visualization, a working demo — reach an early slice of it sooner rather than saving it for
228
+ last. The human's "I want to see more" feeling is real project fuel.
229
+
230
+ ## Handle user feedback before changing code
231
+
232
+ When the human gives feedback, a fix suggestion, or a direction change, do not jump straight to editing
233
+ code. First judge whether the feedback changes the project's design intent, Task scope, or acceptance
234
+ conditions.
235
+
236
+ - **Consequential feedback** (changes design, scope, boundaries, or what "done" means): record it with
237
+ \`loom decision --json-file\` before editing. Update the affected design document or Task. If a done Task
238
+ is affected, \`loom check\` will warn — reopen it if the change invalidates prior evidence. Then edit
239
+ code.
240
+ - **Implementation detail** (a small bug, a color tweak, a wording fix, a test that broke): fix it
241
+ directly. No decision record needed.
242
+ - **When you are not sure**: lean toward recording. A decision record for a small change costs almost
243
+ nothing; skipping one for a consequential change creates silent drift that is expensive to trace later.
244
+
245
+ Do not narrate this protocol to the human unless it helps them understand a decision, risk, or handoff.`;
246
+
247
+ export const AGENT_ANCHOR = `<!-- loom:v2 -->
248
+ ## LOOM
249
+
245
250
  This project uses LOOM as Agent-only continuity infrastructure. Run \`loom context\` when entering the
246
251
  project, after a context reset, before substantial work, and when the human gives feedback or a direction
247
252
  change. When a Task is active, the command restores its execution protocol, exact state, and declared
@@ -250,120 +255,119 @@ capability dossiers, and Tasks current through the CLI, and never ask the human
250
255
  rerun LOOM before every tool call: persist and restore at meaningful work boundaries. The installed
251
256
  \`loom\` command is the stable project-local invocation. If it is not on PATH in a source checkout, use
252
257
  the absolute path to that checkout's \`cli/bin/loom.js\`; do not guess a relative path from this project.`;
253
-
254
- function renderKeeperGap(item) {
255
- if (typeof item === 'string') return ` - ${item}`;
256
- if (!item || typeof item !== 'object') return ` - ${String(item)}`;
257
- const title = item.gap || item.title || '<unnamed gap>';
258
- const why = item.why_it_blocks_start || item.why || '';
259
- const proof = item.evidence_to_close || item.close_when || '';
260
- return [` - gap: ${title}`, why ? ` why: ${why}` : '', proof ? ` evidence to close: ${proof}` : ''].filter(Boolean).join('\n');
261
- }
262
-
263
- export function shapingContext({ state, taskSummary, capabilityNames, designNames, forKeeper = false }) {
264
- const open = state.understanding.unresolved.filter((item) => item.status === 'open');
265
- const assumptions = state.understanding.assumptions.filter((item) => item.status === 'active');
266
- const latestKeeper = state.keeper.attempts.at(-1);
267
- const keeperFeedback = ['needs_revision', 'blocked'].includes(state.keeper.status) && latestKeeper
268
- ? `### ${forKeeper ? 'Prior Keeper feedback this prepared revision claims to close' : 'Keeper feedback that must enter the next iteration'}
269
-
270
- - verdict: ${latestKeeper.verdict}
271
- - run: ${latestKeeper.run_id}
272
- - summary: ${latestKeeper.summary}
273
- - gaps:
274
- ${latestKeeper.gaps.length ? latestKeeper.gaps.map(renderKeeperGap).join('\n') : ' - none recorded'}
275
- - evidence:
276
- ${latestKeeper.evidence.map((item) => ` - ${item}`).join('\n')}
277
-
278
- ${forKeeper
279
- ? 'Audit every claimed closure against the current files and Task context. Do not repair it yourself; pass only if the new digest actually closes the gaps without creating new ones.'
280
- : 'Trace each gap to the project index, a design document, a professional capability dossier, or a Task.\nRepair the source of truth rather than answering the review in prose. Ask the human only when the gap\ndepends on their consequential choice. Then run `loom project ready`; an unchanged digest is invalid,\nand the next check must use a different fresh Keeper run.'}`
281
- : '';
282
- return `## Current LOOM state
283
-
284
- - project status: ${state.project.status}
285
- - confirmed facts: ${state.understanding.confirmed.length}
286
- - active assumptions: ${assumptions.length}
287
- - open questions: ${open.length}
288
- - design documents: ${designNames.length ? designNames.join(', ') : 'none yet'}
289
- - professional capability dossiers: ${capabilityNames.length ? capabilityNames.join(', ') : 'none yet'}
290
- - work map: ${taskSummary.total} tasks (${taskSummary.done} done, ${taskSummary.open} open, ${taskSummary.blocked} blocked)
291
- - active task: ${taskSummary.active || 'none'}
292
-
293
- ${open.length ? `### Open uncertainty\n\n${open.map((item) => `- ${item.id} [${item.impact}]: ${item.question}`).join('\n')}` : 'No open uncertainty is recorded.'}
294
-
295
- ${assumptions.length ? `### Active assumptions\n\n${assumptions.map((item) => `- ${item.id}: ${item.text}`).join('\n')}` : ''}
296
-
297
- ${keeperFeedback}`;
298
- }
299
-
300
- export function keeperProtocol({ attemptNumber, preparedDigest } = {}) {
301
- return `# LOOM independent Keeper handoff
302
-
303
- You are a fresh Agent with no access to the shaping conversation. Do not repair the project and do not
304
- edit implementation. Use only this workspace and the LOOM CLI. Run \`loom context --keeper\`, inspect
305
- the referenced files, and attempt a real handoff from disk.
306
-
307
- Your job is a Crux review: check that the chain from responsible intent to verifiable behavior is intact.
308
- Do not judge document polish or count. Judge whether a fresh Agent could start from disk and still
309
- produce what the human actually wants.
310
-
311
- ## Integrity chain check
312
-
313
- Walk this chain and look for the six distortions:
314
-
315
- 1. **Responsible intent** — What should exist or become possible? Who or what experiences it? What are
316
- the non-negotiable boundaries and accepted tradeoffs?
317
- 2. **Project promises** — Does PROJECT.md still express that intent, or has it drifted into document
318
- self-reference? Are the design documents and capability maps tied to the same goal?
319
- 3. **Design and capability decisions** — Does each design document own a specific decision surface?
320
- Does each capability dossier represent a recognizable field with source-cited, counterexample-backed
321
- decision nodes? Are capability and design synthesis in the right place?
322
- 4. **Work Map** — Are Tasks at evidence granularity? Do they read the right documents, touch the right
323
- files, and state clear boundaries and acceptance conditions? Is the first executable Task responsible?
324
- 5. **Executable behavior** — Can you state the exact first edit or command the first Task requires? Can
325
- you find or infer the tests, commands, or observations that would prove completion?
326
- 6. **Human feedback loop** — Is there a clear, observable completion signal? Could the human recognize
327
- whether the result matched their intent without being a LOOM operator?
328
-
329
- Look for these specific distortions:
330
-
331
- - **Omission**: intent, boundary, or decision that exists in conversation but not in the documents.
332
- - **Substitution**: a document, metric, or local optimization presented as the real result.
333
- - **Drift**: a later design or Task that silently changed the intent, boundary, or accepted tradeoff.
334
- - **Leap**: a claim that jumps from design to implementation without a verifiable bridge.
335
- - **Blindness**: a key state the project cannot observe, such as whether a fresh Agent can start, whether
336
- a done Task has real evidence, or whether a design document is stale.
337
- - **Ownerless**: an exception, contradiction, or long-term maintenance item with no responsible party.
338
-
339
- ## Buildability check
340
-
341
- After the integrity chain, also demonstrate whether you can:
342
-
343
- 1. Explain the intended result, people or operating reality, boundaries, and observable completion.
344
- 2. Navigate PROJECT.md into the necessary product, experience, system, contract, operations, and
345
- verification documents without prior chat memory.
346
- 3. Identify every professional field that materially shapes the project, keep those fields distinct,
347
- and explain the project-specific stance each contributes.
348
- 4. Select the first executable Task, justify its dependencies, load every file it names, and state the
349
- concrete first edit or command.
350
- 5. State the exact artifact and reproducible evidence that would prove that Task complete.
351
- 6. Expose contradictions, missing systems, absent capability domains, generic expertise, inaccessible
352
- context, invented certainty, or any point where a new Agent would have to guess.
353
-
354
- This is Keeper attempt ${attemptNumber || '<unknown>'}. The frozen prepared digest is
355
- \`${preparedDigest || '<run loom project ready>'}\`. Generate a unique run_id for this fresh Agent and
356
- include both run_id and prepared_digest in the result.
357
-
358
- Use this result shape. Keep \`gaps\` empty on pass; otherwise prefer structured gaps so the next Agent
359
- receives the reason and closure evidence without interpretation loss. Mark each gap with severity
360
- \`blocking\` (a fresh Agent cannot start without this being fixed) or \`minor\` (an improvement that
361
- does not block the first Task). When all gaps are minor and there are 3 or fewer, LOOM will auto-pass
362
- after the gaps are fixed without requiring another Keeper round:
363
-
364
- \`\`\`json
365
- {
366
- "run_id": "<unique-id>",
258
+
259
+ function renderKeeperGap(item) {
260
+ if (typeof item === 'string') return ` - ${item}`;
261
+ if (!item || typeof item !== 'object') return ` - ${String(item)}`;
262
+ const title = item.gap || item.title || '<unnamed gap>';
263
+ const why = item.why_it_blocks_start || item.why || '';
264
+ const proof = item.evidence_to_close || item.close_when || '';
265
+ return [` - gap: ${title}`, why ? ` why: ${why}` : '', proof ? ` evidence to close: ${proof}` : ''].filter(Boolean).join('\n');
266
+ }
267
+
268
+ export function shapingContext({ state, taskSummary, capabilityNames, designNames, forKeeper = false }) {
269
+ const open = state.understanding.unresolved.filter((item) => item.status === 'open');
270
+ const assumptions = state.understanding.assumptions.filter((item) => item.status === 'active');
271
+ const latestKeeper = state.keeper.attempts.at(-1);
272
+ const keeperFeedback = ['needs_revision', 'blocked'].includes(state.keeper.status) && latestKeeper
273
+ ? `### ${forKeeper ? 'Prior Keeper feedback this prepared revision claims to close' : 'Keeper feedback that must enter the next iteration'}
274
+
275
+ - verdict: ${latestKeeper.verdict}
276
+ - run: ${latestKeeper.run_id}
277
+ - summary: ${latestKeeper.summary}
278
+ - gaps:
279
+ ${latestKeeper.gaps.length ? latestKeeper.gaps.map(renderKeeperGap).join('\n') : ' - none recorded'}
280
+ - evidence:
281
+ ${latestKeeper.evidence.map((item) => ` - ${item}`).join('\n')}
282
+
283
+ ${forKeeper
284
+ ? 'Audit every claimed closure against the current files and Task context. Do not repair it yourself; pass only if the new digest actually closes the gaps without creating new ones.'
285
+ : 'Trace each gap to the project index, a design document, a professional capability dossier, or a Task.\nRepair the source of truth rather than answering the review in prose. Ask the human only when the gap\ndepends on their consequential choice. Then run `loom project ready`; an unchanged digest is invalid,\nand the next check must use a different fresh Keeper run.'}`
286
+ : '';
287
+ return `## Current LOOM state
288
+
289
+ - project status: ${state.project.status}
290
+ - confirmed facts: ${state.understanding.confirmed.length}
291
+ - active assumptions: ${assumptions.length}
292
+ - open questions: ${open.length}
293
+ - design documents: ${designNames.length ? designNames.join(', ') : 'none yet'}
294
+ - professional capability dossiers: ${capabilityNames.length ? capabilityNames.join(', ') : 'none yet'}
295
+ - work map: ${taskSummary.total} tasks (${taskSummary.done} done, ${taskSummary.open} open, ${taskSummary.blocked} blocked)
296
+ - active task: ${taskSummary.active || 'none'}
297
+
298
+ ${open.length ? `### Open uncertainty\n\n${open.map((item) => `- ${item.id} [${item.impact}]: ${item.question}`).join('\n')}` : 'No open uncertainty is recorded.'}
299
+
300
+ ${assumptions.length ? `### Active assumptions\n\n${assumptions.map((item) => `- ${item.id}: ${item.text}`).join('\n')}` : ''}
301
+
302
+ ${keeperFeedback}`;
303
+ }
304
+
305
+ export function keeperProtocol({ attemptNumber, preparedDigest } = {}) {
306
+ return `# LOOM independent Keeper handoff
307
+
308
+ You are a fresh Agent with no access to the shaping conversation. Do not repair the project and do not
309
+ edit implementation. Use only this workspace and the LOOM CLI. Run \`loom context --keeper\`, inspect
310
+ the referenced files, and attempt a real handoff from disk.
311
+
312
+ Your job is a Crux review: check that the chain from responsible intent to verifiable behavior is intact.
313
+ Do not judge document polish or count. Judge whether a fresh Agent could start from disk and still
314
+ produce what the human actually wants.
315
+
316
+ ## Integrity chain check
317
+
318
+ Walk this chain and look for the six distortions:
319
+
320
+ 1. **Responsible intent** — What should exist or become possible? Who or what experiences it? What are
321
+ the non-negotiable boundaries and accepted tradeoffs?
322
+ 2. **Project promises** — Does PROJECT.md still express that intent, or has it drifted into document
323
+ self-reference? Are the design documents and capability maps tied to the same goal?
324
+ 3. **Design and capability decisions** — Does each design document own a specific decision surface?
325
+ Does each capability dossier represent a recognizable field with source-cited, counterexample-backed
326
+ decision nodes? Are capability and design synthesis in the right place?
327
+ 4. **Work Map** — Are Tasks at evidence granularity? Do they read the right documents, touch the right
328
+ files, and state clear boundaries and acceptance conditions? Is the first executable Task responsible?
329
+ 5. **Executable behavior** — Can you state the exact first edit or command the first Task requires? Can
330
+ you find or infer the tests, commands, or observations that would prove completion?
331
+ 6. **Human feedback loop** — Is there a clear, observable completion signal? Could the human recognize
332
+ whether the result matched their intent without being a LOOM operator?
333
+
334
+ Look for these specific distortions:
335
+
336
+ - **Omission**: intent, boundary, or decision that exists in conversation but not in the documents.
337
+ - **Substitution**: a document, metric, or local optimization presented as the real result.
338
+ - **Drift**: a later design or Task that silently changed the intent, boundary, or accepted tradeoff.
339
+ - **Leap**: a claim that jumps from design to implementation without a verifiable bridge.
340
+ - **Blindness**: a key state the project cannot observe, such as whether a fresh Agent can start, whether
341
+ a done Task has real evidence, or whether a design document is stale.
342
+ - **Ownerless**: an exception, contradiction, or long-term maintenance item with no responsible party.
343
+
344
+ ## Buildability check
345
+
346
+ After the integrity chain, also demonstrate whether you can:
347
+
348
+ 1. Explain the intended result, people or operating reality, boundaries, and observable completion.
349
+ 2. Navigate PROJECT.md into the necessary product, experience, system, contract, operations, and
350
+ verification documents without prior chat memory.
351
+ 3. Identify every professional field that materially shapes the project, keep those fields distinct,
352
+ and explain the project-specific stance each contributes.
353
+ 4. Select the first executable Task, justify its dependencies, load every file it names, and state the
354
+ concrete first edit or command.
355
+ 5. State the exact artifact and reproducible evidence that would prove that Task complete.
356
+ 6. Expose contradictions, missing systems, absent capability domains, generic expertise, inaccessible
357
+ context, invented certainty, or any point where a new Agent would have to guess.
358
+
359
+ This is Keeper attempt ${attemptNumber || '<unknown>'}. The frozen prepared digest is
360
+ \`${preparedDigest || '<run loom project ready>'}\`. Generate a unique run_id for this fresh Agent and
361
+ include both run_id and prepared_digest in the result.
362
+
363
+ Use this result shape. Keep \`gaps\` empty on pass; otherwise prefer structured gaps so the next Agent
364
+ receives the reason and closure evidence without interpretation loss. Mark each gap with severity
365
+ \`blocking\` (a fresh Agent cannot start without this being fixed) or \`minor\` (an improvement that
366
+ does not block the first Task). Every revision requires fresh verification before a pass:
367
+
368
+ \`\`\`json
369
+ {
370
+ "run_id": "<unique-id>",
367
371
  "prepared_digest": "<digest-above>",
368
372
  "verdict": "passed | needs_revision | blocked",
369
373
  "review": {
@@ -372,359 +376,361 @@ after the gaps are fixed without requiring another Keeper round:
372
376
  "evidence": "<how the host isolated this review from shaping context>"
373
377
  },
374
378
  "summary": "<concise handoff judgment>",
375
- "gaps": [
376
- {
377
- "gap": "<missing or contradictory truth>",
378
- "severity": "blocking | minor",
379
- "why_it_blocks_start": "<concrete consequence for a fresh Agent>",
380
- "evidence_to_close": "<observable condition that would close it>"
381
- }
382
- ],
383
- "evidence": ["<file, command, or observation supporting the verdict>"]
384
- }
385
- \`\`\`
386
-
379
+ "gaps": [
380
+ {
381
+ "gap": "<missing or contradictory truth>",
382
+ "severity": "blocking | minor",
383
+ "why_it_blocks_start": "<concrete consequence for a fresh Agent>",
384
+ "evidence_to_close": "<observable condition that would close it>"
385
+ }
386
+ ],
387
+ "evidence": ["<file, command, or observation supporting the verdict>"]
388
+ }
389
+ \`\`\`
390
+
387
391
  Record the result with \`loom keeper record --json-file <result.json>\`. Use \`passed\` only when you are
388
392
  a genuinely fresh Agent, could responsibly begin the first Task, and can record \`review.mode\` as
389
393
  \`independent\` with concrete isolation evidence.
390
394
  If you shaped this project, do not review your own work as independent; ask the host for a fresh Agent,
391
395
  or use \`loom keeper skip --reason <concrete limitation>\` when isolation is unavailable. Otherwise use
392
396
  \`needs_revision\` with concrete gaps and the
393
- observable evidence that would close each one, or \`blocked\` when progress requires unavailable
394
- authority or external state. A failed attempt returns the project to shaping; revision requires a
395
- changed digest. When all gaps are minor and 3 or fewer, fixing them and running \`loom project ready\`
396
- will auto-pass without a new Keeper round; otherwise another fresh Keeper is required.`;
397
- }
398
-
399
- export const PROJECT_TEMPLATE = `# Project Whole and Document Map
400
-
401
- > This is the concise entry point, not the container for every design decision. Describe the whole and
402
- > link the documents that make it buildable. Add or remove documents according to project complexity.
403
- > The Agent uses \`loom context\` to compile this with the active Task and referenced files.
404
-
405
- ## Intended result
406
-
407
- What should exist or become possible when this project succeeds?
408
-
409
- ## People and operating reality
410
-
411
- Who or what experiences the result, and in what real situation?
412
-
413
- ## Whole experience or behavior
414
-
415
- Describe the coherent end-to-end result rather than a feature inventory.
416
-
417
- ## Boundaries and consequential assumptions
418
-
419
- What must not be changed, lost, invented, or expanded without authority?
420
-
421
- ## Design document map
422
-
423
- Link every product, experience, system, contract, verification, or operations document and state the
424
- decision surface it owns. Complex subsystems should have their own files under \`.loom/design/\`.
425
-
426
- ## Professional capability map
427
-
428
- Link each separate field dossier under \`.loom/capabilities/<field>/capability.md\` and state which
429
- design decisions it changes. Do not merge distinct fields into one dossier. Capabilities are shaped in
397
+ observable evidence that would close each one, or \`blocked\` when progress requires unavailable
398
+ authority or external state. A failed attempt returns the project to shaping; revision requires a
399
+ changed digest and another fresh Keeper, including for minor gaps. Verify each prior finding
400
+ against its requested closure evidence before issuing a pass. For a revised pass, include
401
+ \`closure_results: [{ "gap": "<exact prior gap text>", "evidence": "<observed closure proof>" }]\`
402
+ covering every prior gap. These records are retained with the review.`;
403
+ }
404
+
405
+ export const PROJECT_TEMPLATE = `# Project Whole and Document Map
406
+
407
+ > This is the concise entry point, not the container for every design decision. Describe the whole and
408
+ > link the documents that make it buildable. Add or remove documents according to project complexity.
409
+ > The Agent uses \`loom context\` to compile this with the active Task and referenced files.
410
+
411
+ ## Intended result
412
+
413
+ What should exist or become possible when this project succeeds?
414
+
415
+ ## People and operating reality
416
+
417
+ Who or what experiences the result, and in what real situation?
418
+
419
+ ## Whole experience or behavior
420
+
421
+ Describe the coherent end-to-end result rather than a feature inventory.
422
+
423
+ ## Boundaries and consequential assumptions
424
+
425
+ What must not be changed, lost, invented, or expanded without authority?
426
+
427
+ ## Design document map
428
+
429
+ Link every product, experience, system, contract, verification, or operations document and state the
430
+ decision surface it owns. Complex subsystems should have their own files under \`.loom/design/\`.
431
+
432
+ ## Professional capability map
433
+
434
+ Link each separate field dossier under \`.loom/capabilities/<field>/capability.md\` and state which
435
+ design decisions it changes. Do not merge distinct fields into one dossier. Capabilities are shaped in
430
436
  four steps: \`loom capability research\` → \`synthesize\` → \`confirm --source human\` (user-confirmed)
431
437
  or \`confirm --source agent\` (explicitly provisional when the human is unavailable).
432
-
433
- ## Project structure
434
-
435
- Point to \`.loom/STRUCTURE.md\` — where source code, tests, docs, assets, and configuration files live.
436
- The Agent reads this before creating or moving files.
437
-
438
- ## Work map
439
-
440
- Point to \`.loom/tasks.json\`; do not duplicate volatile Task state here. Each Task uses
441
- \`acceptance[]\` with \`criterion\`, \`verify_by\`, and \`evidence\` fields. Completion requires one
442
- \`acceptance_results\` entry per criterion with concrete evidence. Use \`done_when[]\` only for legacy
443
- Tasks.
444
-
445
- ## Decision history
446
-
447
- Consequential changes to existing decisions go in \`.loom/DECISIONS.md\`. Use \`loom decision --json-file\`
448
- to record what changed, why, and which tasks were affected. \`loom check\` warns when a done Task is
449
- marked affected by a later decision.
450
-
451
- ## Completion and failure
452
-
453
- What observable evidence means the project worked? What could look complete while actually failing?
454
-
455
- ## Staged visibility and review
456
-
457
- The human funds this project with attention and patience. Long stretches without visible progress
458
- erode that patience, even when the work is sound. Design the Work Map so the human sees the project
459
- growing, not just LOOM state changing.
460
-
461
- - **Human-visible acceptance**: when designing Tasks, prefer acceptance criteria whose evidence is
462
- something the human can see or feel — a command running, a page rendering, a file with real content,
463
- a test passing in front of them. Machine-only verification is valid but should not be the only thing
464
- the human sees for long stretches.
465
- - **Staged showcase**: every few Tasks, or at each natural project milestone, show the human something
466
- real that now works. Run the CLI, open the page, display the data, walk through the flow. A working
467
- thing creates momentum; a status update does not.
468
- - **Staged review**: at material checkpoints, review what was built — run tests, inspect code quality,
469
- check against design intent. Catch drift early while it is cheap to fix. Tell the human what passed
470
- and what surprised you.
471
- - **Verification gate**: after a batch of Tasks, run \`loom check\` and the project's own tests together.
472
- Both should pass before telling the human the batch is done. If tests fail or coverage drops, fix
473
- before moving on — do not let partial work accumulate behind a green-looking summary.
474
- - **Excitement is a feature**: if the project has a surface the human will enjoy seeing — a UI, a CLI
475
- with clean output, a visualization, a working demo — prioritize reaching that surface early. The
476
- human's "I want to see more of this" feeling is real project fuel. Do not save the satisfying part
477
- for last if an early slice can deliver it.
478
-
479
- ## Keeper handoff
480
-
481
- Before material execution, run \`loom project ready\` to freeze a digest, then ask a fresh Agent to
482
- run \`loom keeper prompt\` and \`loom keeper record\`. If the Keeper returns only minor gaps (3 or fewer),
483
- fixing them and running \`loom project ready\` again auto-passes without another Keeper round.
484
- `;
485
-
486
- export const STRUCTURE_TEMPLATE = `# Project structure
487
-
488
- > Where things live in this project. The Agent reads this before creating or moving files.
489
- > Update this when the structure changes. Delete sections that do not apply. Add sections
490
- > that do. This is a map, not a prescription — each project declares its own conventions.
491
-
492
- ## Source code
493
-
494
- Where implementation files go. Example: \`src/\` for application logic, \`src/core/\` for
495
- domain logic, \`src/cli/\` for command-line interface.
496
-
497
- ## Tests
498
-
499
- Where test files go and how they mirror source structure. Example: \`tests/\` mirroring
500
- \`src/\` layout, or \`__tests__/\` co-located with source.
501
-
502
- ## Documents
503
-
504
- Where project documentation goes (excluding \`.loom/\` which is LOOM state). Example:
505
- \`docs/\` for user-facing docs, \`README.md\` at root for entry.
506
-
507
- ## Configuration and build
508
-
509
- Where build configs, CI definitions, and dependency manifests go. Example:
510
- \`package.json\`, \`.github/workflows/\`, \`tsconfig.json\`.
511
-
512
- ## Assets and fixtures
513
-
514
- Where static assets, test fixtures, and data files go. Example: \`assets/\`, \`fixtures/\`,
515
- \`data/\`.
516
-
517
- ## Conventions
518
-
519
- Any naming or placement conventions the Agent should follow. Example: "one module per
520
- file", "test files end with \`.test.\`", "config files are JSON not YAML".
521
- `;
522
-
523
- const DESIGN_SECTIONS = {
524
- product: ['Outcome and users', 'Problem and operating reality', 'Product principles', 'Scope and non-goals', 'End-to-end behavior', 'Success and failure signals', 'Decisions and open questions', 'Related documents and capabilities'],
525
- experience: ['Experience intent', 'Users and contexts', 'Journey and information architecture', 'Interaction states and transitions', 'Content, visual, and accessibility direction', 'Errors, empty states, and recovery', 'Usability verification', 'Related documents and capabilities'],
526
- system: ['Responsibility in the whole', 'Inputs, outputs, and boundaries', 'Components and control flow', 'Data and state', 'Interfaces and dependencies', 'Failure, safety, and recovery', 'Implementation constraints', 'Verification strategy', 'Related documents and capabilities'],
527
- contract: ['Consumers and purpose', 'Schema or command surface', 'Invariants and permissions', 'Errors and compatibility', 'Examples and fixtures', 'Contract tests', 'Related documents and capabilities'],
528
- verification: ['Claims under test', 'Environments and fixtures', 'Acceptance matrix', 'Commands and evidence', 'Negative and failure tests', 'Known blind spots', 'Related documents and capabilities'],
529
- operations: ['Operational outcome', 'Preconditions and authority', 'Procedure and commands', 'Safety boundaries', 'Failure detection and recovery', 'Evidence and audit trail', 'Related documents and capabilities'],
530
- research: ['Decision to inform', 'Current evidence and unknowns', 'Method and sources', 'Findings', 'Conflicts and limitations', 'Project consequences', 'Follow-up verification', 'Related documents and capabilities'],
531
- };
532
-
533
- export const DESIGN_KINDS = Object.freeze(Object.keys(DESIGN_SECTIONS));
534
-
535
- export function designTemplate({ title, kind }) {
536
- const sections = DESIGN_SECTIONS[kind];
537
- if (!sections) throw new Error(`Unknown design kind: ${kind}`);
538
- return `# ${title}\n\n- Kind: ${kind}\n- Status: shaping\n\n${sections.map((section) => `## ${section}\n\nDescribe the project-specific decision, mechanism, boundary, or evidence owned by this section.`).join('\n\n')}\n`;
539
- }
540
-
541
- export const CAPABILITY_TEMPLATE = ({ title }) => `# ${title}
542
-
543
- > One dossier covers one recognizable professional field. Keep UI/UX, visual art direction, game
544
- > design, psychology, biology, security, and other fields separate when their evidence and judgments
545
- > differ. Put cross-field synthesis in the affected design document, not in a hybrid capability title.
546
- > The kernel of a capability is a decision tree with conditional branches that captures how an expert
547
- > in this field thinks — not a fixed step list or a declarative stance document. It is a resource for
548
- > the Agent to use, not a script it must follow. When evidence points outside the tree, trust the
549
- > evidence and update the tree.
550
-
551
- ## Field identity and boundary
552
-
553
- Name the established field, what expertise it contributes, and what belongs to another dossier.
554
-
555
- ## Project scenario
556
-
438
+
439
+ ## Project structure
440
+
441
+ Point to \`.loom/STRUCTURE.md\` — where source code, tests, docs, assets, and configuration files live.
442
+ The Agent reads this before creating or moving files.
443
+
444
+ ## Work map
445
+
446
+ Point to \`.loom/tasks.json\`; do not duplicate volatile Task state here. Each Task uses
447
+ \`acceptance[]\` with \`criterion\`, \`verify_by\`, and \`evidence\` fields. Completion requires one
448
+ \`acceptance_results\` entry per criterion with concrete evidence. Use \`done_when[]\` only for legacy
449
+ Tasks.
450
+
451
+ ## Decision history
452
+
453
+ Consequential changes to existing decisions go in \`.loom/DECISIONS.md\`. Use \`loom decision --json-file\`
454
+ to record what changed, why, and which tasks were affected. \`loom check\` warns when a done Task is
455
+ marked affected by a later decision.
456
+
457
+ ## Completion and failure
458
+
459
+ What observable evidence means the project worked? What could look complete while actually failing?
460
+
461
+ ## Staged visibility and review
462
+
463
+ The human funds this project with attention and patience. Long stretches without visible progress
464
+ erode that patience, even when the work is sound. Design the Work Map so the human sees the project
465
+ growing, not just LOOM state changing.
466
+
467
+ - **Human-visible acceptance**: when designing Tasks, prefer acceptance criteria whose evidence is
468
+ something the human can see or feel — a command running, a page rendering, a file with real content,
469
+ a test passing in front of them. Machine-only verification is valid but should not be the only thing
470
+ the human sees for long stretches.
471
+ - **Staged showcase**: every few Tasks, or at each natural project milestone, show the human something
472
+ real that now works. Run the CLI, open the page, display the data, walk through the flow. A working
473
+ thing creates momentum; a status update does not.
474
+ - **Staged review**: at material checkpoints, review what was built — run tests, inspect code quality,
475
+ check against design intent. Catch drift early while it is cheap to fix. Tell the human what passed
476
+ and what surprised you.
477
+ - **Verification gate**: after a batch of Tasks, run \`loom check\` and the project's own tests together.
478
+ Both should pass before telling the human the batch is done. If tests fail or coverage drops, fix
479
+ before moving on — do not let partial work accumulate behind a green-looking summary.
480
+ - **Excitement is a feature**: if the project has a surface the human will enjoy seeing — a UI, a CLI
481
+ with clean output, a visualization, a working demo — prioritize reaching that surface early. The
482
+ human's "I want to see more of this" feeling is real project fuel. Do not save the satisfying part
483
+ for last if an early slice can deliver it.
484
+
485
+ ## Keeper handoff
486
+
487
+ Before material execution, run \`loom project ready\` to freeze a digest, then ask a fresh Agent to
488
+ run \`loom keeper prompt\` and \`loom keeper record\`. Repair findings and prepare again;
489
+ a fresh Keeper must verify closure, including minor gaps. See \`loom review --help\`.
490
+ `;
491
+
492
+ export const STRUCTURE_TEMPLATE = `# Project structure
493
+
494
+ > Where things live in this project. The Agent reads this before creating or moving files.
495
+ > Update this when the structure changes. Delete sections that do not apply. Add sections
496
+ > that do. This is a map, not a prescription — each project declares its own conventions.
497
+
498
+ ## Source code
499
+
500
+ Where implementation files go. Example: \`src/\` for application logic, \`src/core/\` for
501
+ domain logic, \`src/cli/\` for command-line interface.
502
+
503
+ ## Tests
504
+
505
+ Where test files go and how they mirror source structure. Example: \`tests/\` mirroring
506
+ \`src/\` layout, or \`__tests__/\` co-located with source.
507
+
508
+ ## Documents
509
+
510
+ Where project documentation goes (excluding \`.loom/\` which is LOOM state). Example:
511
+ \`docs/\` for user-facing docs, \`README.md\` at root for entry.
512
+
513
+ ## Configuration and build
514
+
515
+ Where build configs, CI definitions, and dependency manifests go. Example:
516
+ \`package.json\`, \`.github/workflows/\`, \`tsconfig.json\`.
517
+
518
+ ## Assets and fixtures
519
+
520
+ Where static assets, test fixtures, and data files go. Example: \`assets/\`, \`fixtures/\`,
521
+ \`data/\`.
522
+
523
+ ## Conventions
524
+
525
+ Any naming or placement conventions the Agent should follow. Example: "one module per
526
+ file", "test files end with \`.test.\`", "config files are JSON not YAML".
527
+ `;
528
+
529
+ const DESIGN_SECTIONS = {
530
+ product: ['Outcome and users', 'Problem and operating reality', 'Product principles', 'Scope and non-goals', 'End-to-end behavior', 'Success and failure signals', 'Decisions and open questions', 'Related documents and capabilities'],
531
+ experience: ['Experience intent', 'Users and contexts', 'Journey and information architecture', 'Interaction states and transitions', 'Content, visual, and accessibility direction', 'Errors, empty states, and recovery', 'Usability verification', 'Related documents and capabilities'],
532
+ system: ['Responsibility in the whole', 'Inputs, outputs, and boundaries', 'Components and control flow', 'Data and state', 'Interfaces and dependencies', 'Failure, safety, and recovery', 'Implementation constraints', 'Verification strategy', 'Related documents and capabilities'],
533
+ contract: ['Consumers and purpose', 'Schema or command surface', 'Invariants and permissions', 'Errors and compatibility', 'Examples and fixtures', 'Contract tests', 'Related documents and capabilities'],
534
+ verification: ['Claims under test', 'Environments and fixtures', 'Acceptance matrix', 'Commands and evidence', 'Negative and failure tests', 'Known blind spots', 'Related documents and capabilities'],
535
+ operations: ['Operational outcome', 'Preconditions and authority', 'Procedure and commands', 'Safety boundaries', 'Failure detection and recovery', 'Evidence and audit trail', 'Related documents and capabilities'],
536
+ research: ['Decision to inform', 'Current evidence and unknowns', 'Method and sources', 'Findings', 'Conflicts and limitations', 'Project consequences', 'Follow-up verification', 'Related documents and capabilities'],
537
+ };
538
+
539
+ export const DESIGN_KINDS = Object.freeze(Object.keys(DESIGN_SECTIONS));
540
+
541
+ export function designTemplate({ title, kind }) {
542
+ const sections = DESIGN_SECTIONS[kind];
543
+ if (!sections) throw new Error(`Unknown design kind: ${kind}`);
544
+ return `# ${title}\n\n- Kind: ${kind}\n- Status: shaping\n\n${sections.map((section) => `## ${section}\n\nDescribe the project-specific decision, mechanism, boundary, or evidence owned by this section.`).join('\n\n')}\n`;
545
+ }
546
+
547
+ export const CAPABILITY_TEMPLATE = ({ title }) => `# ${title}
548
+
549
+ > One dossier covers one recognizable professional field. Keep UI/UX, visual art direction, game
550
+ > design, psychology, biology, security, and other fields separate when their evidence and judgments
551
+ > differ. Put cross-field synthesis in the affected design document, not in a hybrid capability title.
552
+ > The kernel of a capability is a decision tree with conditional branches that captures how an expert
553
+ > in this field thinks — not a fixed step list or a declarative stance document. It is a resource for
554
+ > the Agent to use, not a script it must follow. When evidence points outside the tree, trust the
555
+ > evidence and update the tree.
556
+
557
+ ## Field identity and boundary
558
+
559
+ Name the established field, what expertise it contributes, and what belongs to another dossier.
560
+
561
+ ## Project scenario
562
+
557
563
  > This section records which expert situation the project most closely resembles. Use
558
564
  > \`loom capability confirm <slug> --scenario <text> --source human\` for user confirmation. When the
559
565
  > human is unavailable, use \`--source agent\`; LOOM records the selection as provisional.
560
-
561
- State the project scenario that determines which branches of the decision tree are active.
562
-
563
- ## Decision tree
564
-
565
- > Each node is a named decision point an expert reaches in this field. Nodes have entry conditions,
566
- > conditional options, judgment criteria, source citations, counterexamples, and outputs. A node
567
- > without a source citation is not accepted. A branch without a counterexample is a fixed step in
568
- > disguise.
569
-
570
- ### C1: <node name>
571
-
572
- - entry_when: <condition under which an expert arrives at this node>
573
- - options:
574
- - A: <option A> → leads_to: <next node or output>
575
- - B: <option B> → leads_to: <next node or output>
576
- - decide_by: <evidence that determines which option to take>
577
- - source: <which research material or expert narrative supports this node>
578
- - counterexample: <a situation where an expert would NOT walk this path>
579
- - output: <what this node produces — typically a design decision>
580
-
581
- ### C2: <node name>
582
-
583
- <repeat the structure above for each decision node>
584
-
585
- ## Stance and rejected defaults
586
-
587
- > The stance is subordinate to the decision tree. It records what this project refuses and why, but
588
- > the decision tree carries the thinking process.
589
-
590
- State what this project will do, why, the important tradeoffs, and which common or generic approaches it
591
- will deliberately refuse.
592
-
593
- ## Failure signals
594
-
595
- Describe characteristic weak, generic, or harmful outcomes and the observable evidence that distinguishes
596
- a strong result. Experts know when they have gone wrong — record those signals here.
597
-
598
- ## Relationships without merger
599
-
600
- Link adjacent capability dossiers and explain the tension or handoff. Do not absorb their expertise here.
601
- `;
602
-
603
- export const RESEARCH_GUIDE = `# Research guide for this capability
604
-
605
- > This file guides what to write in the research/ directory. Delete it when you have added your own
606
- > research materials. \`loom capability synthesize\` reads all .md files in this directory (except this
607
- > guide) and expects them to contain expert narratives, case studies, or methodology sources that
608
- > inform the decision tree.
609
-
610
- ## What to write
611
-
612
- Create one .md file per research source. Each file should answer: **how does an expert in this field
613
- think through the problems this project faces?**
614
-
615
- Good research materials include:
616
- - Expert narratives: how a practitioner describes their own decision process
617
- - Case studies: real projects where this field's decisions mattered, and what happened
618
- - Methodology sources: established frameworks, heuristics, or principles from the field
619
- - Failure accounts: what went wrong when the field's judgment was absent or ignored
620
-
621
- Bad research materials (will produce weak decision trees):
622
- - Generic textbook summaries with no project-specific relevance
623
- - Tool documentation or API references (those are not professional judgment)
624
- - Marketing copy or opinion pieces without evidence
625
-
626
- ## File format
627
-
628
- Name files descriptively: \`expert-decision-process.md\`, \`case-study-X.md\`, \`failure-account-Y.md\`.
629
- Each file should be 1-3 paragraphs of substantive content. Include the source at the top:
630
-
631
- \`\`\`markdown
632
- # <descriptive title>
633
-
634
- Source: <book, article, interview, observation, or personal experience>
635
-
636
- <content: how the expert thinks, what they decided, what evidence they used, what happened>
637
- \`\`\`
638
-
639
- ## How this feeds synthesize
640
-
641
- \`loom capability synthesize\` checks that:
642
- 1. At least one .md file exists in research/ (besides this guide)
643
- 2. Every decision tree node (### C1, C2, ...) in capability.md has a \`source:\` field
644
- 3. Every node has a \`counterexample:\` field
645
-
646
- The source field in each node should reference which research file supports it. Write research that
647
- you can cite by name when you build the decision tree.
648
- `;
649
-
650
- export function evalConditionPrompt({ brief, loom, humanChannel = 'available' }) {
651
- const environment = environmentProtocol({ humanChannel }).replace('## Environment availability\n\n', '');
652
- return loom
653
- ? `# Evaluation condition\n\n${brief}\n\n${environment}\n\nWork with all ordinary Agent capabilities and tools. Use LOOM as invisible continuity infrastructure: run \`loom context --human-channel ${humanChannel}\`, maintain its disk state, and never ask the human to operate it. This condition has no extra authority or information.`
654
- : `# Evaluation condition\n\n${brief}\n\n${environment}\n\nWork as a normal capable Agent with all ordinary capabilities and tools. LOOM and its files are unavailable in this condition. Use any normal planning or documentation you judge useful.`;
655
- }
656
-
657
- export function evalJudgePrompt() {
658
- return `# Blind Evil Eval judge
659
-
660
- You receive two anonymized runs in randomized order. Do not infer framework identity. Judge observable
661
- work, not framework-shaped filenames or document volume. Cite evidence for every score. Compare intent
662
- fidelity, question value, whole-project coverage, professional capability depth, buildability, continuity
663
- after forced resets, implementation evidence, user burden, and cost/time. Penalize unnecessary ceremony,
664
- questions that do not change decisions, and documentation that a fresh Agent cannot use. Swap order and
665
- judge again; mark order-sensitive conclusions unstable. Attribute missing files or path failures to a run
666
- only after the anonymized packet passed its relative-layout and declared-test preflight. A system wins only if its benefit survives equal
667
- model, tools, workspace, user facts, reset points, and budget.`;
668
- }
669
-
670
- export function promptCatalog() {
671
- const placeholderState = {
672
- project: { status: '<project-status>' },
673
- understanding: {
674
- confirmed: [],
675
- assumptions: [{ id: '<assumption-id>', text: '<assumption>', status: 'active' }],
676
- unresolved: [{ id: '<question-id>', question: '<material uncertainty>', impact: 'high', status: 'open' }],
677
- },
678
- keeper: { status: 'not_run', attempts: [] },
679
- };
680
- const revisionState = {
681
- ...placeholderState,
682
- keeper: {
683
- status: 'needs_revision',
684
- attempts: [{
685
- verdict: 'needs_revision',
686
- run_id: '<fresh-run-id>',
687
- summary: '<why the handoff cannot start>',
688
- gaps: ['<concrete gap>'],
689
- evidence: ['<observable evidence>'],
690
- }],
691
- },
692
- };
693
- return {
694
- purpose: 'Complete inventory of LOOM cognitive messages. Validation errors and JSON status payloads enforce state but are not Agent prompts.',
695
- layers: {
696
- stable_core: AGENT_CORE,
697
- environment_adaptation_available: environmentProtocol({ humanChannel: 'available' }),
698
- environment_adaptation_unavailable: environmentProtocol({ humanChannel: 'unavailable' }),
699
- runtime_protocol: RUNTIME_PROTOCOL,
700
- execution_protocol: EXECUTION_PROTOCOL,
701
- project_state: shapingContext({ state: placeholderState, taskSummary: { total: 0, done: 0, open: 0, blocked: 0, active: null }, capabilityNames: [], designNames: [] }),
702
- project_state_after_keeper_failure: shapingContext({ state: revisionState, taskSummary: { total: 1, done: 0, open: 1, blocked: 0, active: null }, capabilityNames: ['<field>'], designNames: ['<system>.md'] }),
703
- keeper_review_of_prior_failure: shapingContext({ state: revisionState, taskSummary: { total: 1, done: 0, open: 1, blocked: 0, active: null }, capabilityNames: ['<field>'], designNames: ['<system>.md'], forKeeper: true }),
704
- current_task: '## Active Task\n\n<exact Task JSON including acceptance, implements, capability_hooks, and covers if present>\n\n---\n\n## Task context: <path from Task.reads>\n\n<exact file content>\n\n(repeated for every read path)\n\n---\n\n## Capability decision points\n\n<extracted decision-tree nodes referenced by capability_hooks, with options, criteria, sources, and counterexamples>',
705
- on_demand_map: '## On-demand project context\n\n- Decision history: .loom/DECISIONS.md (read when correction or lineage matters; records what changed and why)\n- Design: .loom/design/<document>.md\n- Professional capability: .loom/capabilities/<field>/capability.md\n- Project structure: .loom/STRUCTURE.md (read before creating or moving files)',
706
- keeper_context: '## Decision history (...)\n\n<exact DECISIONS.md>\n\n---\n\n## Work map summary\n\n<summary and first executable Task>\n\n---\n\n## Design document: <name>\n\n<exact content>\n\n---\n\n## Capability dossier: <name>\n\n<exact content>',
707
- },
708
- workspace_anchor: AGENT_ANCHOR,
709
- templates: {
710
- project_index: PROJECT_TEMPLATE,
711
- project_structure: STRUCTURE_TEMPLATE,
712
- design_documents: Object.fromEntries(DESIGN_KINDS.map((kind) => [kind, designTemplate({ title: `<${kind}-title>`, kind })])),
713
- professional_capability: CAPABILITY_TEMPLATE({ title: '<recognizable-professional-field>' }),
714
- decision_history: '# Decision History\n\nCurrent truth belongs in PROJECT.md and linked design documents. This file preserves consequential superseding decisions.',
715
- },
716
- keeper: keeperProtocol({ attemptNumber: '<attempt-number>', preparedDigest: '<prepared-digest>' }),
717
- evaluation: {
718
- baseline_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: false }),
719
- loom_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: true }),
720
- unattended_baseline_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: false, humanChannel: 'unavailable' }),
721
- unattended_loom_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: true, humanChannel: 'unavailable' }),
722
- blind_judge: evalJudgePrompt(),
723
- },
724
- composition: {
725
- normal_resume: ['stable_core', 'environment_adaptation', 'runtime_protocol', 'project_state', 'PROJECT.md', 'on-demand document and capability map'],
726
- active_task: ['normal_resume', 'execution_protocol', 'active Task JSON', 'exact files in Task.reads'],
727
- keeper_handoff: ['keeper', 'normal_resume', 'DECISIONS.md', 'Work Map summary and first executable Task', 'all design documents', 'all professional capability dossiers'],
728
- },
729
- };
730
- }
566
+
567
+ State the project scenario that determines which branches of the decision tree are active.
568
+
569
+ ## Decision tree
570
+
571
+ > Each node is a named decision point an expert reaches in this field. Nodes have entry conditions,
572
+ > conditional options, judgment criteria, source citations, counterexamples, and outputs. A node
573
+ > without a source citation is not accepted. A branch without a counterexample is a fixed step in
574
+ > disguise.
575
+
576
+ ### C1: <node name>
577
+
578
+ - entry_when: <condition under which an expert arrives at this node>
579
+ - options:
580
+ - A: <option A> → leads_to: <next node or output>
581
+ - B: <option B> → leads_to: <next node or output>
582
+ - decide_by: <evidence that determines which option to take>
583
+ - source: <which research material or expert narrative supports this node>
584
+ - counterexample: <a situation where an expert would NOT walk this path>
585
+ - output: <what this node produces — typically a design decision>
586
+
587
+ ### C2: <node name>
588
+
589
+ <repeat the structure above for each decision node>
590
+
591
+ ## Stance and rejected defaults
592
+
593
+ > The stance is subordinate to the decision tree. It records what this project refuses and why, but
594
+ > the decision tree carries the thinking process.
595
+
596
+ State what this project will do, why, the important tradeoffs, and which common or generic approaches it
597
+ will deliberately refuse.
598
+
599
+ ## Failure signals
600
+
601
+ Describe characteristic weak, generic, or harmful outcomes and the observable evidence that distinguishes
602
+ a strong result. Experts know when they have gone wrong — record those signals here.
603
+
604
+ ## Relationships without merger
605
+
606
+ Link adjacent capability dossiers and explain the tension or handoff. Do not absorb their expertise here.
607
+ `;
608
+
609
+ export const RESEARCH_GUIDE = `# Research guide for this capability
610
+
611
+ > This file guides what to write in the research/ directory. Delete it when you have added your own
612
+ > research materials. \`loom capability synthesize\` reads all .md files in this directory (except this
613
+ > guide) and expects them to contain expert narratives, case studies, or methodology sources that
614
+ > inform the decision tree.
615
+
616
+ ## What to write
617
+
618
+ Create one .md file per research source. Each file should answer: **how does an expert in this field
619
+ think through the problems this project faces?**
620
+
621
+ Good research materials include:
622
+ - Expert narratives: how a practitioner describes their own decision process
623
+ - Case studies: real projects where this field's decisions mattered, and what happened
624
+ - Methodology sources: established frameworks, heuristics, or principles from the field
625
+ - Failure accounts: what went wrong when the field's judgment was absent or ignored
626
+
627
+ Bad research materials (will produce weak decision trees):
628
+ - Generic textbook summaries with no project-specific relevance
629
+ - Tool documentation or API references (those are not professional judgment)
630
+ - Marketing copy or opinion pieces without evidence
631
+
632
+ ## File format
633
+
634
+ Name files descriptively: \`expert-decision-process.md\`, \`case-study-X.md\`, \`failure-account-Y.md\`.
635
+ Each file should be 1-3 paragraphs of substantive content. Include the source at the top:
636
+
637
+ \`\`\`markdown
638
+ # <descriptive title>
639
+
640
+ Source: <book, article, interview, observation, or personal experience>
641
+
642
+ <content: how the expert thinks, what they decided, what evidence they used, what happened>
643
+ \`\`\`
644
+
645
+ ## How this feeds synthesize
646
+
647
+ \`loom capability synthesize\` checks that:
648
+ 1. At least one .md file exists in research/ (besides this guide)
649
+ 2. Every decision tree node (### C1, C2, ...) in capability.md has a \`source:\` field
650
+ 3. Every node has a \`counterexample:\` field
651
+
652
+ The source field in each node should reference which research file supports it. Write research that
653
+ you can cite by name when you build the decision tree.
654
+ `;
655
+
656
+ export function evalConditionPrompt({ brief, loom, humanChannel = 'available' }) {
657
+ const environment = environmentProtocol({ humanChannel }).replace('## Environment availability\n\n', '');
658
+ return loom
659
+ ? `# Evaluation condition\n\n${brief}\n\n${environment}\n\nWork with all ordinary Agent capabilities and tools. Use LOOM as invisible continuity infrastructure: run \`loom context --human-channel ${humanChannel}\`, maintain its disk state, and never ask the human to operate it. This condition has no extra authority or information.`
660
+ : `# Evaluation condition\n\n${brief}\n\n${environment}\n\nWork as a normal capable Agent with all ordinary capabilities and tools. LOOM and its files are unavailable in this condition. Use any normal planning or documentation you judge useful.`;
661
+ }
662
+
663
+ export function evalJudgePrompt() {
664
+ return `# Blind Evil Eval judge
665
+
666
+ You receive two anonymized runs in randomized order. Do not infer framework identity. Judge observable
667
+ work, not framework-shaped filenames or document volume. Cite evidence for every score. Compare intent
668
+ fidelity, question value, whole-project coverage, professional capability depth, buildability, continuity
669
+ after forced resets, implementation evidence, user burden, and cost/time. Penalize unnecessary ceremony,
670
+ questions that do not change decisions, and documentation that a fresh Agent cannot use. Swap order and
671
+ judge again; mark order-sensitive conclusions unstable. Attribute missing files or path failures to a run
672
+ only after the anonymized packet passed its relative-layout and declared-test preflight. A system wins only if its benefit survives equal
673
+ model, tools, workspace, user facts, reset points, and budget.`;
674
+ }
675
+
676
+ export function promptCatalog() {
677
+ const placeholderState = {
678
+ project: { status: '<project-status>' },
679
+ understanding: {
680
+ confirmed: [],
681
+ assumptions: [{ id: '<assumption-id>', text: '<assumption>', status: 'active' }],
682
+ unresolved: [{ id: '<question-id>', question: '<material uncertainty>', impact: 'high', status: 'open' }],
683
+ },
684
+ keeper: { status: 'not_run', attempts: [] },
685
+ };
686
+ const revisionState = {
687
+ ...placeholderState,
688
+ keeper: {
689
+ status: 'needs_revision',
690
+ attempts: [{
691
+ verdict: 'needs_revision',
692
+ run_id: '<fresh-run-id>',
693
+ summary: '<why the handoff cannot start>',
694
+ gaps: ['<concrete gap>'],
695
+ evidence: ['<observable evidence>'],
696
+ }],
697
+ },
698
+ };
699
+ return {
700
+ purpose: 'Complete inventory of LOOM cognitive messages. Validation errors and JSON status payloads enforce state but are not Agent prompts.',
701
+ layers: {
702
+ stable_core: AGENT_CORE,
703
+ environment_adaptation_available: environmentProtocol({ humanChannel: 'available' }),
704
+ environment_adaptation_unavailable: environmentProtocol({ humanChannel: 'unavailable' }),
705
+ runtime_protocol: RUNTIME_PROTOCOL,
706
+ execution_protocol: EXECUTION_PROTOCOL,
707
+ project_state: shapingContext({ state: placeholderState, taskSummary: { total: 0, done: 0, open: 0, blocked: 0, active: null }, capabilityNames: [], designNames: [] }),
708
+ project_state_after_keeper_failure: shapingContext({ state: revisionState, taskSummary: { total: 1, done: 0, open: 1, blocked: 0, active: null }, capabilityNames: ['<field>'], designNames: ['<system>.md'] }),
709
+ keeper_review_of_prior_failure: shapingContext({ state: revisionState, taskSummary: { total: 1, done: 0, open: 1, blocked: 0, active: null }, capabilityNames: ['<field>'], designNames: ['<system>.md'], forKeeper: true }),
710
+ current_task: '## Active Task\n\n<exact Task JSON including acceptance, implements, capability_hooks, and covers if present>\n\n---\n\n## Task context: <path from Task.reads>\n\n<exact file content>\n\n(repeated for every read path)\n\n---\n\n## Capability decision points\n\n<extracted decision-tree nodes referenced by capability_hooks, with options, criteria, sources, and counterexamples>',
711
+ on_demand_map: '## On-demand project context\n\n- Decision history: .loom/DECISIONS.md (read when correction or lineage matters; records what changed and why)\n- Design: .loom/design/<document>.md\n- Professional capability: .loom/capabilities/<field>/capability.md\n- Project structure: .loom/STRUCTURE.md (read before creating or moving files)',
712
+ keeper_context: '## Decision history (...)\n\n<exact DECISIONS.md>\n\n---\n\n## Work map summary\n\n<summary and first executable Task>\n\n---\n\n## Design document: <name>\n\n<exact content>\n\n---\n\n## Capability dossier: <name>\n\n<exact content>',
713
+ },
714
+ workspace_anchor: AGENT_ANCHOR,
715
+ templates: {
716
+ project_index: PROJECT_TEMPLATE,
717
+ project_structure: STRUCTURE_TEMPLATE,
718
+ design_documents: Object.fromEntries(DESIGN_KINDS.map((kind) => [kind, designTemplate({ title: `<${kind}-title>`, kind })])),
719
+ professional_capability: CAPABILITY_TEMPLATE({ title: '<recognizable-professional-field>' }),
720
+ decision_history: '# Decision History\n\nCurrent truth belongs in PROJECT.md and linked design documents. This file preserves consequential superseding decisions.',
721
+ },
722
+ keeper: keeperProtocol({ attemptNumber: '<attempt-number>', preparedDigest: '<prepared-digest>' }),
723
+ evaluation: {
724
+ baseline_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: false }),
725
+ loom_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: true }),
726
+ unattended_baseline_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: false, humanChannel: 'unavailable' }),
727
+ unattended_loom_condition: evalConditionPrompt({ brief: '<identical-raw-brief>', loom: true, humanChannel: 'unavailable' }),
728
+ blind_judge: evalJudgePrompt(),
729
+ },
730
+ composition: {
731
+ normal_resume: ['stable_core', 'environment_adaptation', 'runtime_protocol', 'project_state', 'PROJECT.md', 'on-demand document and capability map'],
732
+ active_task: ['normal_resume', 'execution_protocol', 'active Task JSON', 'exact files in Task.reads'],
733
+ keeper_handoff: ['keeper', 'normal_resume', 'DECISIONS.md', 'Work Map summary and first executable Task', 'all design documents', 'all professional capability dossiers'],
734
+ },
735
+ };
736
+ }