@rt-tools/agent-kit 0.28.0 → 0.29.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.
Files changed (55) hide show
  1. package/assets/checks/board-epic-link.github.mjs +13 -1
  2. package/assets/checks/board-runs.github.mjs +102 -2
  3. package/assets/checks/check-board.github.mjs +63 -3
  4. package/assets/checks/main-run.github.mjs +69 -0
  5. package/assets/checks/rt-kit-checks.config.mjs +15 -0
  6. package/assets/checks/tree-assignment.mjs +169 -0
  7. package/assets/hooks/end-conversation-guard.sh +59 -0
  8. package/assets/hooks/epic-over.sh +11 -2
  9. package/assets/hooks/git-guard-delivery-epic.sh +7 -0
  10. package/assets/hooks/git-guard-delivery.sh +2 -1
  11. package/assets/hooks/git-guard-tree-assignment.sh +77 -0
  12. package/assets/hooks/hook-input.sh +8 -1
  13. package/assets/hooks/main-run-context.sh +45 -0
  14. package/assets/hooks/tree-assignment-guard.sh +101 -0
  15. package/assets/hooks/turn-exit-epic.sh +110 -0
  16. package/assets/hooks/turn-exit-guard.sh +34 -20
  17. package/assets/hooks/turn-exit-patterns.sh +0 -9
  18. package/assets/hooks/turn-exit-verdict.sh +20 -8
  19. package/assets/laws/delivery.md +6 -0
  20. package/assets/laws/work-conduct.md +4 -0
  21. package/assets/patterns/git-workflow-merge.md +13 -0
  22. package/assets/patterns/git-workflow-pr-body.github.md +156 -0
  23. package/assets/patterns/git-workflow-pr.github.md +6 -104
  24. package/assets/patterns/git-workflow-stack.md +19 -2
  25. package/assets/patterns/task-flow-close.md +1 -1
  26. package/assets/patterns/task-flow-resume.md +8 -0
  27. package/assets/pitfalls/git-workflow.github.md +6 -0
  28. package/assets/pitfalls/turn-conduct.md +18 -0
  29. package/assets/rules/doc-style.md +3 -2
  30. package/assets/rules/git-workflow.github.md +35 -37
  31. package/assets/rules/task-flow.md +33 -33
  32. package/assets/rules/turn-conduct.md +31 -32
  33. package/assets/samples/tasks/_template/progress.md +1 -1
  34. package/bin/agent-kit.d.ts.map +1 -1
  35. package/bin/agent-kit.js +2 -1
  36. package/bin/agent-kit.js.map +1 -1
  37. package/lib/cargo.d.ts +49 -1
  38. package/lib/cargo.d.ts.map +1 -1
  39. package/lib/cargo.js +9 -2
  40. package/lib/cargo.js.map +1 -1
  41. package/lib/observations-cargo.d.ts +20 -0
  42. package/lib/observations-cargo.d.ts.map +1 -0
  43. package/lib/observations-cargo.js +88 -0
  44. package/lib/observations-cargo.js.map +1 -0
  45. package/lib/shipment.d.ts +8 -20
  46. package/lib/shipment.d.ts.map +1 -1
  47. package/lib/shipment.js +22 -39
  48. package/lib/shipment.js.map +1 -1
  49. package/lib/tree-mark.d.ts +17 -0
  50. package/lib/tree-mark.d.ts.map +1 -0
  51. package/lib/tree-mark.js +41 -0
  52. package/lib/tree-mark.js.map +1 -0
  53. package/package.json +1 -1
  54. package/rt-tools-agent-kit-0.29.0.tgz +0 -0
  55. package/rt-tools-agent-kit-0.28.0.tgz +0 -0
@@ -16,7 +16,7 @@ with a guard does.
16
16
 
17
17
  **Requires:** `hooks/task-flow-guard.sh`, `hooks/task-flow-draft-guard.sh`,
18
18
  `hooks/task-context-load.sh`, `hooks/grill-gate.sh`, `hooks/window-fill-guard.sh`,
19
- `hooks/turn-exit-guard.sh`, `hooks/work-start-guard.sh`
19
+ `hooks/turn-exit-guard.sh`, `hooks/work-start-guard.sh`, `hooks/main-run-context.sh`
20
20
 
21
21
  ## What it is called here
22
22
 
@@ -51,7 +51,7 @@ The state is declared in the "Where we stand" section of the progress by the mac
51
51
  | State | Entry | Mandatory action | Pattern |
52
52
  | --- | --- | --- | --- |
53
53
  | `просьба-не-разобрана` | the owner's message about new work | exploration over the tree, then questions | `task-flow-start` |
54
- | `эпик-заведён` | the epic card, all its tasks and its plan lie in the queue | take the epic branch from the main branch | `task-flow-start` |
54
+ | `эпик-заведён` | the epic card, all its tasks and its plan lie in the queue | take the epic branch from the main branch; with the first task the epic card moves to in progress | `task-flow-start` |
55
55
  | `разбор-закрыт` | the owner's answers lie on disk | a product agreement, or the reason there is none | `task-flow-start` |
56
56
  | `договорённость-записана` | the draft lies, or the reason is named | create the task, the branch from the epic branch, and the folder | `task-flow-start` |
57
57
  | `задача-взята` | task in the work column, branch by number, folder | write the plan | `task-flow-start` |
@@ -72,8 +72,7 @@ output, not by the executor's memory. A filled session window is no state either
72
72
  with a handover, and the work stays where it stood. **An open card says nothing about whether the
73
73
  work is taken.** A card is closed by the merge, and in a session that opens no PRs the list of open
74
74
  ones does not shrink. A task is untaken when the tree holds no trace of it: open numbers are checked
75
- against the archive — closed work has a record there with its number. The audit costs one command
76
- and answers for both sides; the open list answers for neither.
75
+ against the archive — closed work has a record there with its number.
77
76
 
78
77
  What a turn ends with — rule `turn-conduct` under the same law.
79
78
 
@@ -98,7 +97,7 @@ flowchart TD
98
97
  E --> Z{The epic of this work exists}
99
98
  F --> Z
100
99
  Z -->|No| Y[The epic is declared: a card, all its tasks and a plan — then its branch from the main branch]
101
- Z -->|Yes| G[Task, branch from the epic branch, task folder by branch name]
100
+ Z -->|Yes| G[Task, branch from the epic branch, task folder by branch name; the epic card moves with its first task]
102
101
  Y --> G
103
102
  G --> H[A plan with stages; not edited after it is written]
104
103
  H --> I{Stage done}
@@ -147,13 +146,16 @@ flowchart TD
147
146
  - **A reply to the owner's order begins with the result, not with intent or its justification.** A
148
147
  justification under someone else's accepted decision reads as its appraisal. One exception:
149
148
  execution stopped by an obstacle — then the obstacle is named.
149
+ - **The last run of the main branch is read first thing in a session and after every known
150
+ merge.** A merge reads as the end of the work, and a red main branch after it lives until the
151
+ owner notices. The start hook prints it; after a merge the command is called by hand, and a red
152
+ or pushed-out run is fixed before new work is taken.
150
153
  - **A session does not start work by itself.** A start needs the owner's word in the same session:
151
154
  the handover, the state from the startup hook and an assigned epic say what to do, not whether to
152
- work. The form of the message is judged: an empty message, one word or one path order no work.
155
+ work. An empty message, one word or one path order no work.
153
156
  - **A refusal by an external limiter removes the way, not the task.** It is not the tree's guard and
154
- names no exit: read as the end of the road, it stops the work whole. The way is taken from the
155
- guard that already described this fix — a bypass with the reason in the commit body, a mark in the
156
- observations, a word to the owner — and the task stays the same.
157
+ names no exit. The way is taken from the guard that already described this fix — a bypass with
158
+ the reason in the commit body, a word to the owner — and the task stays the same.
157
159
  - **An instruction to work by the progress covers all its steps, including those that change
158
160
  history.** Questions are asked about what the progress lacks.
159
161
  - **A question written by a past session does not become a question to the owner.** It is addressed
@@ -169,14 +171,13 @@ flowchart TD
169
171
  - **A task folder is created for any work, no exceptions.** An exception with even one lawful form
170
172
  is executed as permission. It goes in before the first edit.
171
173
  - **The task folder goes into the branch by a commit, not lives in one working tree.** Uncommitted,
172
- it passes edits without refusal, and the refusal comes at the end, when the plan is already gone.
173
- Outside history one draft without a number is lawful.
174
+ it passes edits without refusal until the plan is already gone. Outside history one draft without
175
+ a number is lawful.
174
176
  - **The task folder is taken apart by the last commit before the PR opens, not after approval.** A
175
177
  person merges as soon as they see green, and no room is left for a closing commit.
176
178
  - **After opening the PR, the executor tells the owner the number, what it waits for and what comes
177
- next.** A draft waits for the run, and next it is lifted: a green run says nothing is broken and
178
- nothing about the locked merge button. A PR opened ready waits for the owner's hand, and that is
179
- said in the same words.
179
+ next.** A draft waits for the run and is lifted after it; a PR opened ready waits for the owner's
180
+ hand, and that is said in the same words.
180
181
  - **A request to merge never comes before the work is checked.** Where the pipeline wakes for this
181
182
  base: folder taken apart and pushed → PR as a draft → run green → draft lifted → the request to
182
183
  merge, naming the number. Where it does not wake, the green push gate is the check, and opening
@@ -197,36 +198,38 @@ flowchart TD
197
198
  is narrowed to what the stages give.
198
199
  - **A stage's readiness sign is taken from the output of a command run while the plan is written.**
199
200
  Written by a guess, it is checked at the stage itself — latest of everything that depended on it.
200
- Some lines come not from the work but from an unconfigured tree, and no stage puts them out.
201
201
  - **A plan for work that ports a technique from outside is written by a measurement of one's own
202
- code.** Reading the sample says how the sample is built; what of it is needed here is said by a
203
- count over one's own files.
202
+ code.** Reading the sample says how it is built; what is needed here is said by a count over
203
+ one's own files.
204
204
  - **Waiting for one part of a stage is never a stop of the stage.** The parts independent of what is
205
205
  awaited are done in the same turn; the owner is told what is done and what is left for their step.
206
- A refused command reads the same: everything else is done first.
207
206
  - **A finding made mid-stage is checked against the plan's exit conditions before the first edit.**
208
- Nearness of subject proves no belonging. A finding named by no exit condition goes to the section
209
- on what the work does not do, and is filed as a task.
207
+ A finding named by no exit condition goes to the section on what the work does not do, and is
208
+ filed as a task.
210
209
  - **Done work is marked only in the progress.** "Where we stand" is rewritten by every session, not
211
210
  appended: it is the first thing the next session reads.
212
- - **A word for a new notion is looked up in the tree's glossary.** The package carries the common
213
- part, the tree appends the subject part by an override; the glossary goes into the context whole
211
+ - **A word for a new notion is looked up in the tree's glossary.** It goes into the context whole
214
212
  at session start, so "did not read it" is never a ground.
215
213
  - **The task folder is created as a draft and gets its number by a command.** Until the grill ends,
216
- how many tasks come out is unknown, so the number never comes first. The command renames the
217
- draft, fills the plan header and strips the layout header from the copies.
214
+ how many tasks come out is unknown, so the number never comes first.
218
215
  - **An abandoned grill is visible.** A draft older than a week is listed by the work queue audit.
219
216
  - **Work ordered in words becomes a task in the queue in the same turn.** Even if it will not be
220
- done now. A draft folder is not the queue: it has no number, and one session knows of it.
221
- Postponed work names a date; postponed silently, it reads as done.
217
+ done now: a draft folder has no number, and one session knows of it. Postponed work names a
218
+ date; postponed silently, it reads as done.
222
219
  - **Work begins with the epic, and a task outside one is not taken.** The epic names what the whole
223
220
  is, and the main branch takes that whole or does not take it. Work outside an epic exists only by
224
221
  the owner's word about that work, said about that work.
225
222
  - **The epic branch is taken before the first task of the epic, not with it.** Taken later, it
226
223
  leaves the first task standing on the main branch, and the epic starts as half of itself already
227
224
  merged.
225
+ - **The epic card moves to in progress by the same turn that takes its first task.** The owner
226
+ follows the epic by one card, and one left where the epic was declared reads as never started.
227
+ Nothing checks this yet: the rule `git-workflow` holds the move command and names the gap.
228
228
  - **The next task is taken from the epic plan, and the queue list is asked only where there is no
229
229
  epic.** By a list of numbers someone else's epic cannot be told from one's own.
230
+ - **Which epic this working copy leads is read from the table of assignments, and the owner writes
231
+ it.** A card of the queue is not an order; a guard refuses every call that takes work until
232
+ their word.
230
233
  - **An epic is not closed by a sign confirmed by reading alone.** What is checkable by eye is
231
234
  called checked only with a command and its output.
232
235
  - **The tasks of an epic are created all at once, by the same turn as the epic itself.** Creating
@@ -243,19 +246,16 @@ flowchart TD
243
246
  for good. Until then the epic branch is not offered to a person at all — the merge button on it
244
247
  means the whole epic.
245
248
  - **The epic plan lies where it is found without the network and after the merge.** The card does
246
- not hold the task order, and the task folder would hold it only until the first merge; the
247
- directory — in the rule's companion. What the owner names along the way is appended there by the
248
- turn that accepted it.
249
- - **Building by a sample begins with reading the sample itself.** The repeated part is opened whole,
250
- by walking the directories.
249
+ not hold the task order, and the task folder dies with the merge; the directory — in the rule's
250
+ companion. What the owner names along the way is appended there by the turn that accepted it.
251
+ - **Building by a sample begins with reading the sample itself, whole, by walking the directories.**
251
252
  - **What acts on the tree, not on the edit, lies outside the index.** The path to the sample and the
252
253
  permission to work outside the epic do not belong to the branch and live next to the handover. A
253
254
  number in the permitted list repeats the owner's word, not replaces it.
254
255
  - **Closed work is reviewed by the rules as a closing step, not as a separate request.** What was
255
256
  loaded and what was missing is seen only by the session that led the work.
256
257
  - **The review of closed work goes to the background, and the executor takes the next task.** The
257
- role works in a turn of its own; the digest is gathered before the launch, the findings are
258
- accepted in one turn.
258
+ digest is gathered before the launch, the findings are accepted in one turn.
259
259
  - **The review's findings wait for the owner, and only the digest of observations leaves for the
260
260
  package.** A proposal sent unreviewed becomes the work of someone who did not order it. The digest
261
261
  is always sent: it says what was used and is never an opinion.
@@ -30,21 +30,18 @@ demand, not with the rule.
30
30
  A turn ends in four ways and no others: a question to the owner the rules do not answer **and no
31
31
  task in the work queue that can be taken without waiting for the answer**; a guard's refusal; a
32
32
  filled window where there is no compaction; work handed in, with the next begun. What confirms
33
- each, the turn map lists where the tree laid it out.
33
+ each, the turn map lists where the tree laid it out. While an epic has an unfinished task, a turn
34
+ ends by these four alone.
34
35
 
35
- The queue is asked by a command in the same turn, and its output stands in the turn itself: "there
36
- are no tasks" is a statement about the tree, and the executor's memory does not confirm it. A turn
37
- where the owner's answer holds one piece of work while an independent one lies next to it ends
38
- with the work taken, and the question goes in a line beside it. The price is measured not in turns
39
- but in days: a session stood a night and a morning naming the owner one and the same step while
40
- three independent tasks lay untaken.
36
+ The queue is asked by a command in the same turn: "there are no tasks" is a statement about the
37
+ tree, and the executor's memory does not confirm it. A turn where the owner's answer holds one
38
+ piece of work while an independent one lies next to it ends with the work taken, and the question
39
+ goes in a line beside it.
41
40
 
42
41
  Everything else is the turn going on, not its end. A milestone does not end a turn: not a commit,
43
42
  not a read agreement, not the boundary "read — now editing", not a green check.
44
- A transition from state to state — least of all: the mandatory action is done, and the next is
45
- done in the same turn; a state boundary looks like a finished piece better than any milestone, and
46
- the report lands exactly
47
- where the next action should have stood.
43
+ A transition from state to state — least of all: the next mandatory action is done in the same
44
+ turn, and a state boundary looks like a finished piece better than any milestone.
48
45
 
49
46
  Four ways to end a turn look like work and are not: a summary of someone else's step, a menu under
50
47
  an assigned order, a declaration of intent, and a command named but not run.
@@ -153,17 +150,14 @@ flowchart TD
153
150
  the tree does not end here either.
154
151
  - **A taken task is not yet begun work, and the turn does not end on it.** Creating the branch,
155
152
  moving the column and naming the number are preparation: the mandatory action of `задача-взята` is
156
- not done by a single line, yet the turn holds much work, and the sign "was there work" releases
157
- it. The guard has a tier for this; a branch without a task number is not under it, an assembled
158
- folder template lifts it.
153
+ not done by a single line. An epic branch, named by the header of its plan, carries no folder by
154
+ the rule and is not judged so.
159
155
  - **Exploration does not end a turn, however much of it there is.** Switching branch, pulling,
160
156
  browsing history and reading PRs are preparation, not work; a turn of these alone leaves the work
161
- where it stood. It looks like work better than anything else: commands, exact numbers, checkable
162
- answers. Parts of a compound command are judged one by one: a read joined to an edit remains work.
157
+ where it stood. Parts of a compound command are judged one by one: a read joined to an edit
158
+ remains work.
163
159
  - **A reply to the owner is not an action and does not stand last in a turn.** The order inside a
164
- turn is one: work, the first step of the next, then text. The reverse — work, report, end — stands
165
- behind every analysed stop: a report is a form of completeness, and an appended summary reads as
166
- the turn's end the more convincingly the more was done. Saying what was done is always allowed;
160
+ turn is one: work, the first step of the next, then text. Saying what was done is always allowed;
167
161
  its place is after the next action, not instead.
168
162
  - **The last action of a turn is only ever work.** One sign for every kind of stop: a file edit or a
169
163
  changing command — last among what the turn did. The guard's tiers — exploration, waiting, handing
@@ -183,13 +177,25 @@ flowchart TD
183
177
  checked.
184
178
  - **The end of an epic is a stop, and it is the one lawful waiting for a word.** Every task of the
185
179
  epic is merged or handed over, so there is no next task to take: a guard refuses taking one, and
186
- the two guards that judge the end of a turn let the stop through by the same reading. The turn
187
- shows the table of the epic's tasks, says what was done on each and what confirms it, and says
188
- outright that the session waits for orders.
180
+ both guards of the turn end let the stop through by one reading of the epic table. The turn shows
181
+ the table of the epic's tasks, what was done on each and what confirms it, and says that the
182
+ session waits for orders. On the main branch the epic is not read, and the turn is judged as before.
189
183
  <!-- rt-when: ответ владельцу о состоянии работы -->
190
184
 
191
185
  - **The word about a stop the guard reads from the owner, not from the executor.** Otherwise the
192
186
  stop is declared by whoever finds it convenient, and the ban holds until the first inconvenience.
187
+ - **Until the epic is closed a turn ends only by one of the four exits.** A turn that ended with
188
+ work is a stop all the same, and so is a second pass over the same turn: the exit guard judges
189
+ both by the epic and returns the turn with the next step named. The end of the epic is the fifth.
190
+ - **The owner's standing word about a stop is quoted in the progress, in « », in the line «Waiting
191
+ for the owner».** The guard reads their word, not a retelling: a line without a quote releases
192
+ nothing, and a quote holds until the owner cancels it. A word said in this turn releases by itself.
193
+ - **The session is ended by the owner and by nobody else.** The tool that closes the conversation is
194
+ refused by a guard always, with no lawful form of bypass: an assignment stands until the owner
195
+ cancels it, and a session that must close is closed by them.
196
+ - **A refusal of a guard ends the turn only as its last action, and only a refusal of work.** A
197
+ refusal answered by the next call is the middle of the turn. A refused stop — the closing tool —
198
+ is no exit: the refused call was itself the stop, and the exit guard leaves it out.
193
199
  - **The phrase "waiting for your word" is a stop declared by the executor, and the guard refuses it
194
200
  by name.** Without the owner's word about a stop in the turn and without a question put to them by
195
201
  the tool, waiting for their word is a report, not work; the instruction holds until they cancel
@@ -197,8 +203,7 @@ flowchart TD
197
203
  - **A statement about the tree's state is watched by the statement guard, not by the executor's
198
204
  memory.** Everything the reply says about the tree carries a command and its output; said without
199
205
  one, it is no statement — not "checked", not "cleared", not "done". The guard reads the turn's
200
- text to the owner and looks for a command of the same turn; each word has its own kind of command,
201
- since a general sign "there was a command" would confirm one thing by another. The previous turn
206
+ text to the owner and looks for a command of the same turn; each word has its own kind of command. The previous turn
202
207
  does not count: the tree's state changes, and yesterday's output says nothing of today's.
203
208
  - **The statement guard waits for the reply text rather than judging the record as it found it.**
204
209
  The text lands in the turn record no earlier than the host calls the hook. Not having waited, the
@@ -230,10 +235,7 @@ flowchart TD
230
235
  notification is for where every event is acted on; where the outcome matters — one wait.
231
236
  - **A guard's refusal ends the turn.** No other road to the refused edit is sought: not a shell
232
237
  command, not a neighbouring tool, not an edit of the guard itself. The edit is done once the
233
- refusal's condition is met, or not at all — then the owner is told the refusal, not a result. A
234
- bypass costs more than a refusal: a guard refuses one file, a bypassed guard lifts the requirement
235
- from the whole tree and says nothing. Not memory alone holds this — the guards also judge the
236
- shell command that writes the file.
238
+ refusal's condition is met, or not at all — then the owner is told the refusal, not a result.
237
239
  - **A command refused by a gate is repeated whole, not by its tail.** A gate refuses the call before
238
240
  it runs, so none of its links worked — those before the refused one included. A repeated tail does
239
241
  work where it was not expected:
@@ -247,10 +249,7 @@ flowchart TD
247
249
  "What the rules already say".
248
250
  - **The owner's answer is sought in their own messages before the rules.** The law says a question
249
251
  with a written answer is not put to the owner, and the most reachable record lies not in the tree
250
- but in the conversation: the owner's first message and their answers to past rounds. The
251
- conversation guard does not see this: it counts loading a rule and searching it as reading, and a
252
- message leaves no trace. A question that answers itself in the owner's words devalues those asked
253
- next to it.
252
+ but in the conversation: the owner's first message and their answers to past rounds.
254
253
  - **The size of work is never a reason to cut its boundaries.** The owner who named the result did
255
254
  not dispute the size: an offer to drop a part is a request to reassign the goal, served as a
256
255
  clarification. What is costly is done at cost, or called costly outright, with the price named.
@@ -9,7 +9,7 @@ Rewritten by every session, not appended to.
9
9
  - **Done:** <briefly>
10
10
  - **Next step:** <what is done first in the new session>
11
11
  - **Uncommitted:** <what lies in the tree outside the index>
12
- - **Waiting for the owner:** <what exactly, or "no">
12
+ - **Waiting for the owner:** <what exactly, or "no"; the owner's standing word about a stop is quoted in « »>
13
13
  - **PR:** <number and state, or "not open yet">
14
14
 
15
15
  ## Decisions along the way
@@ -1 +1 @@
1
- {"version":3,"file":"agent-kit.d.ts","sourceRoot":"","sources":["../../../projects/agent-kit/src/bin/agent-kit.ts"],"names":[],"mappings":";AAeA,OAAO,EAAqC,iBAAiB,EAAqB,MAAM,oBAAoB,CAAC;AA+W7G,wBAAsB,IAAI,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAU9E"}
1
+ {"version":3,"file":"agent-kit.d.ts","sourceRoot":"","sources":["../../../projects/agent-kit/src/bin/agent-kit.ts"],"names":[],"mappings":";AAeA,OAAO,EAAqC,iBAAiB,EAAqB,MAAM,oBAAoB,CAAC;AAgX7G,wBAAsB,IAAI,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAU9E"}
package/bin/agent-kit.js CHANGED
@@ -18,7 +18,8 @@ import { costLines, costOf, CostUnavailableError } from '../lib/cost.js';
18
18
  import { enroll, httpEnroll } from '../lib/enroll.js';
19
19
  import { httpReadOwn, httpShip } from '../lib/ship.js';
20
20
  import { fate } from '../lib/fate.js';
21
- import { propose, treeSlugOf } from '../lib/shipment.js';
21
+ import { propose } from '../lib/shipment.js';
22
+ import { treeSlugOf } from '../lib/tree-mark.js';
22
23
  import { DEFAULT_DAYS } from '../lib/observations.js';
23
24
  import { staleBuild } from '../lib/freshness.js';
24
25
  import { packageRootFrom } from '../lib/package-root.js';
@@ -1 +1 @@
1
- {"version":3,"file":"agent-kit.js","sourceRoot":"","sources":["../../../projects/agent-kit/src/bin/agent-kit.ts"],"names":[],"mappings":";AACA;;;;;GAKG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAmB,WAAW,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,KAAK,EAAE,MAAM,EAAgB,IAAI,EAAqB,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC7G,OAAO,EAAE,WAAW,EAAW,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,oBAAoB,EAAS,MAAM,gBAAgB,CAAC;AAChF,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,eAAe,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AAI,CAAC,GAAG,EAAE,CAAC;QACP,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,wBAAwB,OAAO,GAAG,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;IAClH,CAAC;IAED,OAAO,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED,MAAM,OAAO,GAAsB,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AACrE,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;IAC/B,sCAAsC;IACtC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACtB,CAAC;AACD,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * Точка входа. Разбирает аргументы, добывает выбор проекта, зовёт команду и печатает то, что\n * она вернула. Своей работы у неё нет: всё, что решает, живёт в `commands.ts` и проверяется\n * спеками — кроме одного, чего команде знать не по чину: откуда взялся выбор законов. У строки\n * запуска это флаг, у терминала — вопрос, у прогона без терминала нет ни того ни другого.\n */\nimport { execFileSync } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport process from 'node:process';\n\nimport { unknownFlagsIn } from '../lib/argv.js';\nimport { IEntryOfCatalog, readCatalog, resolveSelection } from '../lib/catalog.js';\nimport { adopt, doctor, IEnvironment, init, IOutcomeOfCommand, list, stats, sync } from '../lib/commands.js';\nimport { CONFIG_PATH, IConfig, readConfig } from '../lib/config.js';\nimport { costLines, costOf, CostUnavailableError, ICost } from '../lib/cost.js';\nimport { enroll, httpEnroll } from '../lib/enroll.js';\nimport { httpReadOwn, httpShip } from '../lib/ship.js';\nimport { fate } from '../lib/fate.js';\nimport { propose, treeSlugOf } from '../lib/shipment.js';\nimport { DEFAULT_DAYS } from '../lib/observations.js';\nimport { staleBuild } from '../lib/freshness.js';\nimport { packageRootFrom } from '../lib/package-root.js';\nimport { IChoice } from '../lib/picker.js';\nimport { IAxis, IOptionOfAxis, readAxes } from '../lib/variants.js';\nimport { ask, askOne, canAsk } from './prompt.js';\n\nconst USAGE: readonly string[] = [\n 'agent-kit <команда>',\n '',\n ' init завести .claude/rt-kit.json и каталог надстроек',\n ' list что везёт пакет и что из этого взято здесь',\n ' sync разложить ресурсы пакета в дерево проекта',\n ' sync --check ничего не писать, отказать при расхождении — для гейта пуша',\n ' doctor рассказать о состоянии раскладки, ничего не меняя',\n ' cost посчитать цену контекста: вход в работу, одно правило, весь слой',\n ' cost --rule <имя> какое правило взвесить; без довода берётся самое тяжёлое',\n ' cost --json то же машиночитаемо — этим числа кладут в замысел',\n ' stats свести наблюдения: чем пользовались, чем ни разу, обо что спотыкались',\n ' stats --days N за сколько дней; без довода — за три',\n ' stats --json то же машиночитаемо — этим сводку прикладывают к предложению',\n ' propose отправить груз в приём: сводку со снимком надстроек, предложения и разборы',\n ' fate судьба своих записей в приёме и надстройки, которые пора снять',\n ' propose --dry-run показать, что уехало бы, и ничего не отправлять',\n ' adopt [файлы] отдать пакету файлы, лежащие на его путях не от него',\n ' enroll --code <код> завести дерево по приглашению владельца: обмен кода на токен',\n ' enroll --token <токен> завести дерево токеном, выданным в админке приёма; в сеть не идёт',\n ' enroll --force перезаписать уже лежащий токен намеренно',\n '',\n ' --root <путь> корень проекта; по умолчанию текущий каталог',\n '',\n 'Выбор законов при `init`:',\n '',\n ' --all взять все законы, ни о чём не спрашивая',\n ' --laws a,b,c взять только названные; имена — из `agent-kit list`',\n ' без обоих спросить галочками; без терминала — отказ',\n '',\n 'Вид ресурсов при `init` — там, где один закон исполняется разными командами:',\n '',\n ' --<ось> <вид> например `--host gitlab`; оси и виды — из `agent-kit list`',\n ' без флага спросить; без терминала — отказ, кроме `--all`',\n];\n\n/**\n * Доводы отправки. Довод со значением помечен `<>`: за ним идёт отдельным словом путь, и без\n * пометки этот путь читался бы как ещё один незнакомый довод.\n */\nconst PROPOSE_FLAGS: readonly string[] = ['--dry-run', '--root <>'];\n\n/** Что печатает отказ на незнакомом доводе: режимы команды, а не весь свод. */\nconst PROPOSE_USAGE: readonly string[] = [\n ' propose отправить груз в приём',\n ' propose --dry-run показать, что уехало бы, и ничего не отправлять',\n ' --root <путь> корень проекта; по умолчанию текущий каталог',\n];\n\n/**\n * Единственное место, где пакет узнаёт собственное расположение. `import.meta` живёт только\n * здесь: библиотечные модули получают каталог ресурсов входным значением, и трансформ тестов,\n * разбирающий модули как CommonJS, на них уже не спотыкается.\n */\nfunction environmentOf(root: string): IEnvironment {\n const pkg: string = packageRootFrom(dirname(fileURLToPath(import.meta.url)));\n const manifest: { name: string; version: string } = JSON.parse(readFileSync(join(pkg, 'package.json'), 'utf8')) as {\n name: string;\n version: string;\n };\n\n return {\n root,\n version: manifest.version,\n // Имя из манифеста, а не записанное здесь: по нему пакет ищет себя в зависимостях дерева,\n // и своя копия имени разошлась бы с манифестом молча — у всякого, кто пакет переименовал.\n name: manifest.name,\n assetsDir: join(pkg, 'assets'),\n // Сверка со своими исходниками возможна только отсюда: здесь пакет знает, где лежит сам.\n // У потребителя исходников рядом нет, и сверка молчит.\n stale: staleBuild(pkg, manifest.name),\n };\n}\n\n/** Вывод git в этом дереве. Отказ и пустота здесь одно и то же: адреса нет — и это не отказ. */\nfunction gitSays(root: string, args: readonly string[]): string {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path -- путь к git у каждой машины свой, и прибитый здесь сделал бы пакет непереносимым\n return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();\n } catch {\n return '';\n }\n}\n\n/** Имена удалённых репозиториев этого дерева, по одному в строке. */\nfunction remoteNames(root: string): readonly string[] {\n return gitSays(root, ['remote'])\n .split('\\n')\n .map((name: string): string => name.trim())\n .filter(Boolean);\n}\n\n/**\n * Чем это дерево себя выдаёт снаружи. Нет удалённого репозитория — нечем, и это не отказ.\n *\n * Имя `origin` — соглашение, а не устройство: рабочая копия, назвавшая свои remotes по хостам,\n * на которые смотрит, оставалась без адреса вовсе, и отправка отказывала словами «удалённого\n * репозитория нет» — при том что репозиторий у неё есть, и не один. Порядок поэтому такой:\n * `origin`, если он есть; ровно один remote — он; несколько без `origin` — адреса нет, и выбор\n * за человеком. Угадать здесь нельзя: угаданное неверно сливает в сводке приёма два дерева в\n * одно, а увидеть это нечем.\n */\nfunction remoteOf(root: string): string {\n const names: readonly string[] = remoteNames(root);\n\n if (names.includes('origin')) {\n return gitSays(root, ['remote', 'get-url', 'origin']);\n }\n\n return names.length === 1 ? gitSays(root, ['remote', 'get-url', names[0]]) : '';\n}\n\nfunction optionOf(argv: readonly string[], name: string, fallback: string): string {\n const index: number = argv.indexOf(name);\n\n return index >= 0 && argv[index + 1] ? argv[index + 1] : fallback;\n}\n\nconst isOutcome: (value: unknown) => value is IOutcomeOfCommand = (value: unknown): value is IOutcomeOfCommand =>\n typeof value === 'object' && value !== null && 'code' in value;\n\n/**\n * Выбор законов для `init`: список идентификаторов, `null` на брошенном выборе или готовый\n * отказ. Пустой список означает «взять всё», поэтому брошенный выбор отличается от него не\n * значением, а `null`: подставить «всё» вместо неотвеченного вопроса значило бы разложить\n * пятнадцать законов тому, кто как раз просил спросить.\n */\nasync function selectionFor(argv: readonly string[], assetsDir: string): Promise<readonly string[] | null | IOutcomeOfCommand> {\n if (argv.includes('--all')) {\n return [];\n }\n\n const catalog: readonly IEntryOfCatalog[] = readCatalog(assetsDir);\n const spoken: string = optionOf(argv, '--laws', '');\n\n if (spoken) {\n const named: string[] = spoken\n .split(',')\n .map((name: string): string => name.trim())\n .filter(Boolean);\n const { ids, unknown } = resolveSelection(named, 'laws', catalog);\n\n return unknown.length\n ? { code: 1, lines: [`таких законов пакет не везёт: ${unknown.join(', ')}`, 'что везёт — `agent-kit list`'] }\n : ids;\n }\n\n if (!canAsk()) {\n return {\n code: 1,\n lines: [\n 'спросить некого: запуск без терминала',\n 'назови законы флагом `--laws a,b,c` или возьми все флагом `--all`',\n 'что везёт пакет — `agent-kit list`',\n ],\n };\n }\n\n const choices: readonly IChoice[] = catalog\n .filter((entry: IEntryOfCatalog): boolean => entry.kind === 'laws')\n .map((entry: IEntryOfCatalog): IChoice => ({ id: entry.id, name: entry.name, title: entry.title }));\n\n return ask(choices, 'Какие законы разложить в этом проекте?');\n}\n\n/**\n * Виды для `init` по осям, объявленным пакетом: что взято из флага, что спрошено.\n *\n * `--all` берёт первый объявленный вид оси и **говорит об этом**: в CI спрашивать некого, а\n * отказ там означал бы, что пакет нельзя разложить без человека. Первый вид — умолчание, а не\n * догадка: порядок в объявлении оси и есть порядок предпочтения.\n */\nasync function variantOfAxis(axis: IAxis, argv: readonly string[]): Promise<string | null | IOutcomeOfCommand> {\n const spoken: string = optionOf(argv, `--${axis.name}`, '');\n const values: readonly string[] = axis.options.map((option: IOptionOfAxis): string => option.value);\n\n if (spoken) {\n return values.includes(spoken)\n ? spoken\n : {\n code: 1,\n lines: [`такого вида по оси «${axis.name}» пакет не везёт: ${spoken}`, `есть: ${values.join(', ')}`],\n };\n }\n\n if (argv.includes('--all')) {\n return axis.options[0]?.value ?? '';\n }\n\n if (!canAsk()) {\n return {\n code: 1,\n lines: ['спросить некого: запуск без терминала', `назови вид флагом \\`--${axis.name} <вид>\\`: ${values.join(', ')}`],\n };\n }\n\n return askOne(\n axis.options.map((option: IOptionOfAxis): IChoice => ({ id: option.value, name: option.value, title: option.title })),\n axis.question\n );\n}\n\nasync function variantsFor(argv: readonly string[], assetsDir: string): Promise<Record<string, string> | null | IOutcomeOfCommand> {\n const axes: readonly IAxis[] = readAxes(assetsDir);\n const chosen: Record<string, string> = {};\n\n for (const axis of axes) {\n const answer: string | null | IOutcomeOfCommand = await variantOfAxis(axis, argv);\n\n if (isOutcome(answer)) {\n return answer;\n }\n\n if (answer === null) {\n return null;\n }\n\n chosen[axis.name] = answer;\n }\n\n return chosen;\n}\n\n/** Заведение настройки: выбор ресурсов и видов, брошенный выбор ничего не пишет. */\nasync function runInit(env: IEnvironment, argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const selection: readonly string[] | null | IOutcomeOfCommand = await selectionFor(argv, env.assetsDir);\n if (isOutcome(selection)) {\n return selection;\n }\n if (selection === null) {\n return { code: 1, lines: ['выбор брошен — ничего не заведено'] };\n }\n\n const variants: Record<string, string> | null | IOutcomeOfCommand = await variantsFor(argv, env.assetsDir);\n if (isOutcome(variants)) {\n return variants;\n }\n\n return variants === null\n ? { code: 1, lines: ['выбор брошен — ничего не заведено'] }\n : init(env.root, selection, variants, env.assetsDir);\n}\n\n/**\n * Цена контекста: три веса и то, чем они сняты.\n *\n * Отказ печатается тем же выводом, а не броском: команду зовут глазами, и трассировка стека\n * говорит ей читателю меньше, чем строка о том, чего в дереве нет.\n */\nfunction runCost(env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand {\n const named: string = optionOf(argv, '--rule', '');\n let cost: ICost;\n try {\n cost = costOf(env.root, named === '' ? null : named);\n } catch (failure: unknown) {\n if (failure instanceof CostUnavailableError) {\n return { code: 1, lines: [failure.message] };\n }\n throw failure;\n }\n\n return { code: 0, lines: [...costLines(cost, argv.includes('--json'))] };\n}\n\n/** Сводка наблюдений: отрезок из флага, сегодняшний день — с края. */\nfunction runStats(env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand {\n const spoken: number = Number(optionOf(argv, '--days', ''));\n\n return stats(env, {\n days: Number.isFinite(spoken) && spoken > 0 ? Math.floor(spoken) : DEFAULT_DAYS,\n // Сегодняшний день берётся здесь: у команды своих часов нет, иначе сводку за\n // отрезок не проверить спекой — вчерашняя фикстура завтра станет позавчерашней.\n today: new Date().toISOString().slice(0, 10),\n json: argv.includes('--json'),\n });\n}\n\n/**\n * Отправка накопленного.\n *\n * Единственное действие этой команды необратимо и уходит наружу, поэтому незнакомый довод её\n * кончает, а не пропускается молча: вызов ради списка режимов отправил в приём всё накопленное, и\n * по выводу это не отличалось от «команда ничего не сделала». Прочие команды такого разбора не\n * знают — их действие обратимо.\n */\nasync function runPropose(env: IEnvironment, argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const unknown: readonly string[] = unknownFlagsIn(argv.slice(1), PROPOSE_FLAGS);\n if (unknown.length) {\n return {\n code: 1,\n lines: [`таких доводов у \\`propose\\` нет: ${unknown.join(', ')}`, '', ...PROPOSE_USAGE],\n };\n }\n\n return propose(env, {\n dryRun: argv.includes('--dry-run'),\n ship: httpShip,\n remote: remoteOf(env.root),\n // Имена доезжают до отказа: выбор за человеком, и отказ, не назвавший, из чего выбирать,\n // отправляет его смотреть то же самое своими руками.\n remotes: remoteNames(env.root),\n // Отрезок тот же, что у сводки по умолчанию: отправку зовут по свежей задаче.\n days: DEFAULT_DAYS,\n today: new Date().toISOString().slice(0, 10),\n });\n}\n\n/** Судьба своих записей: чтение приёма по токену дерева и надстройки под ними. */\nfunction runFate(env: IEnvironment): Promise<IOutcomeOfCommand> {\n return fate(env, { read: httpReadOwn });\n}\n\n/** Приписка дерева к приёмнику по коду приглашения. */\nasync function runEnroll(env: IEnvironment, argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const config: IConfig | null = readConfig(env.root);\n\n if (!config) {\n return { code: 1, lines: [`настройки дерева нет: ${CONFIG_PATH}. Заведите её командой \\`init\\``] };\n }\n\n return enroll({\n root: env.root,\n intake: config.intake,\n code: optionOf(argv, '--code', ''),\n issued: optionOf(argv, '--token', ''),\n tree: treeSlugOf(remoteOf(env.root), config.tree),\n token: config.token,\n force: argv.includes('--force'),\n call: httpEnroll,\n });\n}\n\n/** Ветка команды: окружение и доводы строки запуска на входе, вывод и код возврата на выходе. */\ntype TCommandRun = (env: IEnvironment, argv: readonly string[]) => IOutcomeOfCommand | Promise<IOutcomeOfCommand>;\n\n/** Что делает каждая команда строки запуска. Ключ — слово, которым её зовут. */\nconst COMMANDS: Readonly<Record<string, TCommandRun>> = {\n init: runInit,\n list: (env: IEnvironment): IOutcomeOfCommand => list(env),\n sync: (env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand => sync(env, argv.includes('--check')),\n cost: runCost,\n stats: runStats,\n propose: runPropose,\n fate: runFate,\n enroll: runEnroll,\n doctor: (env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand => doctor(env, optionOf(argv, '--since', '')),\n adopt: (env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand =>\n adopt(\n env,\n argv.slice(1).filter((value: string): boolean => !value.startsWith('--') && value !== optionOf(argv, '--root', ''))\n ),\n};\n\nexport async function main(argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const command: string = argv[0] ?? '';\n const env: IEnvironment = environmentOf(resolve(optionOf(argv, '--root', process.cwd())));\n const run: TCommandRun | undefined = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : undefined;\n\n if (!run) {\n return { code: command ? 1 : 0, lines: command ? [`неизвестная команда «${command}»`, '', ...USAGE] : USAGE };\n }\n\n return run(env, argv);\n}\n\nconst outcome: IOutcomeOfCommand = await main(process.argv.slice(2));\nfor (const line of outcome.lines) {\n // eslint-disable-next-line no-console\n console.log(line);\n}\nprocess.exit(outcome.code);\n"]}
1
+ {"version":3,"file":"agent-kit.js","sourceRoot":"","sources":["../../../projects/agent-kit/src/bin/agent-kit.ts"],"names":[],"mappings":";AACA;;;;;GAKG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,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KAAK,EAAE,CAAC;IAC/B,sCAAsC;IACtC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACtB,CAAC;AACD,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * Точка входа. Разбирает аргументы, добывает выбор проекта, зовёт команду и печатает то, что\n * она вернула. Своей работы у неё нет: всё, что решает, живёт в `commands.ts` и проверяется\n * спеками — кроме одного, чего команде знать не по чину: откуда взялся выбор законов. У строки\n * запуска это флаг, у терминала — вопрос, у прогона без терминала нет ни того ни другого.\n */\nimport { execFileSync } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport process from 'node:process';\n\nimport { unknownFlagsIn } from '../lib/argv.js';\nimport { IEntryOfCatalog, readCatalog, resolveSelection } from '../lib/catalog.js';\nimport { adopt, doctor, IEnvironment, init, IOutcomeOfCommand, list, stats, sync } from '../lib/commands.js';\nimport { CONFIG_PATH, IConfig, readConfig } from '../lib/config.js';\nimport { costLines, costOf, CostUnavailableError, ICost } from '../lib/cost.js';\nimport { enroll, httpEnroll } from '../lib/enroll.js';\nimport { httpReadOwn, httpShip } from '../lib/ship.js';\nimport { fate } from '../lib/fate.js';\nimport { propose } from '../lib/shipment.js';\nimport { treeSlugOf } from '../lib/tree-mark.js';\nimport { DEFAULT_DAYS } from '../lib/observations.js';\nimport { staleBuild } from '../lib/freshness.js';\nimport { packageRootFrom } from '../lib/package-root.js';\nimport { IChoice } from '../lib/picker.js';\nimport { IAxis, IOptionOfAxis, readAxes } from '../lib/variants.js';\nimport { ask, askOne, canAsk } from './prompt.js';\n\nconst USAGE: readonly string[] = [\n 'agent-kit <команда>',\n '',\n ' init завести .claude/rt-kit.json и каталог надстроек',\n ' list что везёт пакет и что из этого взято здесь',\n ' sync разложить ресурсы пакета в дерево проекта',\n ' sync --check ничего не писать, отказать при расхождении — для гейта пуша',\n ' doctor рассказать о состоянии раскладки, ничего не меняя',\n ' cost посчитать цену контекста: вход в работу, одно правило, весь слой',\n ' cost --rule <имя> какое правило взвесить; без довода берётся самое тяжёлое',\n ' cost --json то же машиночитаемо — этим числа кладут в замысел',\n ' stats свести наблюдения: чем пользовались, чем ни разу, обо что спотыкались',\n ' stats --days N за сколько дней; без довода — за три',\n ' stats --json то же машиночитаемо — этим сводку прикладывают к предложению',\n ' propose отправить груз в приём: сводку со снимком надстроек, предложения и разборы',\n ' fate судьба своих записей в приёме и надстройки, которые пора снять',\n ' propose --dry-run показать, что уехало бы, и ничего не отправлять',\n ' adopt [файлы] отдать пакету файлы, лежащие на его путях не от него',\n ' enroll --code <код> завести дерево по приглашению владельца: обмен кода на токен',\n ' enroll --token <токен> завести дерево токеном, выданным в админке приёма; в сеть не идёт',\n ' enroll --force перезаписать уже лежащий токен намеренно',\n '',\n ' --root <путь> корень проекта; по умолчанию текущий каталог',\n '',\n 'Выбор законов при `init`:',\n '',\n ' --all взять все законы, ни о чём не спрашивая',\n ' --laws a,b,c взять только названные; имена — из `agent-kit list`',\n ' без обоих спросить галочками; без терминала — отказ',\n '',\n 'Вид ресурсов при `init` — там, где один закон исполняется разными командами:',\n '',\n ' --<ось> <вид> например `--host gitlab`; оси и виды — из `agent-kit list`',\n ' без флага спросить; без терминала — отказ, кроме `--all`',\n];\n\n/**\n * Доводы отправки. Довод со значением помечен `<>`: за ним идёт отдельным словом путь, и без\n * пометки этот путь читался бы как ещё один незнакомый довод.\n */\nconst PROPOSE_FLAGS: readonly string[] = ['--dry-run', '--root <>'];\n\n/** Что печатает отказ на незнакомом доводе: режимы команды, а не весь свод. */\nconst PROPOSE_USAGE: readonly string[] = [\n ' propose отправить груз в приём',\n ' propose --dry-run показать, что уехало бы, и ничего не отправлять',\n ' --root <путь> корень проекта; по умолчанию текущий каталог',\n];\n\n/**\n * Единственное место, где пакет узнаёт собственное расположение. `import.meta` живёт только\n * здесь: библиотечные модули получают каталог ресурсов входным значением, и трансформ тестов,\n * разбирающий модули как CommonJS, на них уже не спотыкается.\n */\nfunction environmentOf(root: string): IEnvironment {\n const pkg: string = packageRootFrom(dirname(fileURLToPath(import.meta.url)));\n const manifest: { name: string; version: string } = JSON.parse(readFileSync(join(pkg, 'package.json'), 'utf8')) as {\n name: string;\n version: string;\n };\n\n return {\n root,\n version: manifest.version,\n // Имя из манифеста, а не записанное здесь: по нему пакет ищет себя в зависимостях дерева,\n // и своя копия имени разошлась бы с манифестом молча — у всякого, кто пакет переименовал.\n name: manifest.name,\n assetsDir: join(pkg, 'assets'),\n // Сверка со своими исходниками возможна только отсюда: здесь пакет знает, где лежит сам.\n // У потребителя исходников рядом нет, и сверка молчит.\n stale: staleBuild(pkg, manifest.name),\n };\n}\n\n/** Вывод git в этом дереве. Отказ и пустота здесь одно и то же: адреса нет — и это не отказ. */\nfunction gitSays(root: string, args: readonly string[]): string {\n try {\n // eslint-disable-next-line sonarjs/no-os-command-from-path -- путь к git у каждой машины свой, и прибитый здесь сделал бы пакет непереносимым\n return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();\n } catch {\n return '';\n }\n}\n\n/** Имена удалённых репозиториев этого дерева, по одному в строке. */\nfunction remoteNames(root: string): readonly string[] {\n return gitSays(root, ['remote'])\n .split('\\n')\n .map((name: string): string => name.trim())\n .filter(Boolean);\n}\n\n/**\n * Чем это дерево себя выдаёт снаружи. Нет удалённого репозитория — нечем, и это не отказ.\n *\n * Имя `origin` — соглашение, а не устройство: рабочая копия, назвавшая свои remotes по хостам,\n * на которые смотрит, оставалась без адреса вовсе, и отправка отказывала словами «удалённого\n * репозитория нет» — при том что репозиторий у неё есть, и не один. Порядок поэтому такой:\n * `origin`, если он есть; ровно один remote — он; несколько без `origin` — адреса нет, и выбор\n * за человеком. Угадать здесь нельзя: угаданное неверно сливает в сводке приёма два дерева в\n * одно, а увидеть это нечем.\n */\nfunction remoteOf(root: string): string {\n const names: readonly string[] = remoteNames(root);\n\n if (names.includes('origin')) {\n return gitSays(root, ['remote', 'get-url', 'origin']);\n }\n\n return names.length === 1 ? gitSays(root, ['remote', 'get-url', names[0]]) : '';\n}\n\nfunction optionOf(argv: readonly string[], name: string, fallback: string): string {\n const index: number = argv.indexOf(name);\n\n return index >= 0 && argv[index + 1] ? argv[index + 1] : fallback;\n}\n\nconst isOutcome: (value: unknown) => value is IOutcomeOfCommand = (value: unknown): value is IOutcomeOfCommand =>\n typeof value === 'object' && value !== null && 'code' in value;\n\n/**\n * Выбор законов для `init`: список идентификаторов, `null` на брошенном выборе или готовый\n * отказ. Пустой список означает «взять всё», поэтому брошенный выбор отличается от него не\n * значением, а `null`: подставить «всё» вместо неотвеченного вопроса значило бы разложить\n * пятнадцать законов тому, кто как раз просил спросить.\n */\nasync function selectionFor(argv: readonly string[], assetsDir: string): Promise<readonly string[] | null | IOutcomeOfCommand> {\n if (argv.includes('--all')) {\n return [];\n }\n\n const catalog: readonly IEntryOfCatalog[] = readCatalog(assetsDir);\n const spoken: string = optionOf(argv, '--laws', '');\n\n if (spoken) {\n const named: string[] = spoken\n .split(',')\n .map((name: string): string => name.trim())\n .filter(Boolean);\n const { ids, unknown } = resolveSelection(named, 'laws', catalog);\n\n return unknown.length\n ? { code: 1, lines: [`таких законов пакет не везёт: ${unknown.join(', ')}`, 'что везёт — `agent-kit list`'] }\n : ids;\n }\n\n if (!canAsk()) {\n return {\n code: 1,\n lines: [\n 'спросить некого: запуск без терминала',\n 'назови законы флагом `--laws a,b,c` или возьми все флагом `--all`',\n 'что везёт пакет — `agent-kit list`',\n ],\n };\n }\n\n const choices: readonly IChoice[] = catalog\n .filter((entry: IEntryOfCatalog): boolean => entry.kind === 'laws')\n .map((entry: IEntryOfCatalog): IChoice => ({ id: entry.id, name: entry.name, title: entry.title }));\n\n return ask(choices, 'Какие законы разложить в этом проекте?');\n}\n\n/**\n * Виды для `init` по осям, объявленным пакетом: что взято из флага, что спрошено.\n *\n * `--all` берёт первый объявленный вид оси и **говорит об этом**: в CI спрашивать некого, а\n * отказ там означал бы, что пакет нельзя разложить без человека. Первый вид — умолчание, а не\n * догадка: порядок в объявлении оси и есть порядок предпочтения.\n */\nasync function variantOfAxis(axis: IAxis, argv: readonly string[]): Promise<string | null | IOutcomeOfCommand> {\n const spoken: string = optionOf(argv, `--${axis.name}`, '');\n const values: readonly string[] = axis.options.map((option: IOptionOfAxis): string => option.value);\n\n if (spoken) {\n return values.includes(spoken)\n ? spoken\n : {\n code: 1,\n lines: [`такого вида по оси «${axis.name}» пакет не везёт: ${spoken}`, `есть: ${values.join(', ')}`],\n };\n }\n\n if (argv.includes('--all')) {\n return axis.options[0]?.value ?? '';\n }\n\n if (!canAsk()) {\n return {\n code: 1,\n lines: ['спросить некого: запуск без терминала', `назови вид флагом \\`--${axis.name} <вид>\\`: ${values.join(', ')}`],\n };\n }\n\n return askOne(\n axis.options.map((option: IOptionOfAxis): IChoice => ({ id: option.value, name: option.value, title: option.title })),\n axis.question\n );\n}\n\nasync function variantsFor(argv: readonly string[], assetsDir: string): Promise<Record<string, string> | null | IOutcomeOfCommand> {\n const axes: readonly IAxis[] = readAxes(assetsDir);\n const chosen: Record<string, string> = {};\n\n for (const axis of axes) {\n const answer: string | null | IOutcomeOfCommand = await variantOfAxis(axis, argv);\n\n if (isOutcome(answer)) {\n return answer;\n }\n\n if (answer === null) {\n return null;\n }\n\n chosen[axis.name] = answer;\n }\n\n return chosen;\n}\n\n/** Заведение настройки: выбор ресурсов и видов, брошенный выбор ничего не пишет. */\nasync function runInit(env: IEnvironment, argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const selection: readonly string[] | null | IOutcomeOfCommand = await selectionFor(argv, env.assetsDir);\n if (isOutcome(selection)) {\n return selection;\n }\n if (selection === null) {\n return { code: 1, lines: ['выбор брошен — ничего не заведено'] };\n }\n\n const variants: Record<string, string> | null | IOutcomeOfCommand = await variantsFor(argv, env.assetsDir);\n if (isOutcome(variants)) {\n return variants;\n }\n\n return variants === null\n ? { code: 1, lines: ['выбор брошен — ничего не заведено'] }\n : init(env.root, selection, variants, env.assetsDir);\n}\n\n/**\n * Цена контекста: три веса и то, чем они сняты.\n *\n * Отказ печатается тем же выводом, а не броском: команду зовут глазами, и трассировка стека\n * говорит ей читателю меньше, чем строка о том, чего в дереве нет.\n */\nfunction runCost(env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand {\n const named: string = optionOf(argv, '--rule', '');\n let cost: ICost;\n try {\n cost = costOf(env.root, named === '' ? null : named);\n } catch (failure: unknown) {\n if (failure instanceof CostUnavailableError) {\n return { code: 1, lines: [failure.message] };\n }\n throw failure;\n }\n\n return { code: 0, lines: [...costLines(cost, argv.includes('--json'))] };\n}\n\n/** Сводка наблюдений: отрезок из флага, сегодняшний день — с края. */\nfunction runStats(env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand {\n const spoken: number = Number(optionOf(argv, '--days', ''));\n\n return stats(env, {\n days: Number.isFinite(spoken) && spoken > 0 ? Math.floor(spoken) : DEFAULT_DAYS,\n // Сегодняшний день берётся здесь: у команды своих часов нет, иначе сводку за\n // отрезок не проверить спекой — вчерашняя фикстура завтра станет позавчерашней.\n today: new Date().toISOString().slice(0, 10),\n json: argv.includes('--json'),\n });\n}\n\n/**\n * Отправка накопленного.\n *\n * Единственное действие этой команды необратимо и уходит наружу, поэтому незнакомый довод её\n * кончает, а не пропускается молча: вызов ради списка режимов отправил в приём всё накопленное, и\n * по выводу это не отличалось от «команда ничего не сделала». Прочие команды такого разбора не\n * знают — их действие обратимо.\n */\nasync function runPropose(env: IEnvironment, argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const unknown: readonly string[] = unknownFlagsIn(argv.slice(1), PROPOSE_FLAGS);\n if (unknown.length) {\n return {\n code: 1,\n lines: [`таких доводов у \\`propose\\` нет: ${unknown.join(', ')}`, '', ...PROPOSE_USAGE],\n };\n }\n\n return propose(env, {\n dryRun: argv.includes('--dry-run'),\n ship: httpShip,\n remote: remoteOf(env.root),\n // Имена доезжают до отказа: выбор за человеком, и отказ, не назвавший, из чего выбирать,\n // отправляет его смотреть то же самое своими руками.\n remotes: remoteNames(env.root),\n // Отрезок тот же, что у сводки по умолчанию: отправку зовут по свежей задаче.\n days: DEFAULT_DAYS,\n today: new Date().toISOString().slice(0, 10),\n });\n}\n\n/** Судьба своих записей: чтение приёма по токену дерева и надстройки под ними. */\nfunction runFate(env: IEnvironment): Promise<IOutcomeOfCommand> {\n return fate(env, { read: httpReadOwn });\n}\n\n/** Приписка дерева к приёмнику по коду приглашения. */\nasync function runEnroll(env: IEnvironment, argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const config: IConfig | null = readConfig(env.root);\n\n if (!config) {\n return { code: 1, lines: [`настройки дерева нет: ${CONFIG_PATH}. Заведите её командой \\`init\\``] };\n }\n\n return enroll({\n root: env.root,\n intake: config.intake,\n code: optionOf(argv, '--code', ''),\n issued: optionOf(argv, '--token', ''),\n tree: treeSlugOf(remoteOf(env.root), config.tree),\n token: config.token,\n force: argv.includes('--force'),\n call: httpEnroll,\n });\n}\n\n/** Ветка команды: окружение и доводы строки запуска на входе, вывод и код возврата на выходе. */\ntype TCommandRun = (env: IEnvironment, argv: readonly string[]) => IOutcomeOfCommand | Promise<IOutcomeOfCommand>;\n\n/** Что делает каждая команда строки запуска. Ключ — слово, которым её зовут. */\nconst COMMANDS: Readonly<Record<string, TCommandRun>> = {\n init: runInit,\n list: (env: IEnvironment): IOutcomeOfCommand => list(env),\n sync: (env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand => sync(env, argv.includes('--check')),\n cost: runCost,\n stats: runStats,\n propose: runPropose,\n fate: runFate,\n enroll: runEnroll,\n doctor: (env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand => doctor(env, optionOf(argv, '--since', '')),\n adopt: (env: IEnvironment, argv: readonly string[]): IOutcomeOfCommand =>\n adopt(\n env,\n argv.slice(1).filter((value: string): boolean => !value.startsWith('--') && value !== optionOf(argv, '--root', ''))\n ),\n};\n\nexport async function main(argv: readonly string[]): Promise<IOutcomeOfCommand> {\n const command: string = argv[0] ?? '';\n const env: IEnvironment = environmentOf(resolve(optionOf(argv, '--root', process.cwd())));\n const run: TCommandRun | undefined = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : undefined;\n\n if (!run) {\n return { code: command ? 1 : 0, lines: command ? [`неизвестная команда «${command}»`, '', ...USAGE] : USAGE };\n }\n\n return run(env, argv);\n}\n\nconst outcome: IOutcomeOfCommand = await main(process.argv.slice(2));\nfor (const line of outcome.lines) {\n // eslint-disable-next-line no-console\n console.log(line);\n}\nprocess.exit(outcome.code);\n"]}
package/lib/cargo.d.ts CHANGED
@@ -9,8 +9,50 @@
9
9
  * Файл держится без единого импорта намеренно: его читает и приём, и всякий, кто ставит пакет,
10
10
  * — а всё остальное в пакете написано под запуск из строки запуска.
11
11
  */
12
- /** Версия формата запроса приёма. Меняется, когда меняется состав полей самого груза. */
12
+ /**
13
+ * Версия формата запроса приёма. Меняется, когда меняется состав полей самого груза.
14
+ *
15
+ * `2` — четвёртый род груза, строки наблюдений: дерево прежней редакции шлёт три рода под `1`,
16
+ * и приём берёт их как прежде.
17
+ */
13
18
  export declare const CARGO_SCHEMA_VERSION: string;
19
+ /** Род загруженного скила: чей он — пакета или самого дерева. Считает отправитель по раскладке. */
20
+ export type TSkillKind = 'rule' | 'pattern' | 'skill' | 'own';
21
+ /** Роды событий, которые пишут гарды дерева. Приём чужой род не принимает. */
22
+ export declare const OBSERVATION_EVENTS: readonly string[];
23
+ /**
24
+ * Одна строка наблюдения — как лежит в файле дня, плюс род скила у загрузки.
25
+ *
26
+ * Имена полей повторяют файл: `t` время, `ev` событие, `res` ресурс, `kind` род правки у отказа
27
+ * гейта, `sid` признак сессии, `v` версия пакета. Пути в строке нет, признак сессии — контрольная
28
+ * сумма: груз не говорит о дереве больше, чем сводка.
29
+ */
30
+ export interface IObservationLine {
31
+ readonly t: string;
32
+ readonly ev: string;
33
+ readonly res: string;
34
+ readonly kind?: string;
35
+ readonly sid: string;
36
+ readonly v: string;
37
+ readonly skill?: TSkillKind;
38
+ }
39
+ /** Строки одного дня. День уезжает целиком: приём замещает день целиком. */
40
+ export interface IObservationDay {
41
+ /** День вида `2026-09-14`, по всемирному времени — как назван файл. */
42
+ readonly day: string;
43
+ readonly lines: readonly IObservationLine[];
44
+ }
45
+ /**
46
+ * Строки наблюдений за отрезок отправки, по дням.
47
+ *
48
+ * `origin` — признак рабочей копии: у одного дерева их несколько, признак дерева у них общий, а
49
+ * файлы наблюдений у каждой свои. Приём замещает день по паре «копия — день», иначе последняя
50
+ * отправившая копия стирала бы строки соседней. Контрольная сумма пути, самого пути в грузе нет.
51
+ */
52
+ export interface IObservationsCargo extends ICargoHead {
53
+ readonly origin: string;
54
+ readonly days: readonly IObservationDay[];
55
+ }
14
56
  /** Заголовок, которым дерево представляется приёму. */
15
57
  export declare const TREE_TOKEN_HEADER: string;
16
58
  /** Род правки надстройки: дерево замещает раздел пакета, дописывает свой или снимает пакетный. */
@@ -105,6 +147,12 @@ export interface IIntakeAccepted {
105
147
  readonly added?: number;
106
148
  readonly known?: number;
107
149
  }
150
+ /** Ответ приёма на груз наблюдений: сколько дней замещено и сколько строк легло. */
151
+ export interface IObservationsAccepted {
152
+ readonly tree: string;
153
+ readonly days: number;
154
+ readonly rows: number;
155
+ }
108
156
  /** Род записи груза, у которой есть состояние. Набор закрыт: сводка месяца состояния не несёт. */
109
157
  export type TCargoStateKind = 'postmortem' | 'proposal';
110
158
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"cargo.d.ts","sourceRoot":"","sources":["../../../projects/agent-kit/src/lib/cargo.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,yFAAyF;AACzF,eAAO,MAAM,oBAAoB,EAAE,MAAY,CAAC;AAEhD,uDAAuD;AACvD,eAAO,MAAM,iBAAiB,EAAE,MAAuB,CAAC;AAExD,kGAAkG;AAClG,MAAM,MAAM,aAAa,GAAG,S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A0F;AAC1F,MAAM,WAAW,eAAe;IAC5B,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAC/B,mFAAmF;IACnF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC;;;OAGG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CACpC;AAED,oFAAoF;AACpF,MAAM,WAAW,eAAgB,SAAQ,UAAU;IAC/C,QAAQ,CAAC,KAAK,EAAE,SAAS,eAAe,EAAE,CAAC;CAC9C;AAED,qFAAqF;AACrF,MAAM,WAAW,iBAAiB;IAC9B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;IAC/B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,yEAAyE;IACzE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CAC3B;AAED,oFAAoF;AACpF,MAAM,WAAW,mBAAmB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,kCAAkC;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,4EAA4E;IAC5E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,SAAS,iBAAiB,EAAE,CAAC;CACjD"}
package/lib/cargo.js CHANGED
@@ -9,8 +9,15 @@
9
9
  * Файл держится без единого импорта намеренно: его читает и приём, и всякий, кто ставит пакет,
10
10
  * — а всё остальное в пакете написано под запуск из строки запуска.
11
11
  */
12
- /** Версия формата запроса приёма. Меняется, когда меняется состав полей самого груза. */
13
- export const CARGO_SCHEMA_VERSION = '1';
12
+ /**
13
+ * Версия формата запроса приёма. Меняется, когда меняется состав полей самого груза.
14
+ *
15
+ * `2` — четвёртый род груза, строки наблюдений: дерево прежней редакции шлёт три рода под `1`,
16
+ * и приём берёт их как прежде.
17
+ */
18
+ export const CARGO_SCHEMA_VERSION = '2';
19
+ /** Роды событий, которые пишут гарды дерева. Приём чужой род не принимает. */
20
+ export const OBSERVATION_EVENTS = ['skill-load', 'gate-deny', 'guard-deny', 'push-gate'];
14
21
  /** Заголовок, которым дерево представляется приёму. */
15
22
  export const TREE_TOKEN_HEADER = 'x-tree-token';
16
23
  /**