ytdb-slate 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  Approved update notes for Slate releases appear here.
4
4
 
5
+ ## [0.22.0]
6
+
7
+ You can now save a private model and thinking level for each project. Run `/slate model save` in the main session. Slate applies the saved choice when a new interactive session starts. `/slate model` shows the choice, and `/slate model clear` removes it. Use pi 1.6.0 or later.
8
+
9
+ https://github.com/JetBrains/ytdb-slate/releases/tag/v0.22.0
10
+
5
11
  ## [0.21.0]
6
12
 
7
13
  The `threads` tool now lists the worker threads of the current session by default. The new `parentSession` parameter lists the threads of the newest earlier session. After a Slate handoff, `pi --continue` now opens the new session instead of the earlier session. Use pi 1.6.0 or later.
package/README.md CHANGED
@@ -101,6 +101,9 @@ Slate independently implements the thread-weaving architecture from the Random L
101
101
  | `/slate summary` | Show the workflow summary in any mode, even when automatic display is off. |
102
102
  | `/slate summary off` | Stop automatic display and remove a visible summary. |
103
103
  | `/slate summary on` | Save automatic display for the next startup or mode activation. |
104
+ | `/slate model` | Show the stored model, thinking level and [project key](docs/configuration.md#private-project-model). |
105
+ | `/slate model save` | Save the current main-session model and thinking level for this project. |
106
+ | `/slate model clear` | Remove the stored choice for this project. |
104
107
  | `/slate effective` | Show the effective logical-model policy and remembered route selections. |
105
108
  | `/slate handoff [focus]` | Prepare a new-session handoff, with an optional focus. |
106
109
  | `/slate resume` | Clear a context-budget pause and accept user prompts again. |
@@ -29,6 +29,155 @@ The short workflow summary is off by default. Run `/slate summary on` to save an
29
29
 
30
30
  Slate stores this choice as the boolean `startupSummary` key in `<getAgentDir()>/slate-preferences.json`. Pi uses `PI_CODING_AGENT_DIR` when that environment variable sets the agent directory. A missing file or key means the summary is off. Invalid values and read errors warn and enable the summary. This file does not grant home configuration permission in untrusted projects. A `startupSummary` key in either `slate.json` has no effect.
31
31
 
32
+ ## Private project model
33
+
34
+ Run `/slate model save` to save the current model and thinking level of the main session.
35
+ Changing the session model does not save a choice.
36
+ Slate keeps the choice in the **private store**, `slate-preferences.json` in the Pi agent directory.
37
+
38
+ Slate applies the private project model at the start of an interactive main session with no conversation messages on any branch.
39
+ This includes a fresh launch and `/new`, even directly after a handoff.
40
+ The rule applies with orchestrator mode on or off.
41
+
42
+ A handoff continues work in a successor session.
43
+ Slate excludes the successor session even if it cannot take the parent session's model.
44
+ Slate also excludes sessions opened by `/resume`, `/fork`, or the `--fork` option.
45
+ Slate still excludes a forked session when you reopen it.
46
+ Slate does not apply the choice on `/reload`.
47
+ Slate does not apply the choice in print mode, JSON mode, remote procedure call (RPC) mode, or worker threads.
48
+
49
+ Model selection uses this order from lowest to highest priority:
50
+
51
+ 1. User Pi settings.
52
+ 2. Project Pi settings. Pi uses values from `.pi/settings.json` only when it trusts the project.
53
+ 3. Private project model.
54
+ 4. Explicit `--model`.
55
+
56
+ When you specify a model with `--model`, Slate applies neither the stored model nor the stored thinking level.
57
+ With `--thinking` alone, Slate uses that thinking level with the stored model.
58
+ The **requested thinking level** is the command-line level when present and the stored level otherwise.
59
+ Slate sets it after switching the model.
60
+ The **effective thinking level** is the level Pi uses.
61
+
62
+ When Slate applies the choice, one notice names the model and the effective thinking level.
63
+ If both already match, Slate changes nothing and shows no notice.
64
+ If the project has no entry, Slate remains silent.
65
+ Slate warns and keeps the model Pi selected if:
66
+
67
+ - Slate cannot determine the project key.
68
+ - Slate cannot read the private store.
69
+ - The entry is invalid.
70
+ - Pi does not know the model.
71
+ - The model has no configured credentials.
72
+ - Pi refuses the switch or the switch fails before changing the session.
73
+
74
+ If a switch fails after changing the session, Slate warns and names the model and thinking level in use.
75
+ Slate records that live state.
76
+ If the requested and effective thinking levels differ, Slate reports both levels.
77
+
78
+ The **project key** identifies the project in `slate-preferences.json`.
79
+ Run `/slate model` to show the saved choice and its project key.
80
+ If the project has no stored model, Slate shows the key and reports the absence.
81
+ Slate warns if the stored entry is invalid.
82
+ Run `/slate model clear` to remove the choice.
83
+ If there is no entry to clear, Slate reports that and leaves the file unchanged.
84
+
85
+ Slate treats any input whose first word after `/slate` starts with `model` as a model command.
86
+ Letter case does not matter.
87
+ For any form other than the three listed above, Slate shows the valid forms.
88
+ Slate leaves orchestrator mode unchanged.
89
+
90
+ A worktree is a directory where Git checks out files.
91
+ The **Git common directory** holds Git data shared by all worktrees of one clone.
92
+ Slate uses its real path as the project key.
93
+ All worktrees of one clone share one key.
94
+ A bare repository has no worktree and uses its own directory as the Git common directory.
95
+
96
+ Slate searches the working directory and its parents.
97
+ The nearest directory with a `.git` entry or with Git data of its own decides the key.
98
+ A `.git` entry can be a directory or a file that points to a Git directory.
99
+ If Slate finds damaged or unreadable Git data there, it refuses to use a key.
100
+ Slate does not use a repository further up.
101
+
102
+ An empty or broken `.git` entry inside a repository also causes this refusal.
103
+ Remove the empty or broken entry to continue.
104
+ A hand-made `.git` file that points to another valid repository uses that repository's entry.
105
+ If you run `/slate model clear` inside a nested repository, Slate uses that repository's key.
106
+ A subdirectory shares its worktree's key unless a nearer `.git` entry or Git directory decides the result.
107
+ If Slate cannot read or validate that nearer entry or directory, it reports that it cannot determine the key.
108
+ If Slate finds no Git directory or `.git` entry, it uses the real path of the working directory as the key.
109
+ If Slate cannot determine the key, none of the commands uses a substitute.
110
+ Git environment variables such as `GIT_DIR` do not affect the key.
111
+
112
+ The key matches the real path of the Git common directory that Git reports for these layouts:
113
+
114
+ - A normal clone, which is a local copy of a repository.
115
+ - A linked worktree, which shares Git data with another worktree.
116
+ - A bare repository.
117
+ - A nested repository, which sits inside another repository.
118
+ - A submodule, which is a repository that another repository tracks.
119
+ - A worktree with a separate Git directory.
120
+ - A working directory inside a Git directory. Slate uses the key of the repository that owns that Git directory.
121
+ - A working directory that you reach through a symbolic link. A symbolic link is a file system entry that points to another path.
122
+
123
+ A new repository with no commits uses the same key as it does after its first commit.
124
+ The key stays the same with a detached `HEAD`, which points to a commit instead of a branch.
125
+ Git references name commits or other references.
126
+ The key also stays the same with packed references or with reftable, two ways Git stores references.
127
+
128
+ Slate checks the structure of Git files.
129
+ Slate limits how much it reads from each file.
130
+ Slate reads no Git configuration.
131
+ Slate does not check who owns the repository.
132
+ Slate does not stop when the search crosses a file system boundary.
133
+ Slate gives an otherwise valid repository a key even if Git refuses it for one of these reasons.
134
+
135
+ Slate refuses to use a key if the real path of the working directory or a Git directory is not valid text.
136
+ Slate refuses to read or write the private store if its real path is not valid text.
137
+ Before it creates the store, Slate checks the real path of the closest parent folder that exists.
138
+ Slate refuses to create the store if that path is not valid text.
139
+
140
+ Separate clones use separate Git common directories and do not share an entry.
141
+ A normal clone stores its Git common directory at `<clone>/.git`, so moving the clone changes the key.
142
+ A checkout that points to the same Git common directory after a move keeps its key.
143
+ A new clone uses the earlier entry if it has the same Git common directory path.
144
+ An entry stays until you remove it.
145
+
146
+ You can edit the file by hand. The optional `projectModels` key holds a JSON object.
147
+ Each property name is a project key. Its value holds a `model` and a `thinkingLevel`:
148
+
149
+ ```json
150
+ {
151
+ "startupSummary": true,
152
+ "projectModels": {
153
+ "/home/dev/project/.git": {
154
+ "model": "anthropic/claude-sonnet-4-5",
155
+ "thinkingLevel": "medium"
156
+ }
157
+ }
158
+ }
159
+ ```
160
+
161
+ Use `provider/id` for `model`, not a name from Slate routing.
162
+ Slate reads the text before the first slash as the provider.
163
+ Slate cannot save a provider name with a slash or model text with white space.
164
+ The thinking level is one of `off`, `minimal`, `low`, `medium`, `high`, `xhigh` or `max`.
165
+ Remove a property from `projectModels` to remove its entry by hand.
166
+ Slate refuses to save or clear if the file or `projectModels` is not a JSON object.
167
+ You can save over an invalid entry for the current project or clear it.
168
+ Slate does not validate other projects' entries during a save or clear.
169
+ The file stays after the last clear.
170
+
171
+ Each write replaces the whole file. If writes overlap, the later write wins.
172
+ Slate keeps other keys and writes the file with two-space indentation.
173
+ A number in a key that Slate does not own changes on rewrite if JavaScript cannot represent it exactly.
174
+ Negative zero in such a key becomes zero on rewrite.
175
+
176
+ After replacing the file, Slate asks the operating system to write the folder entry to disk.
177
+ This operation is a **folder flush**.
178
+ Slate warns if the folder flush fails.
179
+ Slate gives no such warning on Windows or on a file system that offers no folder flush.
180
+
32
181
  ## Common starting point
33
182
 
34
183
  Create `.pi/slate.json` when you want new interactive sessions to start in orchestrator mode:
@@ -197,28 +197,28 @@ characters. Tool names use 64 characters. Descriptions use 140 characters.
197
197
 
198
198
  | fixture | paths | portable characters | lines |
199
199
  | --- | ---: | ---: | ---: |
200
- | shipped logical section | 0 | 4,528 | 9 |
201
- | trusted shipped-default doctrine | 5 | 9,336 | 72 |
200
+ | shipped logical section | 0 | 4,938 | 9 |
201
+ | trusted shipped-default doctrine | 5 | 9,746 | 72 |
202
202
  | untrusted doctrine without a home configuration file | 4 | 2,711 | 33 |
203
- | draft pull requests, shipped policy | 6 | 9,406 | 73 |
204
- | capped workers, shipped policy | 5 | 10,683 | 82 |
205
- | draft plus capped workers | 6 | 10,753 | 83 |
206
- | deferred issues plus capped workers | 5 | 10,757 | 83 |
207
- | routing recommendations plus capped workers | 5 | 10,736 | 83 |
208
- | draft plus deferred issues and capped workers | 6 | 10,827 | 84 |
209
- | draft plus routing recommendations and capped workers | 6 | 10,802 | 84 |
210
- | deferred issues plus routing recommendations and capped workers | 5 | 10,810 | 84 |
211
- | canonical maximal baseline with all workflow options | 6 | 10,876 | 85 |
212
- | maximal baseline with an open change | 6 | 11,074 | 86 |
213
- | maximal baseline with source and legacy root log | 6 | 11,304 | 88 |
214
- | dogfood `.pi/slate.json` and its two extension units | 6 | 10,001 | 84 |
203
+ | draft pull requests, shipped policy | 6 | 9,816 | 73 |
204
+ | capped workers, shipped policy | 5 | 11,093 | 82 |
205
+ | draft plus capped workers | 6 | 11,163 | 83 |
206
+ | deferred issues plus capped workers | 5 | 11,167 | 83 |
207
+ | routing recommendations plus capped workers | 5 | 11,146 | 83 |
208
+ | draft plus deferred issues and capped workers | 6 | 11,237 | 84 |
209
+ | draft plus routing recommendations and capped workers | 6 | 11,212 | 84 |
210
+ | deferred issues plus routing recommendations and capped workers | 5 | 11,220 | 84 |
211
+ | canonical maximal baseline with all workflow options | 6 | 11,286 | 85 |
212
+ | maximal baseline with an open change | 6 | 11,484 | 86 |
213
+ | maximal baseline with source and legacy root log | 6 | 11,714 | 88 |
214
+ | dogfood `.pi/slate.json` and its two extension units | 6 | 10,411 | 84 |
215
215
  | runtime boundary plus draft and capped workers, source and legacy log | 6 | 26,053 | 86 |
216
216
  | runtime boundary plus draft and deferred issues, source and legacy log | 6 | 26,127 | 87 |
217
217
  | runtime boundary plus routing recommendations, source and legacy log | 5 | 26,036 | 86 |
218
218
  | runtime boundary plus deferred issues and routing recommendations, source and legacy log | 5 | 26,110 | 87 |
219
219
  | runtime boundary plus draft and routing recommendations, source and legacy log | 6 | 26,102 | 87 |
220
220
  | same boundary composition plus deferred issues | 6 | 26,176 | 88 |
221
- | valid shipped policy plus 88 capped worker tools, source and legacy log | 6 | 28,978 | 171 |
221
+ | valid shipped policy plus 88 capped worker tools, source and legacy log | 6 | 29,388 | 171 |
222
222
 
223
223
  An untrusted session with an empty home `slate.json` receives the same doctrine
224
224
  as the trusted shipped-default fixture above. It includes routing and writing
@@ -229,7 +229,7 @@ project preferences can.
229
229
  The canonical maximal baseline uses all four default logical models, all
230
230
  three workflow options, and the fixed capped worker roster. Its largest variant
231
231
  has an open change, one direct source folder, and a legacy root log. Its
232
- five-percent requirement is `ceil(11,304 × 1.05) = 11,870`.
232
+ five-percent requirement is `ceil(11,714 × 1.05) = 12,300`.
233
233
  The 26,300 whole-doctrine ceiling exceeds it. The table pins all eight
234
234
  combinations of the three workflow options with the capped worker roster. The
235
235
  dogfood row reads the actual project configuration. A change to `.pi/slate.json` requires a fresh render.
@@ -246,9 +246,9 @@ the first value beyond the ceiling.
246
246
 
247
247
  The over-cap counterfactual uses a valid shipped logical policy and one supported
248
248
  worker-extension unit with 88 capped tools. It also includes an open change,
249
- its source, and the legacy root log. Its 28,978 portable characters exceed
250
- the whole-doctrine ceiling by 2,678. The check therefore detects whole-doctrine
251
- growth without using a retired model-row shape or an assumed per-tool increment.
249
+ its source, and the legacy root log. Its 29,388 portable characters exceed
250
+ the whole-doctrine ceiling by 3,088. The check measures the whole doctrine
251
+ directly.
252
252
  Worker-extension doctrine has no runtime size cap, so the fixture reaches the
253
253
  whole-doctrine guard rather than failing logical-policy validation first.
254
254
 
@@ -262,9 +262,9 @@ Check the phase-row table with `test/workflow-context-budget.test.ts`.
262
262
  The logical-section limits remain 19,400 characters and 105 lines. The
263
263
  all-tail limit remains 24,600 characters. The whole-doctrine ceiling is 26,300 characters.
264
264
 
265
- The shipped model policy section has a separate limit of 4,755 portable
266
- characters and 9 lines. The character limit is the measured 4,528 characters
267
- plus five percent reserve, rounded up. The line limit has no reserve.
265
+ The shipped model policy section has a limit of 5,185 portable characters and
266
+ 9 lines. The approval date is 2026-11-25. The character limit adds five percent
267
+ to the measured 4,938 characters and rounds up. The line limit has no reserve.
268
268
  A fifth default model needs a new user approval. A higher limit requires a new user
269
269
  approval.
270
270
 
@@ -557,10 +557,11 @@ this cost separately. It depends on the installation path.
557
557
 
558
558
  The user approved the limits for the other 35 rows on 2026-10-16.
559
559
  Each of those byte limits is ceil(baseline bytes * 1.05).
560
- The user approved the two limits for Research, publishing off, ordinary plan
561
- on 2026-11-12. These limits are 76,835 and 145,471 bytes.
562
- They equal the limits approved on 2026-10-16 plus 979 bytes of approved
563
- shipped model policy growth. They carry no five percent reserve.
560
+ The approved limits for Research with publishing off and an ordinary plan
561
+ are 77,245 required bytes and 145,881 conditional-maximum bytes.
562
+ The approval date is 2026-11-25. Each limit uses its 2026-11-12 approved value
563
+ plus 410 bytes of approved shipped model policy growth.
564
+ Neither limit includes a five percent reserve.
564
565
  A higher limit requires a new user approval.
565
566
  Tests enforce total <= stored literal limit.
566
567
  The token limit is ceil(byte limit / 4). Reserve is checked at approval,
@@ -569,42 +570,42 @@ reads. Any subset fits because removing ranges cannot increase union size.
569
570
 
570
571
  | Phase | Publishing | Plan | Required bytes | Estimated tokens | Byte limit | Token limit | Conditional maximum bytes | Estimated tokens | Byte limit | Token limit |
571
572
  | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
572
- | 1. Research | off | ordinary | 76439 | 19110 | 76835 | 19209 | 145422 | 36356 | 145471 | 36368 |
573
- | 1. Research | off | nested | 91724 | 22931 | 129137 | 32285 | 160707 | 40177 | 197773 | 49444 |
574
- | 1. Research | on | ordinary | 87951 | 21988 | 92700 | 23175 | 156934 | 39234 | 161336 | 40334 |
575
- | 1. Research | on | nested | 103236 | 25809 | 145981 | 36496 | 172219 | 43055 | 214617 | 53655 |
576
- | 2. Risk assessment | off | ordinary | 112832 | 28208 | 114401 | 28601 | 181815 | 45454 | 183038 | 45760 |
577
- | 2. Risk assessment | off | nested | 128117 | 32030 | 167682 | 41921 | 197100 | 49275 | 236319 | 59080 |
578
- | 2. Risk assessment | on | ordinary | 124344 | 31086 | 131245 | 32812 | 193327 | 48332 | 199882 | 49971 |
579
- | 2. Risk assessment | on | nested | 139629 | 34908 | 184526 | 46132 | 208612 | 52153 | 253163 | 63291 |
580
- | 3. Design validation | off | ordinary | 112832 | 28208 | 114401 | 28601 | 181815 | 45454 | 183038 | 45760 |
581
- | 3. Design validation | off | nested | 128117 | 32030 | 167682 | 41921 | 197100 | 49275 | 236319 | 59080 |
582
- | 3. Design validation | on | ordinary | 124344 | 31086 | 131245 | 32812 | 193327 | 48332 | 199882 | 49971 |
583
- | 3. Design validation | on | nested | 139629 | 34908 | 184526 | 46132 | 208612 | 52153 | 253163 | 63291 |
584
- | 4. Focus reconfirmation | off | ordinary | 112832 | 28208 | 114401 | 28601 | 181815 | 45454 | 183038 | 45760 |
585
- | 4. Focus reconfirmation | off | nested | 128117 | 32030 | 167682 | 41921 | 197100 | 49275 | 236319 | 59080 |
586
- | 4. Focus reconfirmation | on | ordinary | 124344 | 31086 | 131245 | 32812 | 193327 | 48332 | 199882 | 49971 |
587
- | 4. Focus reconfirmation | on | nested | 139629 | 34908 | 184526 | 46132 | 208612 | 52153 | 253163 | 63291 |
588
- | 5. Adversarial design review | off | ordinary | 135747 | 33937 | 138753 | 34689 | 232514 | 58129 | 236562 | 59141 |
589
- | 5. Adversarial design review | off | nested | 151032 | 37758 | 192034 | 48009 | 247799 | 61950 | 289844 | 72461 |
590
- | 5. Adversarial design review | on | ordinary | 147259 | 36815 | 155597 | 38900 | 244026 | 61007 | 253406 | 63352 |
591
- | 5. Adversarial design review | on | nested | 162544 | 40636 | 208878 | 52220 | 259311 | 64828 | 306688 | 76672 |
592
- | 6. Final design approval | off | ordinary | 135747 | 33937 | 138753 | 34689 | 232514 | 58129 | 236562 | 59141 |
593
- | 6. Final design approval | off | nested | 151032 | 37758 | 192034 | 48009 | 247799 | 61950 | 289844 | 72461 |
594
- | 6. Final design approval | on | ordinary | 147259 | 36815 | 155597 | 38900 | 244026 | 61007 | 253406 | 63352 |
595
- | 6. Final design approval | on | nested | 162544 | 40636 | 208878 | 52220 | 259311 | 64828 | 306688 | 76672 |
596
- | 7. Track loop | off | ordinary | 158942 | 39736 | 163384 | 40846 | 260346 | 65087 | 302924 | 75731 |
597
- | 7. Track loop | off | nested | 174227 | 43557 | 216665 | 54167 | 260346 | 65087 | 302924 | 75731 |
598
- | 7. Track loop | on | ordinary | 170454 | 42614 | 180228 | 45057 | 271858 | 67965 | 319769 | 79943 |
599
- | 7. Track loop | on | nested | 185739 | 46435 | 233509 | 58378 | 271858 | 67965 | 319769 | 79943 |
600
- | 8. Final acceptance | off | ordinary | 158942 | 39736 | 163384 | 40846 | 260346 | 65087 | 302924 | 75731 |
601
- | 8. Final acceptance | off | nested | 174227 | 43557 | 216665 | 54167 | 260346 | 65087 | 302924 | 75731 |
602
- | 8. Final acceptance | on | ordinary | 170454 | 42614 | 180228 | 45057 | 271858 | 67965 | 319769 | 79943 |
603
- | 8. Final acceptance | on | nested | 185739 | 46435 | 233509 | 58378 | 271858 | 67965 | 319769 | 79943 |
604
- | 9. Delivery | off | ordinary | 158942 | 39736 | 163384 | 40846 | 260346 | 65087 | 302924 | 75731 |
605
- | 9. Delivery | off | nested | 174227 | 43557 | 216665 | 54167 | 260346 | 65087 | 302924 | 75731 |
606
- | 9. Delivery | on | ordinary | 170454 | 42614 | 180228 | 45057 | 271858 | 67965 | 319769 | 79943 |
607
- | 9. Delivery | on | nested | 185739 | 46435 | 233509 | 58378 | 271858 | 67965 | 319769 | 79943 |
573
+ | 1. Research | off | ordinary | 76849 | 19213 | 77245 | 19312 | 145832 | 36458 | 145881 | 36471 |
574
+ | 1. Research | off | nested | 92134 | 23034 | 129137 | 32285 | 161117 | 40280 | 197773 | 49444 |
575
+ | 1. Research | on | ordinary | 88361 | 22091 | 92700 | 23175 | 157344 | 39336 | 161336 | 40334 |
576
+ | 1. Research | on | nested | 103646 | 25912 | 145981 | 36496 | 172629 | 43158 | 214617 | 53655 |
577
+ | 2. Risk assessment | off | ordinary | 113242 | 28311 | 114401 | 28601 | 182225 | 45557 | 183038 | 45760 |
578
+ | 2. Risk assessment | off | nested | 128527 | 32132 | 167682 | 41921 | 197510 | 49378 | 236319 | 59080 |
579
+ | 2. Risk assessment | on | ordinary | 124754 | 31189 | 131245 | 32812 | 193737 | 48435 | 199882 | 49971 |
580
+ | 2. Risk assessment | on | nested | 140039 | 35010 | 184526 | 46132 | 209022 | 52256 | 253163 | 63291 |
581
+ | 3. Design validation | off | ordinary | 113242 | 28311 | 114401 | 28601 | 182225 | 45557 | 183038 | 45760 |
582
+ | 3. Design validation | off | nested | 128527 | 32132 | 167682 | 41921 | 197510 | 49378 | 236319 | 59080 |
583
+ | 3. Design validation | on | ordinary | 124754 | 31189 | 131245 | 32812 | 193737 | 48435 | 199882 | 49971 |
584
+ | 3. Design validation | on | nested | 140039 | 35010 | 184526 | 46132 | 209022 | 52256 | 253163 | 63291 |
585
+ | 4. Focus reconfirmation | off | ordinary | 113242 | 28311 | 114401 | 28601 | 182225 | 45557 | 183038 | 45760 |
586
+ | 4. Focus reconfirmation | off | nested | 128527 | 32132 | 167682 | 41921 | 197510 | 49378 | 236319 | 59080 |
587
+ | 4. Focus reconfirmation | on | ordinary | 124754 | 31189 | 131245 | 32812 | 193737 | 48435 | 199882 | 49971 |
588
+ | 4. Focus reconfirmation | on | nested | 140039 | 35010 | 184526 | 46132 | 209022 | 52256 | 253163 | 63291 |
589
+ | 5. Adversarial design review | off | ordinary | 136157 | 34040 | 138753 | 34689 | 232924 | 58231 | 236562 | 59141 |
590
+ | 5. Adversarial design review | off | nested | 151442 | 37861 | 192034 | 48009 | 248209 | 62053 | 289844 | 72461 |
591
+ | 5. Adversarial design review | on | ordinary | 147669 | 36918 | 155597 | 38900 | 244436 | 61109 | 253406 | 63352 |
592
+ | 5. Adversarial design review | on | nested | 162954 | 40739 | 208878 | 52220 | 259721 | 64931 | 306688 | 76672 |
593
+ | 6. Final design approval | off | ordinary | 136157 | 34040 | 138753 | 34689 | 232924 | 58231 | 236562 | 59141 |
594
+ | 6. Final design approval | off | nested | 151442 | 37861 | 192034 | 48009 | 248209 | 62053 | 289844 | 72461 |
595
+ | 6. Final design approval | on | ordinary | 147669 | 36918 | 155597 | 38900 | 244436 | 61109 | 253406 | 63352 |
596
+ | 6. Final design approval | on | nested | 162954 | 40739 | 208878 | 52220 | 259721 | 64931 | 306688 | 76672 |
597
+ | 7. Track loop | off | ordinary | 159352 | 39838 | 163384 | 40846 | 260756 | 65189 | 302924 | 75731 |
598
+ | 7. Track loop | off | nested | 174637 | 43660 | 216665 | 54167 | 260756 | 65189 | 302924 | 75731 |
599
+ | 7. Track loop | on | ordinary | 170864 | 42716 | 180228 | 45057 | 272268 | 68067 | 319769 | 79943 |
600
+ | 7. Track loop | on | nested | 186149 | 46538 | 233509 | 58378 | 272268 | 68067 | 319769 | 79943 |
601
+ | 8. Final acceptance | off | ordinary | 159352 | 39838 | 163384 | 40846 | 260756 | 65189 | 302924 | 75731 |
602
+ | 8. Final acceptance | off | nested | 174637 | 43660 | 216665 | 54167 | 260756 | 65189 | 302924 | 75731 |
603
+ | 8. Final acceptance | on | ordinary | 170864 | 42716 | 180228 | 45057 | 272268 | 68067 | 319769 | 79943 |
604
+ | 8. Final acceptance | on | nested | 186149 | 46538 | 233509 | 58378 | 272268 | 68067 | 319769 | 79943 |
605
+ | 9. Delivery | off | ordinary | 159352 | 39838 | 163384 | 40846 | 260756 | 65189 | 302924 | 75731 |
606
+ | 9. Delivery | off | nested | 174637 | 43660 | 216665 | 54167 | 260756 | 65189 | 302924 | 75731 |
607
+ | 9. Delivery | on | ordinary | 170864 | 42716 | 180228 | 45057 | 272268 | 68067 | 319769 | 79943 |
608
+ | 9. Delivery | on | nested | 186149 | 46538 | 233509 | 58378 | 272268 | 68067 | 319769 | 79943 |
608
609
 
609
610
  Conditional sets have the following whole-document costs. Early notes cost
610
611
  zero extra after required notes enter phase 7. Unusual prose costs zero extra
@@ -98,12 +98,13 @@ Luna uses these cautions in order:
98
98
 
99
99
  1. `May treat supplied repair context as permission to implement despite explicit task limits. Restrict write access for record-only work and verify the changed files.`
100
100
  2. `Do not use Luna to handle complex texts.`
101
- 3. `May shorten long file paths in tool calls. Give the full path and require a read-back of the edited lines.`
101
+ 3. `May shorten long file paths in tool calls. Give the full path and require a read-back of the edited lines. Require one shell variable for each long path, and forbid typing the path again.`
102
102
  4. `May undo its own checked writes before it ends. Check the final file state after every record task.`
103
103
  5. `For an append outside a research log or implementer report, anchor one single-block edit on the exact current last line, then read back the tail.`
104
104
  6. `May report state outside the task scope incorrectly. Verify such a claim before acting on it.`
105
- 7. `May change apostrophe or backslash characters, or omit text, when it stages supplied text. Its own comparison with the staged file cannot detect this. Require a quoted heredoc or the file-writing tool, a stated line count and a read-back against the task text.`
105
+ 7. `May change apostrophe or backslash characters, or omit text, when it stages supplied text. Its own comparison with the staged file cannot detect this. Require a quoted heredoc or the file-writing tool, a stated line count and a read-back against the task text. May change staged text to reach a stated line count. State that equality with the task text decides, and forbid a change that only reaches a count.`
106
106
  8. `For an append with cat, name exactly one source file in the command.`
107
+ 9. `In a check command, may redirect output to the record itself. Give the check as explicit commands with a temporary target, and state that only the append may write to the record.`
107
108
 
108
109
  Sol uses these cautions in order:
109
110
 
@@ -392,11 +393,17 @@ for an unknown or ambiguous route. Main recovery stays available during handoff
392
393
  pause. An unresolved stop keeps worker dispatch paused while brief writing waits
393
394
  for the user choice.
394
395
 
395
- Pi 1.6.0 model and effort switches are session-only unless the caller explicitly
396
- requests persistence. Slate retains shared saved-default ownership and its
397
- compatibility restoration guard. The guard covers explicit persistence and
398
- hosts that persist switches. A restoration failure is visible and can leave the
399
- changed default in place.
396
+ Slate switches the main-session model during failover, handoff adoption, and
397
+ [private project model application](configuration.md#private-project-model)
398
+ at session start. Pi 1.6.0 model and effort switches are session-only unless
399
+ the caller requests persistence.
400
+
401
+ Failover and handoff adoption share an optional guard for global Pi model
402
+ defaults. The guard attempts to restore only changes that match the switch.
403
+ It warns if restoration fails. Private project model application does not use
404
+ the guard. The verification ladder covers failover and handoff adoption. A recorded
405
+ interactive run checks the private project model switch and the global Pi
406
+ settings file.
400
407
 
401
408
  ## Package reliance boundary
402
409
 
@@ -16,8 +16,8 @@
16
16
  * the model selector and an extension's pi.setModel all arrive as source "set"
17
17
  * (agent-session's setModel emits "set" unconditionally; only the cycle
18
18
  * keybinding emits "cycle", and "restore" is declared in the SDK but emitted by
19
- * no shipped code). So a switch slate is about to make is DECLARED first, and the
20
- * event matching that declaration is the one switch that does not move the base.
19
+ * no shipped code). Slate declares its switches against an active tracker.
20
+ * An event that matches the declaration does not move the base.
21
21
  *
22
22
  * DECLARATION LIFETIME — THE SETTER'S OWN DURATION, NEVER A CLOCK (BG10).
23
23
  * A declaration is IN FLIGHT from the moment it is declared until the SETTER
@@ -211,11 +211,14 @@ export interface BaseModelTracker {
211
211
  */
212
212
  expectOwnSwitch(from: string | undefined, to: string): () => void;
213
213
  /**
214
- * Run ONE slate-initiated model switch under a declaration: declares (from, to),
215
- * awaits `performSwitch`, and retires the declaration when it settles — on
216
- * success, on `false`, and on a throw alike. Returns exactly what
217
- * `performSwitch` returns and re-throws its error unchanged; the tracker itself
218
- * never throws. This is the sanctioned form at every slate switch site.
214
+ * Use this method for a Slate switch against an active tracker.
215
+ * It declares (from, to) and awaits `performSwitch`.
216
+ * It retires the declaration when the switch settles.
217
+ * It returns the switch result or rethrows the switch error unchanged.
218
+ *
219
+ * Private project model application runs before the tracker seed.
220
+ * Slate suppresses the nested `model_select` observation during application.
221
+ * Slate then seeds the tracker from the live state.
219
222
  */
220
223
  ownSwitch<T>(from: string | undefined, to: string, performSwitch: () => Promise<T>): Promise<T>;
221
224
  /** Called after a handoff adoption SUCCEEDS, to deliberately re-seed the base. */
@@ -47,6 +47,7 @@ import { registerOrchestratorFailover } from "./failover.ts";
47
47
  import { registerSlateHandoff, sanitizeContextBudget } from "./handoff.ts";
48
48
  import { createLogicalRuntime, type LogicalRuntime } from "./logical-model-runtime.ts";
49
49
  import { registerSlateMode } from "./mode.ts";
50
+ import { applyPrivateProjectModel, reportPrivateProjectModel } from "./project-model-startup.ts";
50
51
  import { registerNotificationEvents } from "./notification-events.ts";
51
52
  import { createTerminalNotificationChannels } from "./notification-terminal.ts";
52
53
  import { createPushNotificationChannel } from "./notification-push.ts";
@@ -80,18 +81,12 @@ export default function (pi: ExtensionAPI) {
80
81
  // stale manager. Starts as the empty set (feature off) until session_start.
81
82
  let resolveWorkerExtensionSet: () => WorkerExtensionSet = () => EMPTY_WORKER_EXTENSION_SET;
82
83
 
83
- // One base-model tracker per session (base-model.ts), reassigned every
84
- // session_start below so its seed and its one-report-per-condition budget are
85
- // per session. TWO consumption modes, deliberately different (CQ12): the SWITCH
86
- // SITES (failover.ts, handoff.ts) take the live `() => baseModel` indirection,
87
- // because a switch always belongs to the CURRENT session; ThreadManager instead
88
- // binds the instance BY VALUE at construction (CN20), so a manager orphaned by a
89
- // session swap keeps answering with its own session's base model rather than a
90
- // newer one's. Constructed eagerly here — before any session_start — so a
91
- // model_select arriving during startup has somewhere to land, and so even the
92
- // pre-session manager below can be given one; that pre-session instance reports
93
- // through the console, since no extension context exists yet.
84
+ // Each session gets a new base-model tracker with its own seed and warnings.
85
+ // Failover and handoff read the current tracker when they switch models.
86
+ // The initial tracker receives selections before session_start.
87
+ // It reports through the console because no extension context exists yet.
94
88
  let baseModel: BaseModelTracker = createBaseModelTracker({ warn: (msg) => console.warn(msg) });
89
+ let applyingPrivateProjectModel = false;
95
90
  let logicalRuntime: Readonly<LogicalRuntime> | undefined;
96
91
  let logicalSessionEpoch = 0;
97
92
  let compressorRetryPolicy: CompressorRetryPolicy | undefined;
@@ -124,10 +119,10 @@ export default function (pi: ExtensionAPI) {
124
119
  // tracker, and pairs each event with the thinking level pi has already clamped
125
120
  // by emission time (setModel emits AFTER its thinking cascade).
126
121
  pi.on("model_select", async (event) => {
127
- baseModel.observe(event, readLiveEffort(pi));
122
+ if (!applyingPrivateProjectModel) baseModel.observe(event, readLiveEffort(pi));
128
123
  });
129
124
 
130
- pi.on("session_start", async (_event, ctx) => {
125
+ pi.on("session_start", async (event, ctx) => {
131
126
  notifications.retire();
132
127
  // Invalidate asynchronous recovery before replacing session-owned state.
133
128
  const epoch = ++logicalSessionEpoch;
@@ -168,6 +163,18 @@ export default function (pi: ExtensionAPI) {
168
163
  // worker open or a doctrine build — after session_start finishes, so tools
169
164
  // registered during session_start are captured (AD41).
170
165
  resolveWorkerExtensionSet = createWorkerExtensionResolver(pi, () => config.workerExtensions ?? [], warn);
166
+ // The seed reads the final model and thinking level. Do not treat the
167
+ // private project model switch as a user selection during the switch.
168
+ applyingPrivateProjectModel = true;
169
+ try {
170
+ await applyPrivateProjectModel(pi, event, ctx);
171
+ } catch {
172
+ const warning = "slate: Slate could not complete private project model application. The session keeps its live model and thinking level.";
173
+ reportPrivateProjectModel(ctx, warning, "warning");
174
+ } finally {
175
+ applyingPrivateProjectModel = false;
176
+ }
177
+ if (epoch !== logicalSessionEpoch || !lifecycleRecoveryOwnership.isCurrentLifecycle()) return;
171
178
  // Fresh tracker per session, seeded from the session's OWN resolved model —
172
179
  // undefined is legitimate (no model, or no auth for one) and stays silent.
173
180
  // Same warn channel as the sanitizers above. A handoff adoption re-seeds it
@@ -95,7 +95,7 @@ const SHIPPED_DEFINITIONS: LogicalModelDefinition[] = [
95
95
  model: "luna-6", capabilityRating: 35, effort: "max", costRating: 2,
96
96
  preferredProvider: "openai", providers: providers("openai", "gpt-6-luna"),
97
97
  guidelines: ["auxiliary tasks only, such as file location, check-result collection, or routine text management such as modifying research logs", "never primary research, implementation, design, or review", "consumer-contract work only when auxiliary"],
98
- cautions: [LUNA_CAUTION, "Do not use Luna to handle complex texts.", "May shorten long file paths in tool calls. Give the full path and require a read-back of the edited lines.", "May undo its own checked writes before it ends. Check the final file state after every record task.", "For an append outside a research log or implementer report, anchor one single-block edit on the exact current last line, then read back the tail.", "May report state outside the task scope incorrectly. Verify such a claim before acting on it.", "May change apostrophe or backslash characters, or omit text, when it stages supplied text. Its own comparison with the staged file cannot detect this. Require a quoted heredoc or the file-writing tool, a stated line count and a read-back against the task text.", "For an append with cat, name exactly one source file in the command."], source: source(),
98
+ cautions: [LUNA_CAUTION, "Do not use Luna to handle complex texts.", "May shorten long file paths in tool calls. Give the full path and require a read-back of the edited lines. Require one shell variable for each long path, and forbid typing the path again.", "May undo its own checked writes before it ends. Check the final file state after every record task.", "For an append outside a research log or implementer report, anchor one single-block edit on the exact current last line, then read back the tail.", "May report state outside the task scope incorrectly. Verify such a claim before acting on it.", "May change apostrophe or backslash characters, or omit text, when it stages supplied text. Its own comparison with the staged file cannot detect this. Require a quoted heredoc or the file-writing tool, a stated line count and a read-back against the task text. May change staged text to reach a stated line count. State that equality with the task text decides, and forbid a change that only reaches a count.", "For an append with cat, name exactly one source file in the command.", "In a check command, may redirect output to the record itself. Give the check as explicit commands with a temporary target, and state that only the append may write to the record."], source: source(),
99
99
  },
100
100
  {
101
101
  model: "claude-sonnet-5.5", capabilityRating: 35, effort: "high", costRating: 25,
package/extension/mode.ts CHANGED
@@ -71,7 +71,7 @@ import {
71
71
  type WritingChecker,
72
72
  } from "./writing.ts";
73
73
  import type { WorkerExtensionSet, WorkerExtensionUnit } from "./worker-extensions.ts";
74
- import { preferencePath, readStartupSummary, renderStartupSummary, saveStartupSummary, SUMMARY_WIDGET_KEY } from "./startup-summary.ts";
74
+ import { preferencePath, readProjectModel, readStartupSummary, renderStartupSummary, saveStartupSummary, SUMMARY_WIDGET_KEY, writeProjectModel } from "./startup-summary.ts";
75
75
 
76
76
  const ORCHESTRATOR_TOOLS = ["read", "grep", "find", "ls", "thread", "threads", "episode", "slate_change"];
77
77
 
@@ -413,6 +413,7 @@ export function registerSlateMode(
413
413
  // failure and checker failure through the real turn hook.
414
414
  loadWritingChecker: () => Promise<WritingChecker> = loadWritingCheckerModule,
415
415
  saveSummary: typeof saveStartupSummary = saveStartupSummary,
416
+ writeModel: typeof writeProjectModel = writeProjectModel,
416
417
  ): void {
417
418
  let savedTools: string[] | undefined;
418
419
  let uiCtx: ExtensionContext | undefined;
@@ -613,12 +614,54 @@ export function registerSlateMode(
613
614
  });
614
615
 
615
616
  pi.registerCommand("slate", {
616
- description: "Slate orchestrator mode: on | off | summary [on | off] | handoff [focus] | resume | effective (no arg toggles)",
617
+ description: "Slate orchestrator mode: on | off | summary [on | off] | model [save | clear] | handoff [focus] | resume | effective (no arg toggles)",
617
618
  handler: async (args, ctx) => {
618
619
  uiCtx = ctx;
619
620
  const trimmed = args?.trim() ?? "";
620
621
  const [verb, ...rest] = trimmed.split(/\s+/);
621
622
  const arg = verb?.toLowerCase();
623
+ if (arg?.startsWith("model")) {
624
+ if (arg !== "model") {
625
+ warnSummary(ctx, "Usage: /slate model [save | clear].");
626
+ return;
627
+ }
628
+ const action = rest[0]?.toLowerCase();
629
+ const info = (text: string) => ctx.hasUI ? ctx.ui.notify(text, "info") : console.log(text);
630
+ if (rest.length === 0) {
631
+ const result = readProjectModel(ctx.cwd);
632
+ if (result.kind === "key-unavailable") warnSummary(ctx, `Cannot determine the project key: ${result.reason}`);
633
+ else if (result.kind === "store-unreadable") warnSummary(ctx, `Cannot read the private store for ${result.key}: ${result.reason}`);
634
+ else if (result.kind === "invalid-entry") warnSummary(ctx, `Invalid project model for ${result.key}.`);
635
+ else if (result.kind === "entry") info(`Project key: ${result.key}. Stored model: ${result.entry.model}. Thinking level: ${result.entry.thinkingLevel}.`);
636
+ else info(`Project key: ${result.key}. No stored model.`);
637
+ return;
638
+ }
639
+ if (rest.length !== 1 || (action !== "save" && action !== "clear")) {
640
+ warnSummary(ctx, "Usage: /slate model [save | clear].");
641
+ return;
642
+ }
643
+ let result;
644
+ try {
645
+ if (action === "save") {
646
+ const { model, thinkingLevel } = ctx;
647
+ if (!model) throw new Error("The main session has no current model.");
648
+ if (thinkingLevel === undefined) throw new Error("The main session has no current thinking level.");
649
+ if (model.provider.includes("/")) throw new Error("The provider name contains a slash.");
650
+ result = writeModel(ctx.cwd, { model: `${model.provider}/${model.id}`, thinkingLevel });
651
+ } else result = writeModel(ctx.cwd, undefined);
652
+ } catch (error) {
653
+ warnSummary(ctx, `Cannot ${action} the project model: ${String(error)}`);
654
+ return;
655
+ }
656
+ if (result.saved?.durabilityWarning) warnSummary(ctx, result.saved.durabilityWarning);
657
+ else if (!result.saved) info(`No stored model to clear for ${result.key}.`);
658
+ else {
659
+ const reply = `${action === "save" ? "Saved" : "Cleared"} the project model for ${result.key}.`;
660
+ try { info(reply); }
661
+ catch (error) { warnSummary(ctx, `${reply} Slate could not show the reply: ${String(error)}`); }
662
+ }
663
+ return;
664
+ }
622
665
  if (arg === "summary") {
623
666
  const choice = rest[0]?.toLowerCase();
624
667
  if (rest.length === 0) { displaySummary(ctx); return; }
@@ -0,0 +1,103 @@
1
+ import { accessSync, closeSync, constants, fstatSync, lstatSync, openSync, readlinkSync, readSync, realpathSync, statSync, type PathLike } from "node:fs";
2
+ import { dirname, isAbsolute, join, sep } from "node:path";
3
+
4
+ const POINTER_LIMIT = 1_048_576;
5
+ const HEAD_LIMIT = 255;
6
+
7
+ export function realTextPath(path: PathLike): string {
8
+ const bytes = realpathSync.native(path, { encoding: "buffer" });
9
+ const text = bytes.toString("utf8");
10
+ if (!Buffer.from(text).equals(bytes)) throw new Error(String(path) + ": real path is not valid text.");
11
+ return text;
12
+ }
13
+
14
+ function directoryPath(path: PathLike): string {
15
+ const resolved = realTextPath(path);
16
+ if (!statSync(resolved).isDirectory()) throw new Error(resolved + " is not a directory.");
17
+ return resolved;
18
+ }
19
+
20
+ function entryAt(path: string) {
21
+ try { return lstatSync(path); }
22
+ catch (error) {
23
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
24
+ return undefined;
25
+ }
26
+ }
27
+
28
+ function readPrefix(path: string, limit: number, rejectLarger: boolean): Buffer {
29
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
30
+ try {
31
+ const info = fstatSync(fd);
32
+ if (!info.isFile()) throw new Error(path + " is not a regular file.");
33
+ if (rejectLarger && info.size > limit) throw new Error(path + " exceeds " + limit + " bytes.");
34
+ const buffer = Buffer.alloc(Math.min(info.size, limit));
35
+ let length = 0;
36
+ while (length < buffer.length) {
37
+ const count = readSync(fd, buffer, length, buffer.length - length, null);
38
+ if (count === 0) break;
39
+ length += count;
40
+ }
41
+ return buffer.subarray(0, length);
42
+ } finally { closeSync(fd); }
43
+ }
44
+
45
+ function pointer(path: string, base: string, prefix = ""): string {
46
+ try {
47
+ if (!statSync(path).isFile()) throw new Error("The pointer is not a regular file.");
48
+ const content = readPrefix(path, POINTER_LIMIT, true);
49
+ let end = content.length;
50
+ while (content[end - 1] === 13 || content[end - 1] === 10) end--;
51
+ const bytes = content.subarray(prefix.length, end);
52
+ if (content.toString("latin1", 0, prefix.length) !== prefix || !bytes.length || bytes.includes(0)) {
53
+ throw new Error("Invalid pointer.");
54
+ }
55
+ const text = bytes.toString("utf8");
56
+ // Let the file system follow links before it resolves parent segments.
57
+ const parent = isAbsolute(text) ? "" : base + sep;
58
+ if (Buffer.from(text).equals(bytes)) return directoryPath(parent + text);
59
+ // Keep the original path bytes on systems that accept them.
60
+ if (process.platform === "win32") throw new Error("The pointer path is not valid text.");
61
+ return directoryPath(Buffer.concat([Buffer.from(parent), bytes]));
62
+ } catch (error) {
63
+ throw new Error(path + ": " + String(error), { cause: error });
64
+ }
65
+ }
66
+
67
+ function validHead(path: string): boolean {
68
+ const head = entryAt(path);
69
+ if (head?.isSymbolicLink()) return readlinkSync(path).startsWith("refs/");
70
+ if (!head?.isFile()) return false;
71
+ const content = readPrefix(path, HEAD_LIMIT, false).toString("latin1");
72
+ // Both detached hash formats have at least 40 hexadecimal digits.
73
+ return /^ref:[ \t\r\n\v\f]*refs\//.test(content) || /^[0-9a-fA-F]{40}/.test(content);
74
+ }
75
+
76
+ function gitDirectoryKey(dir: string): string {
77
+ const head = join(dir, "HEAD");
78
+ if (!validHead(head)) throw new Error(head + " is not a valid Git HEAD.");
79
+ const common = join(dir, "commondir");
80
+ const key = entryAt(common) ? pointer(common, dir) : dir;
81
+ accessSync(join(key, "objects"), constants.X_OK);
82
+ accessSync(join(key, "refs"), constants.X_OK);
83
+ return key;
84
+ }
85
+
86
+ export function resolveProjectKey(cwd: string): string {
87
+ // The native path of `.` keeps bytes that process.cwd() can lose.
88
+ const working = directoryPath(cwd === process.cwd() ? "." : cwd);
89
+ for (let dir = working; ; dir = dirname(dir)) {
90
+ const git = join(dir, ".git");
91
+ if (entryAt(git)) {
92
+ const entry = statSync(git);
93
+ if (entry.isFile()) return gitDirectoryKey(pointer(git, dir, "gitdir: "));
94
+ if (entry.isDirectory()) return gitDirectoryKey(directoryPath(git));
95
+ throw new Error(git + " is neither a regular file nor a directory.");
96
+ }
97
+ if (entryAt(join(dir, "HEAD")) &&
98
+ (entryAt(join(dir, "commondir")) || (entryAt(join(dir, "objects")) && entryAt(join(dir, "refs"))))) {
99
+ return gitDirectoryKey(dir);
100
+ }
101
+ if (dirname(dir) === dir) return working;
102
+ }
103
+ }
@@ -0,0 +1,100 @@
1
+ import * as piSdk from "@earendil-works/pi-coding-agent";
2
+ import type { ExtensionAPI, ExtensionContext, SessionStartEvent } from "@earendil-works/pi-coding-agent";
3
+ import { currentModelSpec } from "./base-model.ts";
4
+ import { sanitizeForNotify } from "./notify.ts";
5
+ import { readProjectModel } from "./startup-summary.ts";
6
+ import { splitModelSpec } from "./state.ts";
7
+
8
+ const readWarnings = {
9
+ "key-unavailable": "Slate cannot determine the project key.",
10
+ "store-unreadable": "Slate cannot read the private store.",
11
+ "invalid-entry": "The private project model entry is invalid.",
12
+ } as const;
13
+
14
+ export function reportPrivateProjectModel(
15
+ ctx: Pick<ExtensionContext, "hasUI" | "ui">,
16
+ message: string,
17
+ level: "warning" | "info",
18
+ ): void {
19
+ try {
20
+ if (ctx.hasUI) {
21
+ ctx.ui.notify(message, level);
22
+ return;
23
+ }
24
+ } catch {
25
+ // Send the same message to the console if the notice fails.
26
+ }
27
+ try {
28
+ if (level === "warning") console.warn(message);
29
+ else console.info(message);
30
+ } catch {
31
+ // A reporting failure must not stop session startup.
32
+ }
33
+ }
34
+
35
+ export async function applyPrivateProjectModel(
36
+ pi: Pick<ExtensionAPI, "setModel" | "getThinkingLevel" | "setThinkingLevel">,
37
+ event: SessionStartEvent,
38
+ ctx: ExtensionContext,
39
+ ): Promise<void> {
40
+ if (ctx.mode !== "tui") return;
41
+
42
+ if (event.reason === "resume" || event.reason === "fork" || event.reason === "reload") return;
43
+ const session = ctx.sessionManager;
44
+ // The file header identifies a fork child even when Pi reopens it.
45
+ if (event.reason === "startup" && session.getSessionFile() && session.getHeader()?.parentSession) return;
46
+ const entries = session.getEntries();
47
+ if (entries.some((entry) => entry?.type === "custom" && entry.customType === "slate-handoff" &&
48
+ (entry.data as { sessionId?: unknown } | null)?.sessionId === session.getSessionId())) return;
49
+ // A damaged message still counts because the session is not provably empty.
50
+ if (entries.some((entry) => entry?.type === "message" || entry?.type === "custom_message" ||
51
+ entry?.type === "compaction" || (entry?.type === "branch_summary" && entry.summary))) return;
52
+
53
+ const args = piSdk.parseArgs(process.argv.slice(2));
54
+ if (args.model) return;
55
+ const result = readProjectModel(ctx.cwd);
56
+ if (result.kind === "none") return;
57
+
58
+ const report = (message: string, level: "warning" | "info") => reportPrivateProjectModel(ctx, message, level);
59
+ const warn = (reason: string) => report(`slate: Private project model not applied. ${reason}`, "warning");
60
+ if (result.kind !== "entry") return warn(readWarnings[result.kind]);
61
+
62
+ const { model: spec, thinkingLevel } = result.entry;
63
+ const label = sanitizeForNotify(spec);
64
+ const target = splitModelSpec(spec)!; // The private store reader validates the model.
65
+ const model = ctx.model;
66
+ const previousLevel = pi.getThinkingLevel();
67
+ const requested = args.thinking ?? thinkingLevel;
68
+ const isTarget = (candidate: ExtensionContext["model"]) =>
69
+ candidate?.provider === target.provider && candidate.id === target.id;
70
+ const switchModel = !isTarget(model);
71
+ if (!switchModel && previousLevel === requested) return;
72
+
73
+ const selected = ctx.modelRegistry.find(target.provider, target.id);
74
+ if (!selected) return warn(`Pi does not know model ${label}.`);
75
+ if (!ctx.modelRegistry.hasConfiguredAuth(selected)) return warn(`No credentials are configured for ${label}.`);
76
+
77
+ const warnLiveState = (liveLevel: typeof previousLevel) => {
78
+ const liveModel = sanitizeForNotify(currentModelSpec(ctx) ?? "none");
79
+ report(`slate: Private project model switch failed. The session now uses ${liveModel} with thinking level ${liveLevel}. The requested thinking level was ${requested}.`, "warning");
80
+ };
81
+ try {
82
+ if (switchModel) {
83
+ if (!(await pi.setModel(selected))) return warn(`Pi refused to switch to ${label}.`);
84
+ if (!isTarget(ctx.model)) return warnLiveState(pi.getThinkingLevel());
85
+ }
86
+ if (pi.getThinkingLevel() !== requested) pi.setThinkingLevel(requested);
87
+ } catch {
88
+ const liveLevel = pi.getThinkingLevel();
89
+ if (ctx.model === model && liveLevel === previousLevel) {
90
+ return warn(`Pi could not apply ${label} before changing the session model or thinking level.`);
91
+ }
92
+ return warnLiveState(liveLevel);
93
+ }
94
+
95
+ const effective = pi.getThinkingLevel();
96
+ report(`slate: Applied private project model ${label} with thinking level ${effective}.`, "info");
97
+ if (effective !== requested) {
98
+ report(`slate: Requested thinking level ${requested} differs from the effective thinking level ${effective}.`, "warning");
99
+ }
100
+ }
@@ -1,7 +1,9 @@
1
- import { closeSync, fchmodSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { closeSync, fchmodSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { dirname, join } from "node:path";
4
4
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
+ import { realTextPath, resolveProjectKey } from "./project-key.ts";
6
+ import { isModelSpec, isThinkingLevel, type ThinkingLevel } from "./state.ts";
5
7
 
6
8
  export const SUMMARY_WIDGET_KEY = "slate-startup-summary";
7
9
  export function preferencePath(agentDir = getAgentDir()): string {
@@ -12,26 +14,29 @@ function jsonObject(value: unknown): value is Record<string, unknown> {
12
14
  return value !== null && typeof value === "object" && !Array.isArray(value);
13
15
  }
14
16
 
15
- function readPreferences(path: string): Record<string, unknown> {
16
- try {
17
- lstatSync(path);
18
- } catch (error) {
19
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
20
- throw new Error(`Cannot read ${path}: ${String(error)}`);
21
- }
17
+ function readPreferences(path: string): { target: string; mode?: number; data: Record<string, unknown> } {
18
+ let target: string;
19
+ let mode: number;
22
20
  let parsed: unknown;
23
21
  try {
24
- parsed = JSON.parse(readFileSync(path, "utf8"));
22
+ try { lstatSync(path); }
23
+ catch (error) {
24
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
25
+ return { target: path, data: {} };
26
+ }
27
+ target = realTextPath(path);
28
+ mode = statSync(target).mode & 0o7777;
29
+ parsed = JSON.parse(readFileSync(target, "utf8"));
25
30
  } catch (error) {
26
31
  throw new Error(`Cannot read or parse ${path}: ${String(error)}`);
27
32
  }
28
33
  if (!jsonObject(parsed)) throw new Error(`${path} must contain a JSON object.`);
29
- return parsed;
34
+ return { target, mode, data: parsed };
30
35
  }
31
36
 
32
37
  export function readStartupSummary(path = preferencePath()): { enabled: boolean; warning?: string } {
33
38
  try {
34
- const value = readPreferences(path).startupSummary;
39
+ const value = readPreferences(path).data.startupSummary;
35
40
  if (value === undefined) return { enabled: false };
36
41
  if (typeof value === "boolean") return { enabled: value };
37
42
  return { enabled: true, warning: `slate: ${path} needs a boolean startupSummary value. The summary is on.` };
@@ -42,24 +47,39 @@ export function readStartupSummary(path = preferencePath()): { enabled: boolean;
42
47
 
43
48
  export type SaveResult = { path: string; durabilityWarning?: string };
44
49
 
45
- /** The optional hook only injects a failure at a test boundary before replacement. */
46
- export function saveStartupSummary(enabled: boolean, path = preferencePath(), hooks: { beforeReplace?: () => void; syncFolder?: (folder: string) => void } = {}): SaveResult {
47
- // Read before any mutation. A malformed or unreadable old file must not be replaced.
48
- const previous = readPreferences(path);
49
- mkdirSync(dirname(path), { recursive: true });
50
- // Write through a link rather than replacing the link itself.
51
- let entry: ReturnType<typeof lstatSync> | undefined;
52
- try { entry = lstatSync(path); }
53
- catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
54
- const target = entry?.isSymbolicLink() ? realpathSync(path) : path;
55
- let mode: number | undefined;
56
- try { mode = statSync(target).mode & 0o7777; }
57
- catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
50
+ type WriteHooks = { beforeReplace?: () => void; syncFolder?: (folder: string) => void };
51
+
52
+ export function saveStartupSummary(enabled: boolean, path = preferencePath(), hooks: WriteHooks = {}): SaveResult {
53
+ return updatePreferences(path, "Startup summary", (data) => {
54
+ data.startupSummary = enabled;
55
+ return true;
56
+ }, hooks)!;
57
+ }
58
+
59
+ function checkStoreParent(folder: string): void {
60
+ for (;;) {
61
+ try {
62
+ realTextPath(folder);
63
+ return;
64
+ } catch (error) {
65
+ const parent = dirname(folder);
66
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || parent === folder) throw error;
67
+ folder = parent;
68
+ }
69
+ }
70
+ }
71
+
72
+ function updatePreferences(path: string, label: string, update: (data: Record<string, unknown>) => boolean, hooks: WriteHooks): SaveResult | undefined {
73
+ const { target, mode, data } = readPreferences(path);
74
+ if (!update(data)) return undefined;
75
+ if (mode === undefined) checkStoreParent(dirname(target));
76
+ mkdirSync(dirname(target), { recursive: true });
58
77
  const temp = join(dirname(target), `.slate-preferences-${randomUUID()}.tmp`);
78
+ // The temporary file must not expose store content to more readers than the target.
79
+ const fd = openSync(temp, "wx", mode ?? 0o666);
59
80
  try {
60
- const fd = openSync(temp, "wx", 0o666);
61
81
  try {
62
- writeFileSync(fd, `${JSON.stringify({ ...previous, startupSummary: enabled }, null, 2)}\n`);
82
+ writeFileSync(fd, `${JSON.stringify(data, null, 2)}\n`);
63
83
  if (mode !== undefined) fchmodSync(fd, mode);
64
84
  fsyncSync(fd);
65
85
  } finally { closeSync(fd); }
@@ -79,7 +99,7 @@ export function saveStartupSummary(enabled: boolean, path = preferencePath(), ho
79
99
  catch (error) {
80
100
  if (!unsupportedFolderFlush(error)) return {
81
101
  path,
82
- durabilityWarning: `Startup summary is saved in ${path}, but the folder could not be flushed. The choice may not survive a crash: ${String(error)}`,
102
+ durabilityWarning: `${label} is saved in ${path}, but the folder could not be flushed. The change may not survive a crash: ${String(error)}`,
83
103
  };
84
104
  }
85
105
  return { path };
@@ -94,6 +114,56 @@ function unsupportedFolderFlush(error: unknown): boolean {
94
114
  return ["ENOTSUP", "EOPNOTSUPP", "EINVAL", "EISDIR"].includes((error as NodeJS.ErrnoException).code ?? "");
95
115
  }
96
116
 
117
+ type ProjectModel = { model: string; thinkingLevel: ThinkingLevel };
118
+ type ProjectModelRead =
119
+ | { kind: "entry"; key: string; entry: ProjectModel }
120
+ | { kind: "none"; key: string }
121
+ | { kind: "invalid-entry"; key: string }
122
+ | { kind: "store-unreadable"; key: string; reason: string }
123
+ | { kind: "key-unavailable"; reason: string };
124
+
125
+ function projectModels(data: Record<string, unknown>): Record<string, unknown> {
126
+ if (data.projectModels === undefined) return {};
127
+ if (!jsonObject(data.projectModels)) throw new Error("projectModels must be a JSON object.");
128
+ return data.projectModels;
129
+ }
130
+
131
+ function validProjectModel(value: unknown): value is ProjectModel {
132
+ return jsonObject(value) && isModelSpec(value.model) && isThinkingLevel(value.thinkingLevel);
133
+ }
134
+
135
+ export function readProjectModel(cwd: string, path = preferencePath()): ProjectModelRead {
136
+ let key;
137
+ try { key = resolveProjectKey(cwd); }
138
+ catch (error) { return { kind: "key-unavailable", reason: String(error) }; }
139
+ try {
140
+ const entries = projectModels(readPreferences(path).data);
141
+ if (!Object.hasOwn(entries, key)) return { kind: "none", key };
142
+ const entry = entries[key];
143
+ return validProjectModel(entry) ? { kind: "entry", key, entry } : { kind: "invalid-entry", key };
144
+ } catch (error) {
145
+ return { kind: "store-unreadable", key, reason: String(error) };
146
+ }
147
+ }
148
+
149
+ export function writeProjectModel(cwd: string, entry: ProjectModel | undefined, path = preferencePath(), hooks: WriteHooks = {}) {
150
+ let key;
151
+ try { key = resolveProjectKey(cwd); }
152
+ catch (error) { throw new Error(`Cannot determine the project key: ${String(error)}`); }
153
+ const saved = updatePreferences(path, "Project model change", (data) => {
154
+ const entries = projectModels(data);
155
+ if (entry !== undefined) {
156
+ if (!validProjectModel(entry)) throw new Error("A provider/id model and a valid thinking level are required.");
157
+ data.projectModels = { ...entries, [key]: entry };
158
+ } else {
159
+ if (!Object.hasOwn(entries, key)) return false;
160
+ delete entries[key];
161
+ }
162
+ return true;
163
+ }, hooks);
164
+ return { key, saved };
165
+ }
166
+
97
167
  type SummaryStyleKind = "heading" | "action" | "command" | "dim";
98
168
  type SummaryStyle = (kind: SummaryStyleKind, text: string) => string;
99
169
  type SummaryPart = [text: string, kind?: SummaryStyleKind];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ytdb-slate",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Design-first feature development for the pi coding agent. Slate researches, designs, implements and reviews each change. You judge the design and keep control of the code without reading every line.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {