@rt-tools/agent-kit 0.30.0 → 0.31.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/assets/checks/board-runs.github.mjs +7 -2
- package/assets/checks/board.github.mjs +28 -4
- package/assets/checks/task-new-queue.github.mjs +51 -0
- package/assets/checks/task-new.github.mjs +4 -41
- package/assets/defaults/project.sh +3 -0
- package/assets/hooks/epic-stop-guard.sh +6 -1
- package/assets/hooks/git-guard-delivery-body.sh +51 -0
- package/assets/hooks/git-guard-delivery-merge.sh +32 -0
- package/assets/hooks/git-guard-delivery.sh +12 -26
- package/assets/hooks/grill-gate.sh +2 -2
- package/assets/hooks/write-targets.sh +69 -3
- package/assets/patterns/admin-nav-item.md +2 -1
- package/assets/patterns/browser-verification-stand.md +3 -0
- package/assets/patterns/doc-style-human.md +21 -0
- package/assets/patterns/git-workflow-docker.md +4 -2
- package/assets/patterns/git-workflow-merge.md +6 -0
- package/assets/patterns/git-workflow-pr-body.github.md +4 -1
- package/assets/patterns/git-workflow-pr-ready.md +9 -0
- package/assets/patterns/spec-driven-domain.md +12 -0
- package/assets/patterns/testing-e2e.md +16 -2
- package/assets/patterns/testing-unit.md +4 -0
- package/assets/pitfalls/styling-bem.md +11 -0
- package/assets/rules/browser-verification.md +7 -5
- package/assets/rules/component-structure.md +4 -0
- package/assets/rules/deploy-flow.github.md +28 -2
- package/assets/rules/git-workflow.github.md +1 -1
- package/assets/rules/lib-layers.md +2 -2
- package/assets/rules/reuse-first.md +7 -0
- package/assets/rules/shared-code.md +3 -0
- package/assets/rules/spec-driven.md +3 -1
- package/assets/rules/testing.md +3 -1
- package/assets/rules/turn-conduct.md +10 -11
- package/lib/proposals.d.ts.map +1 -1
- package/lib/proposals.js +9 -1
- package/lib/proposals.js.map +1 -1
- package/lib/ship.d.ts +9 -0
- package/lib/ship.d.ts.map +1 -1
- package/lib/ship.js +16 -0
- package/lib/ship.js.map +1 -1
- package/lib/shipment.d.ts.map +1 -1
- package/lib/shipment.js +30 -29
- package/lib/shipment.js.map +1 -1
- package/package.json +1 -1
- package/rt-tools-agent-kit-0.30.0.tgz +0 -0
|
@@ -38,6 +38,12 @@ has a scenario prefix of its own, and the audit gives no spec a second prefix: t
|
|
|
38
38
|
such work part into two numberings — one per spec they will merge into. The plan names both, and
|
|
39
39
|
they merge apart, each into its own spec.
|
|
40
40
|
|
|
41
|
+
The place of an agreement is chosen by the length of the spec it will merge into, at the moment it
|
|
42
|
+
is written. The domain spec plus the agreement's rules is measured against the tree's size limit;
|
|
43
|
+
one that would cross it is written from the start as the agreement of a new subdomain, with its
|
|
44
|
+
own scenario prefix. Measured only at the merge, the overrun moves a finished agreement to a new
|
|
45
|
+
place and a new prefix, together with the test titles that carry its numbers.
|
|
46
|
+
|
|
41
47
|
## Mandatory sections
|
|
42
48
|
|
|
43
49
|
`## Зачем` · `## Терминология` with the subsection `### Как это называется в интерфейсе` ·
|
|
@@ -155,6 +161,12 @@ command's name is given by the rule's companion.
|
|
|
155
161
|
4. `npm run check:specs` — before the push.
|
|
156
162
|
5. Acceptance goes by the scenarios, not by a retelling of the edit.
|
|
157
163
|
|
|
164
|
+
Between steps 2 and 3 `npm run check:specs` is red by design, not by mistake. A scenario without a
|
|
165
|
+
test it only lists, but a rule without a binding and a contract row without a procedure it refuses,
|
|
166
|
+
and their bindings name code that is not written yet. So a stage that edits the spec names as its
|
|
167
|
+
readiness sign the refusal list itself — only the new rules unbound, only the new scenarios under
|
|
168
|
+
"no test" — and not exit 0. Exit 0 is the sign of the stage that writes the bound code.
|
|
169
|
+
|
|
158
170
|
A rule promising a result a person sees is confirmed on the running application, not by
|
|
159
171
|
inference from the call graph. Reading confirms headings, the link to bindings and the shape of
|
|
160
172
|
data; a rule with nothing to confirm it on leaves as an open question and is not written as a
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
name: testing-e2e
|
|
3
3
|
kind: pattern
|
|
4
4
|
rule: testing
|
|
5
|
-
description: Pattern of rule testing. Load when editing and running end-to-end tests in
|
|
5
|
+
description: Pattern of rule testing. Load when editing and running end-to-end tests in any end-to-end suite of the tree (apps/*-e2e) — what an end-to-end test closes, ready-made run commands, a stand from the production build behind real nginx, test switches. Not for unit tests — that is pattern testing-unit.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# End-to-end tests
|
|
@@ -31,7 +31,8 @@ An action that adds a node to the page — sending a message, adding a row, atta
|
|
|
31
31
|
done at least twice in one test. The first time the page holds only the node the action needs; the
|
|
32
32
|
second time it also holds the one the first action added, and a query that matched by a shared mark
|
|
33
33
|
now finds the wrong node. One send per test passes against a handler that breaks on every second
|
|
34
|
-
send.
|
|
34
|
+
send. A toast is such a node too: the one from the previous action is still on screen, so the toast
|
|
35
|
+
is matched by the text only its own action puts out, not by a broad pattern.
|
|
35
36
|
|
|
36
37
|
Elements are found by `qa-dataid`: classes change together with the layout, and a search by role
|
|
37
38
|
and text breaks on translations.
|
|
@@ -128,8 +129,17 @@ The same holds for a popup that stays open after its item is chosen. It covers t
|
|
|
128
129
|
click aimed at a button under it goes to the popup: the screen answers as if the button had not
|
|
129
130
|
been pressed at all. The popup is closed and its absence awaited by the same pair of lines.
|
|
130
131
|
|
|
132
|
+
A screen is ready when its data is, not when its heading is. A heading, a month title or a toolbar
|
|
133
|
+
comes from the template and is drawn before the request answers. A check or a frame that waits for
|
|
134
|
+
it reads an empty grid. The wait names a node that exists only with data: a row, a booking, a
|
|
135
|
+
selected record.
|
|
136
|
+
|
|
131
137
|
## Common misses
|
|
132
138
|
|
|
139
|
+
- **A search on the stand matches by substring, and older seeds stay.** `editor@example.com` also
|
|
140
|
+
found `stand-editor@…` and `e2e-editor@…` left by earlier runs, and four old tests failed at
|
|
141
|
+
once. People a suite creates carry the suite prefix in the whole value (`e2e-<suite>-…`), and the
|
|
142
|
+
test searches by that whole value, not by a common part.
|
|
133
143
|
- **A service limit per client address counts the whole suite as one client.** Every test goes from
|
|
134
144
|
one machine, so a limit on requests per minute is reached by the sum of the tests, not by any one
|
|
135
145
|
of them. Adding tests pushes old ones into refusal (429): a run of one spec stays green, and only
|
|
@@ -164,3 +174,7 @@ been pressed at all. The popup is closed and its absence awaited by the same pai
|
|
|
164
174
|
- **A build directory removed under a mounted volume leaves the container with an empty root:** the
|
|
165
175
|
stand answers 403 to everything, and all tests fail at once. After
|
|
166
176
|
`rm -rf dist/apps/<application>` the container is recreated.
|
|
177
|
+
- **The service name of a direct call is copied from the contract.** A service is often named by
|
|
178
|
+
its audience, not by its record. A guessed name gets "not found" for the whole path, and that
|
|
179
|
+
reads as a broken procedure or a missing right. The name is found in the contract declarations
|
|
180
|
+
before the first call.
|
|
@@ -129,6 +129,10 @@ nothing.
|
|
|
129
129
|
|
|
130
130
|
- A lib without its own `vitest.config.mts`: `nx test <project>` passes green without running a
|
|
131
131
|
single file. Before writing the first test in a lib, check that the config is next to it.
|
|
132
|
+
- **The compiler import goes into the harness file, not into the spec.** A lib that renders nothing
|
|
133
|
+
still pulls the framework when its test imports a barrel with a framework service, and the first
|
|
134
|
+
import fails on JIT. The import goes into the file named in `setupFiles` of the lib's run config:
|
|
135
|
+
in the spec the linter moves it below its neighbours, and the test turns red only in the full set.
|
|
132
136
|
- Substituting a module (`vi.mock`) would hide what the test is created for — which call went to
|
|
133
137
|
the database and in what order. The double is written by hand.
|
|
134
138
|
- Do not create your own helpers for assertions: `expect(...).toBe(...)` and `.toEqual(...)`
|
|
@@ -37,6 +37,10 @@ The rule is `styling-bem`; the articles that hold the law stand there.
|
|
|
37
37
|
- **`justify-content: center` in a flex container with `overflow-x` pushes the first items beyond
|
|
38
38
|
zero scroll** — there is no way to scroll to them. In scrollable strips —
|
|
39
39
|
`justify-content: safe center`.
|
|
40
|
+
- **A strip with `overflow-x` inside a flex column collapses to a few pixels.** Any `overflow` other
|
|
41
|
+
than `visible` makes the item a scroll container, and its automatic minimum height becomes zero.
|
|
42
|
+
When the column runs out of height, the strip yields first. The strip gets `flex-shrink: 0`. The
|
|
43
|
+
measurement is the strip's height against its button's, at three widths.
|
|
40
44
|
- **Do not put `scrollbar-gutter: stable` on the root:** the reserve for the scrollbar narrows the
|
|
41
45
|
containing block for `position: fixed`, and a popup aligned to the right edge lands a reserve's
|
|
42
46
|
width to the left of its button.
|
|
@@ -49,3 +53,10 @@ The rule is `styling-bem`; the articles that hold the law stand there.
|
|
|
49
53
|
be reset.
|
|
50
54
|
- **stylelint disable comments are not placed.** Selectors are combined by nesting.
|
|
51
55
|
- **Moving styles adds no new declarations** — only existing ones are relocated.
|
|
56
|
+
- **A moved rule keeps the reach it had, not the one its comment names.** Sass `&` repeats the
|
|
57
|
+
whole parent selector, `:host-context(...)` included. `:host-context(.x) .block { &__a &__b {} }`
|
|
58
|
+
compiles to two `:host-context` in one selector. After the encapsulation shim, `__a` no longer
|
|
59
|
+
limits `__b`, and the rule reaches every `__b`. Before a move, the reach is read from the
|
|
60
|
+
compiled selector in the build output. After the move, frames of the affected screens are
|
|
61
|
+
compared byte for byte with frames taken before the edit. Build, lint and the class check stay
|
|
62
|
+
green, and the eye misses a change of one font step.
|
|
@@ -91,6 +91,10 @@ flowchart TD
|
|
|
91
91
|
answers it. The sign that closes the screen arrives with the substituted profile. Asking a person
|
|
92
92
|
to do a step of the check — type a password, open a tab, press a button — means a wrongly chosen
|
|
93
93
|
path, not a lack of rights on the executor's side.
|
|
94
|
+
- **A move of people into a sign-in system is checked by signing in as a moved person.** The stand
|
|
95
|
+
holds the same profile fields as the real people have after the move: a person moved with only a
|
|
96
|
+
mail and rights lacks what the system requires of a profile, and is sent to a step the form check
|
|
97
|
+
never reaches. Requests to the form, the API and the sign-in settings walk no part of that path.
|
|
94
98
|
- **Changing the number of elements in a container is a layout edit.** It touches no styles, so it
|
|
95
99
|
reads as a markup edit, and the check shrinks to response codes. The pages answer in every locale,
|
|
96
100
|
and the document is already twice the viewport width. It is closed by a measurement — document
|
|
@@ -102,6 +106,9 @@ flowchart TD
|
|
|
102
106
|
edge and clipping without a sign show only where the content does not fit its place. On a short
|
|
103
107
|
value all three look fine. The value for measurement is the extreme one — what the node can get
|
|
104
108
|
from a real consumer, not what stands in the example.
|
|
109
|
+
- **The longest value is set for every node that shares the line, not only for the edited one.** An
|
|
110
|
+
element next to a neighbour takes its place from the neighbour's length. A long neighbour wraps
|
|
111
|
+
the element to a new line, and the element lands at its start. Its own short value hides that.
|
|
105
112
|
- **A ready-made kit piece taken for values of another size is measured, not looked at.** A
|
|
106
113
|
component that lived where values are short gets a value four times longer in its new place. It
|
|
107
114
|
behaves differently while staying the same code. The test does not see this at all: clipping by
|
|
@@ -194,11 +201,6 @@ frontend-application law: such access compiles and fails only when the page is s
|
|
|
194
201
|
the new stand, and the list of what was left is named to the owner at the end of the session —
|
|
195
202
|
only they can kill those. Not named so, stands pile up across sessions and hold connections to the
|
|
196
203
|
storage.
|
|
197
|
-
- **A measurement is also taken by an end-to-end test, not only by the browser driver.** Window
|
|
198
|
-
width, node position and the document going sideways are read there by the same computed values.
|
|
199
|
-
The viewport is set for the test suite, and the result repeats on every run — unlike a manual
|
|
200
|
-
measurement, which lives exactly one session. The driver stays where an unfamiliar screen is
|
|
201
|
-
looked at, not where a known number is confirmed.
|
|
202
204
|
- **A statement about the production build is made from the build itself, not from the branch.**
|
|
203
205
|
Between the branch and what is served to the reader stands the image build. It substitutes
|
|
204
206
|
environment values, cuts out the unused and renames symbols. "The build holds this" is checked by
|
|
@@ -94,3 +94,7 @@ environment either — that is `Q-FA-1` in the law.
|
|
|
94
94
|
`role="dialog"`, `role="tablist"` or `role="tooltip"` means that `<prefix>-message`,
|
|
95
95
|
`<prefix>-table`, `<prefix>-dialog`, `<prefix>-tabs` or `<prefix>-tooltip` were bypassed. The rule
|
|
96
96
|
whole — `reuse-first`.
|
|
97
|
+
- **A kit icon name is copied from its file, and an unknown name draws an empty frame.** The kit
|
|
98
|
+
draws the frame of an icon it did not find and says nothing. The build, the lint and the tests
|
|
99
|
+
stay green, and the owner sees an empty square. Before the edit the name is looked up among the
|
|
100
|
+
kit icon files: some names carry the `ico-` prefix and most do not.
|
|
@@ -72,7 +72,30 @@ flowchart TD
|
|
|
72
72
|
image says only that the build passed: the migrate step, the storage login, the startup order
|
|
73
73
|
and whether every container has enough put inside are visible from one launch of the stack. On
|
|
74
74
|
one's own machine that costs one command; on the node it costs a rollout that can no longer be
|
|
75
|
-
cancelled — the migrate failure surfaces as a container log on the node.
|
|
75
|
+
cancelled — the migrate failure surfaces as a container log on the node. The same launch is made
|
|
76
|
+
before a merge that lifts packages without a line of code changed: the stack passes an unset
|
|
77
|
+
variable as an empty string, and a new package version may stop accepting what the old one took.
|
|
78
|
+
- **A variable read by several procedures is turned on first on a stand from the production
|
|
79
|
+
build.** On the stand every reader passes; on production one edit says nothing about the
|
|
80
|
+
neighbours, and a variable left empty there turns into addresses built from nothing.
|
|
81
|
+
- **The name production is served under is confirmed by a live answer of that name.** `curl -s -o
|
|
82
|
+
/dev/null -w '%{http_code} %{redirect_url}\n' https://<name>/`: a redirect to a foreign address
|
|
83
|
+
means the name is dead, and the rollout does not go by it. Three files of one epoch agree by
|
|
84
|
+
common origin, not by being right. When a domain moves, the old name is searched across the whole
|
|
85
|
+
tree, not only the paths of one's own part.
|
|
86
|
+
- **Data the screens need that migrations do not create is a step of the rollout.** A seed run once
|
|
87
|
+
by hand heals one storage; a new or restored one stays empty, and a screen that shows an empty
|
|
88
|
+
list for an empty answer looks the same as an unreachable server. The step runs on every rollout
|
|
89
|
+
and is safe to repeat: found records are not overwritten. After the first rollout that depends on
|
|
90
|
+
seeded data the count of records is read on production.
|
|
91
|
+
- **A move of the pipeline to another runner is closed by a search for the labels across all
|
|
92
|
+
workflows.** A flow left on the host is named in the task with its reason. An order worded by a
|
|
93
|
+
set — "all", "every" — is closed against the list of that set, not against the member that got in
|
|
94
|
+
the way first. A rollout with production keys from a developer machine needs a separate word of
|
|
95
|
+
the owner.
|
|
96
|
+
- **The epic plan is checked line by line against the pitfalls of the rollout step before the merge
|
|
97
|
+
of the epic.** Every empty secret in the preparation script becomes a step "before the merge" or
|
|
98
|
+
a decision of the owner, not a line "left to do".
|
|
76
99
|
|
|
77
100
|
- **The image carries every file its own startup steps read.** The storage schema, the client
|
|
78
101
|
settings, the environment template — everything lying next to it in the repository does not get
|
|
@@ -87,7 +110,10 @@ flowchart TD
|
|
|
87
110
|
notice that by. They differ in the tail: the server then removes dangling layers and the build
|
|
88
111
|
cache, the build machine keeps them, otherwise every build goes as the first. Cleanup on the
|
|
89
112
|
build side does not wait for the merge: a branch image takes as much space, never leaves for the
|
|
90
|
-
registry and is never a rollback point.
|
|
113
|
+
registry and is never a rollback point. The build step names its builder explicitly: without the
|
|
114
|
+
name the build goes through the machine's current builder, which may have no cache limit, while
|
|
115
|
+
the declared one stands empty. The build machine keeps the build cache and removes dangling
|
|
116
|
+
images: the builder cache lies in its own volume, and dangling images are not part of it.
|
|
91
117
|
- **The rollout cleans up old images after itself, keeping the last three sha.** An image tagged
|
|
92
118
|
with a sha is never dangling, and a dangling cleanup does not touch it: in half a year they eat
|
|
93
119
|
the server disk whole. Three sha is the rollback depth, and fewer cannot be taken: a breakage
|
|
@@ -172,7 +172,7 @@ flowchart TD
|
|
|
172
172
|
- **The build is in the set on a par with lint and unit tests.** The linter does not read types,
|
|
173
173
|
and a type error in uncovered code lives until the merge.
|
|
174
174
|
- **On a machine with several runners, any path from the home directory is shared.** Install
|
|
175
|
-
directory, container name
|
|
175
|
+
directory, container name, builder name and published port are per project.
|
|
176
176
|
- **The push gate set is never narrower than the pipeline set.** A pipeline step with neither a
|
|
177
177
|
line in the set nor a declared exclusion refuses the push: a warning reads as permission.
|
|
178
178
|
- **The gate set calls the package default instead of listing it line by line.** Rewritten as
|
|
@@ -14,10 +14,10 @@ cut in this tree, what it is called and what we do not have.
|
|
|
14
14
|
|
|
15
15
|
| In the law | Here |
|
|
16
16
|
| ------------------------------------ | ------------------------------------------------------------------- |
|
|
17
|
-
| lib family |
|
|
17
|
+
| lib family | the frontend families listed by the `families` key of the checks' settings, and the backend family named by the `apiFamily` key |
|
|
18
18
|
| layer | `api`, `data-access`, `feature`, `shell`, `ui`, `util` |
|
|
19
19
|
| the right to see a lib | a tag in `eslint/boundaries/domains/<family>.config.mjs` |
|
|
20
|
-
| lib shared by
|
|
20
|
+
| lib shared by every application | `libs/common/util`, tag `scope:common-util` |
|
|
21
21
|
| family base | `<family>/core`; its tag is in `ADMIN_UNIVERSAL` |
|
|
22
22
|
| barrel | `src/index.ts` of the lib and `index.ts` of the component directory |
|
|
23
23
|
|
|
@@ -54,6 +54,13 @@ flowchart TD
|
|
|
54
54
|
- **Work starts with reading the ready-made, not with a blank file.** First the base is found — a
|
|
55
55
|
kit component, a base class, a sample in a neighbouring domain — then one's own is written on
|
|
56
56
|
top of it.
|
|
57
|
+
- **A sample is taken whole, and every departure from it is a decision written before the code.**
|
|
58
|
+
A sample read for one side of it — the data flow, the store, the columns — is not a sample: its
|
|
59
|
+
layout, its waiting state and its empty states are part of it as much as the markup of the table.
|
|
60
|
+
The executor lists what the sample holds, copies it, and names each departure in the progress
|
|
61
|
+
with its reason; a departure that appears in the code without a line in the progress is a miss,
|
|
62
|
+
not a choice. The check before showing the work is a measurement of one's own screen against the
|
|
63
|
+
sample's, node by node, not of one's own screen alone.
|
|
57
64
|
- **A restriction invented on the spot is checked by a search over the tree before it becomes an
|
|
58
65
|
argument.** "This is not allowed" is a statement about the tree like any other, and a tree
|
|
59
66
|
where the technique is already applied answers it with one command. Named to the owner before
|
|
@@ -101,3 +101,6 @@ name of the edit event in three. Cutting that down is work by domains, and it is
|
|
|
101
101
|
- The same logic written anew under another name is not caught by the check, and there will be no
|
|
102
102
|
such check: two checks of the same shape from different domains are not a copy. Only whoever reads
|
|
103
103
|
the edit can notice it — so says the law too.
|
|
104
|
+
- A value set declared by the contract (`@<scope>/common/proto`) is shared too. A screen enum with
|
|
105
|
+
the same members `npm run check:dupes` refuses even under another name. The api layer service maps
|
|
106
|
+
the contract value into what `State` needs — a label, a sign — and the screen declares no set.
|
|
@@ -231,7 +231,9 @@ flowchart TD
|
|
|
231
231
|
grows into dozens of subdomains, and the one needed is told from the rest only by reading: whoever
|
|
232
232
|
takes apart a complaint about a file pays the whole window for that and therefore judges by memory.
|
|
233
233
|
The command reads the bindings of the companions — the very ones the audit keeps fresh — and,
|
|
234
|
-
called without a name, names the resources no spec speaks of.
|
|
234
|
+
called without a name, names the resources no spec speaks of. It knows only what the package
|
|
235
|
+
lays out; for an application file it answers that the package carries no such name, and the
|
|
236
|
+
product spec is found by the file path in the bindings of the domain specs.
|
|
235
237
|
<!-- rt-when: *.md -->
|
|
236
238
|
|
|
237
239
|
## The shape of a compressed article
|
package/assets/rules/testing.md
CHANGED
|
@@ -173,7 +173,9 @@ flowchart TD
|
|
|
173
173
|
- **A line is not added to the known list for a red check.** The list was gathered by the day the
|
|
174
174
|
check was created and has only shrunk since: an added line silences the signal, not the cause,
|
|
175
175
|
and in history looks the same as a fix. A place where the check is right by the letter and
|
|
176
|
-
wrong in substance is reviewed by the owner, and until their answer the check is right.
|
|
176
|
+
wrong in substance is reviewed by the owner, and until their answer the check is right. An inline
|
|
177
|
+
mark that switches a check off for one place is the same line, written into the file instead of
|
|
178
|
+
the list. It is not placed even for a moment.
|
|
177
179
|
- **An exchange counts as read on both sides, not by the success of calls.** Sending and editing
|
|
178
180
|
state answer with success even when there is nothing to read the result with: over two hundred
|
|
179
181
|
records stood as new because there was nobody to collect them, and only those whose file still
|
|
@@ -247,18 +247,18 @@ flowchart TD
|
|
|
247
247
|
For a call with a reading twin, the kind is chosen by the action, not the command's name.
|
|
248
248
|
- **A turn in which a question was put to the owner does not end until laws and rules were read in
|
|
249
249
|
that same turn.** Reading is any of three roads: loading a rule, reading a file of laws or rules,
|
|
250
|
-
a search over them.
|
|
251
|
-
|
|
250
|
+
a search over them. With edits in the turn, only the rule the gate demands counts, and the
|
|
251
|
+
refusal names it. The guard refuses on the question tool before the menu leaves, and at
|
|
252
|
+
the turn's end for a question in prose. What was found lands in the grill section "What the
|
|
253
|
+
rules already say".
|
|
252
254
|
- **The owner's answer is sought in their own messages before the rules.** The law says a question
|
|
253
|
-
with a written answer is not put to the owner, and the most reachable record lies
|
|
254
|
-
|
|
255
|
-
- **The size of work is never a reason to cut its boundaries.**
|
|
256
|
-
|
|
257
|
-
clarification. What is costly is done at cost, or called costly outright, with the price named.
|
|
255
|
+
with a written answer is not put to the owner, and the most reachable record lies in the
|
|
256
|
+
conversation: the owner's first message and their answers to past rounds.
|
|
257
|
+
- **The size of work is never a reason to cut its boundaries.** An offer to drop a part is a request
|
|
258
|
+
to reassign the goal, served as a clarification. What is costly is done at cost, or called costly outright, with the price named.
|
|
258
259
|
- **The actions the executor does not do without the owner's word are listed in the rule's
|
|
259
260
|
companion.** Each tree has its own list; the package knows only the demand that it be named.
|
|
260
|
-
Unnamed,
|
|
261
|
-
finds it convenient this minute.
|
|
261
|
+
Unnamed, the appraisal "this is safe" is assigned by whoever finds it convenient.
|
|
262
262
|
- **What the host's automatic mode refuses is listed in the companion and read before the step.**
|
|
263
263
|
Such a refusal is a refused permission, not a guard: the step is named in one line and the work it
|
|
264
264
|
does not hold goes on. A browser click goes one per call.
|
|
@@ -269,8 +269,7 @@ flowchart TD
|
|
|
269
269
|
owner applies to the action, not the turn: work with a separable harmless part is split, not
|
|
270
270
|
postponed whole. The owner is told what is done and what remained for their word.
|
|
271
271
|
- **The sign of irreversibility is taken from the list, not derived by argument.** The list was
|
|
272
|
-
drawn up by someone who already weighed reversibility
|
|
273
|
-
silently. Actions outside the list the executor does not gate.
|
|
272
|
+
drawn up by someone who already weighed reversibility, and an argument cancels it silently. Actions outside the list the executor does not gate.
|
|
274
273
|
- **A turn in which the executor admitted a miss does not end until the incident record exists.**
|
|
275
274
|
The incident guard refuses at the turn's end. The records directory is named by the rule's companion, the file name is the date and
|
|
276
275
|
the miss, the form — the layout template. The admission is caught by a set of samples: a miss
|
package/lib/proposals.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,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,SAAS,EAAE,CAUhE;AAED,MAAM,WAAW,KAAK;IAClB,mDAAmD;IACnD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACxB;AAKD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,KAAK,EAAE,CAgBhF;AAED;;;GAGG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAIvE;AAOD,uDAAuD;AACvD,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAuB7E;AAED;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,GAAE,MAAqB,GAAG,MAAM,CAkB7G;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE7C;AAID;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,SAAS,SAAS,EAAE,GAAG,SAAS,MAAM,EAAE,CAUnF;AAED,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,SAAS,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAK/F"}
|
package/lib/proposals.js
CHANGED
|
@@ -200,7 +200,15 @@ export function markSent(text, proposal, url, field = 'отправлено') {
|
|
|
200
200
|
const shift = lines.slice(0, proposal.line).filter((line) => MARKED.test(line)).length;
|
|
201
201
|
// Пометка встаёт сразу под заголовок: конец блока определяется следующим заголовком, а его
|
|
202
202
|
// может и не быть — тогда «конец» пришлось бы искать по пустым строкам в хвосте файла.
|
|
203
|
-
|
|
203
|
+
const mark = `- **${field}:** ${url}`;
|
|
204
|
+
// Блок без цитаты отбивается при каждой отправке: такая же пометка в нём уже стоит, и вторая
|
|
205
|
+
// с той же причиной ничего не добавляет. Блок кончается следующим заголовком.
|
|
206
|
+
const at = proposal.line + shift;
|
|
207
|
+
const end = lines.findIndex((line, index) => index >= at && line.startsWith('## '));
|
|
208
|
+
if (lines.slice(at, end < 0 ? lines.length : end).includes(mark)) {
|
|
209
|
+
return text;
|
|
210
|
+
}
|
|
211
|
+
lines.splice(at, 0, mark);
|
|
204
212
|
return lines.join('\n');
|
|
205
213
|
}
|
|
206
214
|
/**
|
package/lib/proposals.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proposals.js","sourceRoot":"","sources":["../../../projects/agent-kit/src/lib/proposals.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC/E,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAEpC,mEAAmE;AACnE,MAAM,CAAC,MAAM,aAAa,GAAW,0BAA0B,CAAC;AAEhE,yEAAyE;AACzE,MAAM,CAAC,MAAM,UAAU,GAAW,OAAO,CAAC;AAC1C,MAAM,CAAC,MAAM,YAAY,GAAW,WAAW,CAAC;AAChD,MAAM,CAAC,MAAM,OAAO,GAAW,QAAQ,CAAC;AAExC,MAAM,SAAS,GAAsB,CAAC,UAAU,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;AAQzE;;;;;GAKG;AACH,SAAS,SAAS,CAAC,IAAY;IAC3B,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,I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a;IACjC,OAAO,SAAS,KAAK,EAAE,CAAC;AAC5B,CAAC;AAED,MAAM,QAAQ,GAAW,SAAS,CAAC;AAEnC;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAA6B;IAC5D,OAAO;QACH,+BAA+B,OAAO,CAAC,MAAM,EAAE;QAC/C,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAgB,EAAU,EAAE;YACxC,MAAM,GAAG,GAAY,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC/C,MAAM,IAAI,GAAW,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,uEAAuE,CAAC;YAExG,OAAO,KAAK,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,eAAe,KAAK,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;QAC5E,CAAC,CAAC;KACL,CAAC;AACN,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,SAA+B,EAAE,IAAY;IACrF,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAW,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC/C,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;IACtF,CAAC;AACL,CAAC","sourcesContent":["/**\n * Предложения по слою правил: разбор файла, отбор того, что уезжает наружу, и проверка на адрес\n * дерева.\n *\n * Файл пишет главный агент после разбора закрытой задачи — по блоку на предложение, с адресом в\n * заголовке. Адрес роль проставляет и так; здесь он впервые становится тем, что читает машина.\n *\n * Проверка на утечку живёт в этом же модуле не для удобства: предложение уезжает в чужой\n * репозиторий целиком, и запрет называть чужое дерево обязан держаться проверкой, а не памятью\n * того, кто пишет.\n */\nimport { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, join } from 'node:path';\nimport { byText } from './order.js';\n\n/** Куда главный агент кладёт предложения. Путь от корня дерева. */\nexport const PROPOSALS_DIR: string = '.claude/rt-kit/proposals';\n\n/** Адрес предложения: куда правка идёт. Наружу уезжает только первый. */\nexport const TO_PACKAGE: string = 'пакет';\nexport const TO_COMPANION: string = 'компаньон';\nexport const TO_TREE: string = 'дерево';\n\nconst ADDRESSES: readonly string[] = [TO_PACKAGE, TO_COMPANION, TO_TREE];\n\n/** Разобранный заголовок блока. */\ninterface IHeading {\n readonly address: string;\n readonly resource: string;\n}\n\n/**\n * Заголовок блока: `## <адрес> · <ресурс>`. Разделитель — тот же, что в шаблоне.\n *\n * Разбирается строкой, а не образцом: образец на «слово, разделитель, остаток» перебирает\n * границу слова столько раз, сколько в строке знаков.\n */\nfunction headingOf(line: string): IHeading | null {\n if (!line.startsWith('## ')) {\n return null;\n }\n\n const rest: string = line.slice(3);\n const at: number = rest.indexOf('·');\n\n if (at < 0) {\n return null;\n }\n\n const address: string = rest.slice(0, at).trim();\n const resource: string = rest.slice(at + 1).trim();\n\n return address && !address.includes(' ') && resource ? { address, resource } : null;\n}\n\n/** Пометка об отправке. По ней же предложение узнаётся отправленным. */\nconst SENT: RegExp = /^- +\\*\\*отправлено:\\*\\* *(\\S+)/m;\n\n/**\n * Поле ближайшего утверждения: точная цитата строки ресурса, к которой блок относится, — либо\n * слово о том, что ближайшего нет вовсе.\n *\n * Поле обязательно, и обязательно оно затем, чтобы ресурс был прочитан. Мерить похожесть текстов\n * пробовали замером: законное соседство двух статей одного правила дало 0.345 общих значимых\n * слов, а законный перенос удачной статьи на соседнее место — 0.355. Порога между ними нет, и\n * назначенный наугад он отбивал бы правки вместо повторов. Названная цитата судится фактом: она\n * в ресурсе либо есть, либо её там нет.\n */\nconst NEAREST: RegExp = /^- +\\*\\*ближайшее:\\*\\* *([^\\n]+)/m;\n\n/**\n * Слово о том, что ближайшего утверждения в ресурсе нет: цитировать нечего.\n *\n * Конец слова здесь проверяется отрицательным просмотром, а не границей слова: границу движок\n * считает по латинице и цифрам, и между «т» и пробелом её нет вовсе — образец с `\\b` не совпал\n * бы ни с одним русским словом.\n */\nconst NOTHING_NEAR: RegExp = /^нет(?![а-яё])/i;\n\n/**\n * Цитата ближайшего утверждения: кавычки-ёлочки, как в остальных текстах дерева.\n *\n * Ищется позициями, а не образцом: образец на «открыть, набрать не-закрывающих, закрыть» линтер\n * отбивает как ветвящийся, и поводы у него есть — строка без закрывающей кавычки перебирается им\n * до конца.\n */\nfunction quotedIn(text: string): string {\n const from: number = text.indexOf('«');\n const to: number = from < 0 ? -1 : text.indexOf('»', from + 1);\n\n return from >= 0 && to > from ? text.slice(from + 1, to) : '';\n}\n\n/** Пометка любого рода: по ней считается сдвиг, когда в файл вставляют ещё одну. */\nconst MARKED: RegExp = /^- +\\*\\*(отправлено|отбито):\\*\\*/m;\n\nexport interface IProposal {\n readonly address: string;\n readonly resource: string;\n /** Тело блока без заголовка: место, повод и готовый текст. */\n readonly body: string;\n /** Ссылка на заведённую запись; пусто — не отправлялось. */\n readonly sent: string;\n /** Поле ближайшего утверждения, как его написали; пусто — поля нет вовсе. */\n readonly nearest: string;\n /** Файл, в котором блок лежит, путём от корня дерева. */\n readonly file: string;\n /** Строка заголовка в файле, считая с единицы. */\n readonly line: number;\n}\n\n/**\n * Блоки файла предложений.\n *\n * Незаполненный образец пропускается: в шаблоне ресурс стоит скобками — `rules/<правило>.md`, —\n * и отправить его значило бы завести запись о правке несуществующего файла.\n */\nexport function parseProposals(text: string, file: string): readonly IProposal[] {\n const lines: readonly string[] = text.split('\\n');\n const found: IProposal[] = [];\n let at: number = -1;\n\n const close: (end: number) => void = (end: number): void => {\n if (at < 0) {\n return;\n }\n const heading: IHeading = headingOf(lines[at]) as IHeading;\n const body: string = lines\n .slice(at + 1, end)\n .join('\\n')\n .trim();\n const { address, resource }: IHeading = heading;\n if (ADDRESSES.includes(address) && !resource.includes('<')) {\n found.push({\n address,\n resource,\n body,\n file,\n sent: SENT.exec(body)?.[1] ?? '',\n nearest: (NEAREST.exec(body)?.[1] ?? '').trim(),\n line: at + 1,\n });\n }\n at = -1;\n };\n\n lines.forEach((line: string, index: number): void => {\n if (line.startsWith('## ')) {\n close(index);\n if (headingOf(line) !== null) {\n at = index;\n }\n }\n });\n close(lines.length);\n\n return found;\n}\n\n/** Все файлы предложений дерева, в порядке имён. */\nexport function readProposals(root: string): readonly IProposal[] {\n const dir: string = join(root, PROPOSALS_DIR);\n if (!existsSync(dir)) {\n return [];\n }\n\n return readdirSync(dir)\n .filter((name: string): boolean => name.endsWith('.md'))\n .sort(byText)\n .flatMap((name: string): readonly IProposal[] => parseProposals(readFileSync(join(dir, name), 'utf8'), join(PROPOSALS_DIR, name)));\n}\n\nexport interface ILeak {\n /** Строка блока, считая с единицы от заголовка. */\n readonly line: number;\n readonly text: string;\n readonly why: string;\n}\n\n/** Абсолютный путь машины: он не бывает общим ни для одного дерева, кроме этого. */\nconst ABSOLUTE: RegExp = /(^|[\\s(`'\"])(~\\/|\\/(Users|home|var|opt|srv|mnt)\\/)\\S+/;\n\n/**\n * Что в тексте называет дерево, из которого предложение уезжает.\n *\n * `marks` — имена, которые знает только это дерево: корень, его последнее звено, адрес его\n * удалённого репозитория. Пакет их не угадывает — они приходят доводом с края.\n */\nexport function leaksIn(text: string, marks: readonly string[]): readonly ILeak[] {\n const found: ILeak[] = [];\n\n text.split('\\n').forEach((line: string, index: number): void => {\n if (ABSOLUTE.test(line)) {\n found.push({ line: index + 1, text: line.trim(), why: 'абсолютный путь этой машины' });\n\n return;\n }\n const mark: string | undefined = marks.find((value: string): boolean => Boolean(value) && line.includes(value));\n if (mark) {\n found.push({ line: index + 1, text: line.trim(), why: `имя этого дерева: ${mark}` });\n }\n });\n\n return found;\n}\n\n/**\n * Чем дерево себя выдаёт. Последнее звено пути берётся отдельно от полного: в тексте оно\n * встречается чаще, чем путь целиком.\n */\nexport function marksOf(root: string, remote: string): readonly string[] {\n const name: string = basename(root);\n\n return [root, name, remote].filter(Boolean);\n}\n\n/** Один пробел вместо любой пробельной вереницы: цитата в блоке перенесена по своей ширине. */\nfunction flat(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n\n/** Почему блок не уезжает; пустая строка — уезжает. */\nexport function nearestMissing(proposal: IProposal, assetsDir: string): string {\n if (!proposal.nearest) {\n return 'поля «ближайшее» нет: назови точную строку ресурса, к которой это относится, и то, чего она не покрывает, — либо напиши «нет»';\n }\n if (NOTHING_NEAR.test(proposal.nearest)) {\n return '';\n }\n\n const quoted: string = quotedIn(proposal.nearest);\n if (!quoted) {\n return 'ближайшее названо без цитаты: строка ресурса приводится в кавычках-ёлочках дословно — иначе проверить нечего';\n }\n\n const path: string = join(assetsDir, proposal.resource);\n if (!existsSync(path)) {\n // Ресурса у этого дерева нет — сверять не с чем, и отбивать нечего: блок про ресурс,\n // которого пакет здесь не держит, судится на приёмной стороне.\n return '';\n }\n\n return flat(readFileSync(path, 'utf8')).includes(flat(quoted))\n ? ''\n : `цитаты нет в «${proposal.resource}»: ${flat(quoted).slice(0, 60)}… — либо ресурс не читали, либо утверждение переписано с тех пор`;\n}\n\n/**\n * Пометка об отправке дописывается в блок, а не в конец файла: блоков в файле несколько.\n *\n * Место считается от номера строки заголовка — но номера у всех блоков посчитаны при разборе, до\n * единой вставки, а каждая вставка сдвигает файл на строку вниз. Поэтому к номеру прибавляется\n * число пометок, уже стоящих выше: без этого вторая пометка встаёт на строку выше своего места,\n * пятая — на четыре, то есть посреди готового текста правки, а последнему блоку её не достаётся\n * вовсе, и при следующей отправке он уезжает вторым разом.\n */\nexport function markSent(text: string, proposal: IProposal, url: string, field: string = 'отправлено'): string {\n const lines: string[] = text.split('\\n');\n // Сдвиг считает пометки обоих родов: отбитый блок получает свою, и следующая за ним встала бы\n // строкой выше своего места, если бы её не посчитали.\n const shift: number = lines.slice(0, proposal.line).filter((line: string): boolean => MARKED.test(line)).length;\n // Пометка встаёт сразу под заголовок: конец блока определяется следующим заголовком, а его\n // может и не быть — тогда «конец» пришлось бы искать по пустым строкам в хвосте файла.\n lines.splice(proposal.line + shift, 0, `- **${field}:** ${url}`);\n\n return lines.join('\\n');\n}\n\n/**\n * Значение пометки, которое ставит сама отправка, и его образец.\n *\n * Форма объявлена один раз и рядом: пишет её простановка, читает её вывод о пропущенном, и своя\n * копия у второго разошлась бы с первой молча — блок с настоящей пометкой стал бы «поставленным\n * рукой», а поставленный рукой перестал бы называться.\n */\nexport function ownMark(month: string): string {\n return `приём:${month}`;\n}\n\nconst OWN_MARK: RegExp = /^приём:/;\n\n/**\n * Блоки, которые отбор счёл уже уехавшими, — с их файлом, строкой и значением пометки.\n *\n * Поле пометки читалось по наличию, и значение ей было безразлично: поставленная рукой — а её\n * ставят, заполняя поле по привычке, — она означала «уехало», и блок не ехал никогда. Сухой прогон\n * его тоже не показывал, поэтому снаружи всё выглядело так, будто разборов просто не было.\n *\n * Ноль пропущенных печатается тоже: молчание о пропущенном читается как «пропускать было нечего»,\n * и отличить одно от другого читателю нечем.\n *\n * Пометка не своей формы называется отдельно. Своё значение отправка пишет одной формой —\n * `приём:<месяц>`; всё прочее поставлено рукой, и почти всегда это слово «нет», означающее ровно\n * обратное написанному.\n */\nexport function skippedAsSentLines(skipped: readonly IProposal[]): readonly string[] {\n return [\n `пропущено как отправленное: ${skipped.length}`,\n ...skipped.map((entry: IProposal): string => {\n const own: boolean = OWN_MARK.test(entry.sent);\n const said: string = own ? '' : ' — поставлена рукой: своё значение отправка пишет как «приём:<месяц>»';\n\n return ` ${entry.file}:${entry.line} — пометка «${entry.sent}»${said}`;\n }),\n ];\n}\n\n/** Пометка об отправке: по ней предложение второй раз не уезжает. */\nexport function markProposals(root: string, proposals: readonly IProposal[], mark: string): void {\n for (const proposal of proposals) {\n const path: string = join(root, proposal.file);\n writeFileSync(path, markSent(readFileSync(path, 'utf8'), proposal, mark), 'utf8');\n }\n}\n"]}
|
|
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,KAAK,EAAE,CAAC;AAC5B,CAAC;AAED,MAAM,QAAQ,GAAW,SAAS,CAAC;AAEnC;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAA6B;IAC5D,OAAO;QACH,+BAA+B,OAAO,CAAC,MAAM,EAAE;QAC/C,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,KAAgB,EAAU,EAAE;YACxC,MAAM,GAAG,GAAY,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC/C,MAAM,IAAI,GAAW,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,uEAAuE,CAAC;YAExG,OAAO,KAAK,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,eAAe,KAAK,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;QAC5E,CAAC,CAAC;KACL,CAAC;AACN,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,SAA+B,EAAE,IAAY;IACrF,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAW,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC/C,aAAa,CAAC,IAAI,EAAE,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;IACtF,CAAC;AACL,CAAC","sourcesContent":["/**\n * Предложения по слою правил: разбор файла, отбор того, что уезжает наружу, и проверка на адрес\n * дерева.\n *\n * Файл пишет главный агент после разбора закрытой задачи — по блоку на предложение, с адресом в\n * заголовке. Адрес роль проставляет и так; здесь он впервые становится тем, что читает машина.\n *\n * Проверка на утечку живёт в этом же модуле не для удобства: предложение уезжает в чужой\n * репозиторий целиком, и запрет называть чужое дерево обязан держаться проверкой, а не памятью\n * того, кто пишет.\n */\nimport { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, join } from 'node:path';\nimport { byText } from './order.js';\n\n/** Куда главный агент кладёт предложения. Путь от корня дерева. */\nexport const PROPOSALS_DIR: string = '.claude/rt-kit/proposals';\n\n/** Адрес предложения: куда правка идёт. Наружу уезжает только первый. */\nexport const TO_PACKAGE: string = 'пакет';\nexport const TO_COMPANION: string = 'компаньон';\nexport const TO_TREE: string = 'дерево';\n\nconst ADDRESSES: readonly string[] = [TO_PACKAGE, TO_COMPANION, TO_TREE];\n\n/** Разобранный заголовок блока. */\ninterface IHeading {\n readonly address: string;\n readonly resource: string;\n}\n\n/**\n * Заголовок блока: `## <адрес> · <ресурс>`. Разделитель — тот же, что в шаблоне.\n *\n * Разбирается строкой, а не образцом: образец на «слово, разделитель, остаток» перебирает\n * границу слова столько раз, сколько в строке знаков.\n */\nfunction headingOf(line: string): IHeading | null {\n if (!line.startsWith('## ')) {\n return null;\n }\n\n const rest: string = line.slice(3);\n const at: number = rest.indexOf('·');\n\n if (at < 0) {\n return null;\n }\n\n const address: string = rest.slice(0, at).trim();\n const resource: string = rest.slice(at + 1).trim();\n\n return address && !address.includes(' ') && resource ? { address, resource } : null;\n}\n\n/** Пометка об отправке. По ней же предложение узнаётся отправленным. */\nconst SENT: RegExp = /^- +\\*\\*отправлено:\\*\\* *(\\S+)/m;\n\n/**\n * Поле ближайшего утверждения: точная цитата строки ресурса, к которой блок относится, — либо\n * слово о том, что ближайшего нет вовсе.\n *\n * Поле обязательно, и обязательно оно затем, чтобы ресурс был прочитан. Мерить похожесть текстов\n * пробовали замером: законное соседство двух статей одного правила дало 0.345 общих значимых\n * слов, а законный перенос удачной статьи на соседнее место — 0.355. Порога между ними нет, и\n * назначенный наугад он отбивал бы правки вместо повторов. Названная цитата судится фактом: она\n * в ресурсе либо есть, либо её там нет.\n */\nconst NEAREST: RegExp = /^- +\\*\\*ближайшее:\\*\\* *([^\\n]+)/m;\n\n/**\n * Слово о том, что ближайшего утверждения в ресурсе нет: цитировать нечего.\n *\n * Конец слова здесь проверяется отрицательным просмотром, а не границей слова: границу движок\n * считает по латинице и цифрам, и между «т» и пробелом её нет вовсе — образец с `\\b` не совпал\n * бы ни с одним русским словом.\n */\nconst NOTHING_NEAR: RegExp = /^нет(?![а-яё])/i;\n\n/**\n * Цитата ближайшего утверждения: кавычки-ёлочки, как в остальных текстах дерева.\n *\n * Ищется позициями, а не образцом: образец на «открыть, набрать не-закрывающих, закрыть» линтер\n * отбивает как ветвящийся, и поводы у него есть — строка без закрывающей кавычки перебирается им\n * до конца.\n */\nfunction quotedIn(text: string): string {\n const from: number = text.indexOf('«');\n const to: number = from < 0 ? -1 : text.indexOf('»', from + 1);\n\n return from >= 0 && to > from ? text.slice(from + 1, to) : '';\n}\n\n/** Пометка любого рода: по ней считается сдвиг, когда в файл вставляют ещё одну. */\nconst MARKED: RegExp = /^- +\\*\\*(отправлено|отбито):\\*\\*/m;\n\nexport interface IProposal {\n readonly address: string;\n readonly resource: string;\n /** Тело блока без заголовка: место, повод и готовый текст. */\n readonly body: string;\n /** Ссылка на заведённую запись; пусто — не отправлялось. */\n readonly sent: string;\n /** Поле ближайшего утверждения, как его написали; пусто — поля нет вовсе. */\n readonly nearest: string;\n /** Файл, в котором блок лежит, путём от корня дерева. */\n readonly file: string;\n /** Строка заголовка в файле, считая с единицы. */\n readonly line: number;\n}\n\n/**\n * Блоки файла предложений.\n *\n * Незаполненный образец пропускается: в шаблоне ресурс стоит скобками — `rules/<правило>.md`, —\n * и отправить его значило бы завести запись о правке несуществующего файла.\n */\nexport function parseProposals(text: string, file: string): readonly IProposal[] {\n const lines: readonly string[] = text.split('\\n');\n const found: IProposal[] = [];\n let at: number = -1;\n\n const close: (end: number) => void = (end: number): void => {\n if (at < 0) {\n return;\n }\n const heading: IHeading = headingOf(lines[at]) as IHeading;\n const body: string = lines\n .slice(at + 1, end)\n .join('\\n')\n .trim();\n const { address, resource }: IHeading = heading;\n if (ADDRESSES.includes(address) && !resource.includes('<')) {\n found.push({\n address,\n resource,\n body,\n file,\n sent: SENT.exec(body)?.[1] ?? '',\n nearest: (NEAREST.exec(body)?.[1] ?? '').trim(),\n line: at + 1,\n });\n }\n at = -1;\n };\n\n lines.forEach((line: string, index: number): void => {\n if (line.startsWith('## ')) {\n close(index);\n if (headingOf(line) !== null) {\n at = index;\n }\n }\n });\n close(lines.length);\n\n return found;\n}\n\n/** Все файлы предложений дерева, в порядке имён. */\nexport function readProposals(root: string): readonly IProposal[] {\n const dir: string = join(root, PROPOSALS_DIR);\n if (!existsSync(dir)) {\n return [];\n }\n\n return readdirSync(dir)\n .filter((name: string): boolean => name.endsWith('.md'))\n .sort(byText)\n .flatMap((name: string): readonly IProposal[] => parseProposals(readFileSync(join(dir, name), 'utf8'), join(PROPOSALS_DIR, name)));\n}\n\nexport interface ILeak {\n /** Строка блока, считая с единицы от заголовка. */\n readonly line: number;\n readonly text: string;\n readonly why: string;\n}\n\n/** Абсолютный путь машины: он не бывает общим ни для одного дерева, кроме этого. */\nconst ABSOLUTE: RegExp = /(^|[\\s(`'\"])(~\\/|\\/(Users|home|var|opt|srv|mnt)\\/)\\S+/;\n\n/**\n * Что в тексте называет дерево, из которого предложение уезжает.\n *\n * `marks` — имена, которые знает только это дерево: корень, его последнее звено, адрес его\n * удалённого репозитория. Пакет их не угадывает — они приходят доводом с края.\n */\nexport function leaksIn(text: string, marks: readonly string[]): readonly ILeak[] {\n const found: ILeak[] = [];\n\n text.split('\\n').forEach((line: string, index: number): void => {\n if (ABSOLUTE.test(line)) {\n found.push({ line: index + 1, text: line.trim(), why: 'абсолютный путь этой машины' });\n\n return;\n }\n const mark: string | undefined = marks.find((value: string): boolean => Boolean(value) && line.includes(value));\n if (mark) {\n found.push({ line: index + 1, text: line.trim(), why: `имя этого дерева: ${mark}` });\n }\n });\n\n return found;\n}\n\n/**\n * Чем дерево себя выдаёт. Последнее звено пути берётся отдельно от полного: в тексте оно\n * встречается чаще, чем путь целиком.\n */\nexport function marksOf(root: string, remote: string): readonly string[] {\n const name: string = basename(root);\n\n return [root, name, remote].filter(Boolean);\n}\n\n/** Один пробел вместо любой пробельной вереницы: цитата в блоке перенесена по своей ширине. */\nfunction flat(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n\n/** Почему блок не уезжает; пустая строка — уезжает. */\nexport function nearestMissing(proposal: IProposal, assetsDir: string): string {\n if (!proposal.nearest) {\n return 'поля «ближайшее» нет: назови точную строку ресурса, к которой это относится, и то, чего она не покрывает, — либо напиши «нет»';\n }\n if (NOTHING_NEAR.test(proposal.nearest)) {\n return '';\n }\n\n const quoted: string = quotedIn(proposal.nearest);\n if (!quoted) {\n return 'ближайшее названо без цитаты: строка ресурса приводится в кавычках-ёлочках дословно — иначе проверить нечего';\n }\n\n const path: string = join(assetsDir, proposal.resource);\n if (!existsSync(path)) {\n // Ресурса у этого дерева нет — сверять не с чем, и отбивать нечего: блок про ресурс,\n // которого пакет здесь не держит, судится на приёмной стороне.\n return '';\n }\n\n return flat(readFileSync(path, 'utf8')).includes(flat(quoted))\n ? ''\n : `цитаты нет в «${proposal.resource}»: ${flat(quoted).slice(0, 60)}… — либо ресурс не читали, либо утверждение переписано с тех пор`;\n}\n\n/**\n * Пометка об отправке дописывается в блок, а не в конец файла: блоков в файле несколько.\n *\n * Место считается от номера строки заголовка — но номера у всех блоков посчитаны при разборе, до\n * единой вставки, а каждая вставка сдвигает файл на строку вниз. Поэтому к номеру прибавляется\n * число пометок, уже стоящих выше: без этого вторая пометка встаёт на строку выше своего места,\n * пятая — на четыре, то есть посреди готового текста правки, а последнему блоку её не достаётся\n * вовсе, и при следующей отправке он уезжает вторым разом.\n */\nexport function markSent(text: string, proposal: IProposal, url: string, field: string = 'отправлено'): string {\n const lines: string[] = text.split('\\n');\n // Сдвиг считает пометки обоих родов: отбитый блок получает свою, и следующая за ним встала бы\n // строкой выше своего места, если бы её не посчитали.\n const shift: number = lines.slice(0, proposal.line).filter((line: string): boolean => MARKED.test(line)).length;\n // Пометка встаёт сразу под заголовок: конец блока определяется следующим заголовком, а его\n // может и не быть — тогда «конец» пришлось бы искать по пустым строкам в хвосте файла.\n const mark: string = `- **${field}:** ${url}`;\n // Блок без цитаты отбивается при каждой отправке: такая же пометка в нём уже стоит, и вторая\n // с той же причиной ничего не добавляет. Блок кончается следующим заголовком.\n const at: number = proposal.line + shift;\n const end: number = lines.findIndex((line: string, index: number): boolean => index >= at && line.startsWith('## '));\n if (lines.slice(at, end < 0 ? lines.length : end).includes(mark)) {\n return text;\n }\n lines.splice(at, 0, mark);\n\n return lines.join('\\n');\n}\n\n/**\n * Значение пометки, которое ставит сама отправка, и его образец.\n *\n * Форма объявлена один раз и рядом: пишет её простановка, читает её вывод о пропущенном, и своя\n * копия у второго разошлась бы с первой молча — блок с настоящей пометкой стал бы «поставленным\n * рукой», а поставленный рукой перестал бы называться.\n */\nexport function ownMark(month: string): string {\n return `приём:${month}`;\n}\n\nconst OWN_MARK: RegExp = /^приём:/;\n\n/**\n * Блоки, которые отбор счёл уже уехавшими, — с их файлом, строкой и значением пометки.\n *\n * Поле пометки читалось по наличию, и значение ей было безразлично: поставленная рукой — а её\n * ставят, заполняя поле по привычке, — она означала «уехало», и блок не ехал никогда. Сухой прогон\n * его тоже не показывал, поэтому снаружи всё выглядело так, будто разборов просто не было.\n *\n * Ноль пропущенных печатается тоже: молчание о пропущенном читается как «пропускать было нечего»,\n * и отличить одно от другого читателю нечем.\n *\n * Пометка не своей формы называется отдельно. Своё значение отправка пишет одной формой —\n * `приём:<месяц>`; всё прочее поставлено рукой, и почти всегда это слово «нет», означающее ровно\n * обратное написанному.\n */\nexport function skippedAsSentLines(skipped: readonly IProposal[]): readonly string[] {\n return [\n `пропущено как отправленное: ${skipped.length}`,\n ...skipped.map((entry: IProposal): string => {\n const own: boolean = OWN_MARK.test(entry.sent);\n const said: string = own ? '' : ' — поставлена рукой: своё значение отправка пишет как «приём:<месяц>»';\n\n return ` ${entry.file}:${entry.line} — пометка «${entry.sent}»${said}`;\n }),\n ];\n}\n\n/** Пометка об отправке: по ней предложение второй раз не уезжает. */\nexport function markProposals(root: string, proposals: readonly IProposal[], mark: string): void {\n for (const proposal of proposals) {\n const path: string = join(root, proposal.file);\n writeFileSync(path, markSent(readFileSync(path, 'utf8'), proposal, mark), 'utf8');\n }\n}\n"]}
|
package/lib/ship.d.ts
CHANGED
|
@@ -24,6 +24,15 @@ export interface IShipped {
|
|
|
24
24
|
}
|
|
25
25
|
/** Чем груз уезжает. Двойник в спеке — того же вида. */
|
|
26
26
|
export type TShip = (intake: string, token: string, shipment: IShipment) => Promise<IShipped>;
|
|
27
|
+
/**
|
|
28
|
+
* Что приём сказал о принятом: месяц записи, судьба самой записи и — у предложений — счёт
|
|
29
|
+
* легшего и уже лежавшего.
|
|
30
|
+
*
|
|
31
|
+
* Без счёта строка одинакова и у прогона, привёзшего новое, и у прогона, у которого всё уже
|
|
32
|
+
* лежало: человек читает второе как первое. Приём, счёта не приславший, оставляет строку
|
|
33
|
+
* прежней — так же читаются сводка и разборы, у которых счёта нет вовсе.
|
|
34
|
+
*/
|
|
35
|
+
export declare function accepted(shipped: IShipped): string;
|
|
27
36
|
/** Адрес операции приёма. Косая черта в конце адреса приёма второй не становится. */
|
|
28
37
|
export declare function intakeUrl(intake: string, operation: string): string;
|
|
29
38
|
export declare function readToken(root: string, spoken: string): string;
|
package/lib/ship.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ship.d.ts","sourceRoot":"","sources":["../../../projects/agent-kit/src/lib/ship.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,eAAe,EAAqB,MAAM,YAAY,CAAC;AAEhE;;;GAGG;AACH,eAAO,MAAM,eAAe,EAAE,MAAe,CAAC;AAE9C,4EAA4E;AAC5E,MAAM,WAAW,SAAS;IACtB,gGAAgG;IAChG,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,8EAA8E;IAC9E,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;I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,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAiBxG;;;;;GAKG;AACH,eAAO,MAAM,WAAW,EAAE,QAazB,CAAC"}
|
package/lib/ship.js
CHANGED
|
@@ -17,6 +17,22 @@ import { TREE_TOKEN_HEADER } from './cargo.js';
|
|
|
17
17
|
* умолчания среды, а это минуты: человек, позвавший команду, видит не отказ, а зависший запуск.
|
|
18
18
|
*/
|
|
19
19
|
export const SHIP_TIMEOUT_MS = 15_000;
|
|
20
|
+
/**
|
|
21
|
+
* Что приём сказал о принятом: месяц записи, судьба самой записи и — у предложений — счёт
|
|
22
|
+
* легшего и уже лежавшего.
|
|
23
|
+
*
|
|
24
|
+
* Без счёта строка одинакова и у прогона, привёзшего новое, и у прогона, у которого всё уже
|
|
25
|
+
* лежало: человек читает второе как первое. Приём, счёта не приславший, оставляет строку
|
|
26
|
+
* прежней — так же читаются сводка и разборы, у которых счёта нет вовсе.
|
|
27
|
+
*/
|
|
28
|
+
export function accepted(shipped) {
|
|
29
|
+
if (!shipped.accepted) {
|
|
30
|
+
return 'принято';
|
|
31
|
+
}
|
|
32
|
+
const record = `${shipped.accepted.month}${shipped.accepted.created ? ', запись заведена' : ', запись дописана'}`;
|
|
33
|
+
const added = shipped.accepted.added;
|
|
34
|
+
return added === undefined ? record : `${record}, принято ${added}, уже лежало ${shipped.accepted.known ?? 0}`;
|
|
35
|
+
}
|
|
20
36
|
/** Адрес без косых черт в конце: их считает сам вызывающий, а не движок разбора образцов. */
|
|
21
37
|
function withoutTrailingSlash(address) {
|
|
22
38
|
let end = address.length;
|
package/lib/ship.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ship.js","sourceRoot":"","sources":["../../../projects/agent-kit/src/lib/ship.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,S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I,EAAE,CAAC;IAEzC,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACnI,CAAC,CAAC","sourcesContent":["/**\n * Отправка груза в приём: единственное место пакета, которое ходит в сеть.\n *\n * Ходит оно только по команде человека — ни один гард в сеть не ходит вовсе. Вынесено отдельно,\n * чтобы сборка груза осталась проверяемой: спека подставляет двойник и никуда не стучится.\n *\n * Груз уезжает в закрытый приём, а не в открытую очередь работ: сводка говорит о рабочих\n * привычках команды — чем пользуются, обо что спотыкаются, сколько раз признавали промах, — и в\n * открытой очереди это выложено всему свету.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\n\nimport { IIntakeAccepted, TREE_TOKEN_HEADER } from './cargo.js';\n\n/**\n * Предел ожидания приёма. Без него молчащая — не отказавшая — служба держит отправку до\n * умолчания среды, а это минуты: человек, позвавший команду, видит не отказ, а зависший запуск.\n */\nexport const SHIP_TIMEOUT_MS: number = 15_000;\n\n/** Что уезжает одним запросом: род груза словом, операция приёма и тело. */\nexport interface IShipment {\n /** Род груза словами — его называет отказ: дерево шлёт три рода и должно знать, какой отбит. */\n readonly kind: string;\n /** Последнее звено адреса операции: `summary`, `proposals`, `postmortems`. */\n readonly operation: string;\n readonly body: unknown;\n}\n\n/** Чем кончился один запрос. Отказ — такой же ответ, как принятое: его печатает вызывающий. */\nexport interface IShipped {\n readonly ok: boolean;\n /** Код ответа. Ноль — приём не ответил вовсе: не дозвонились, оборвалось, вышло время. */\n readonly status: number;\n /** Что сказал приём. У неотвеченного запроса — причина, по которой он не состоялся. */\n readonly said: string;\n /** Дерево и месяц записи. Пусто у отказа: приём их называет только у принятого груза. */\n readonly accepted: IIntakeAccepted | null;\n}\n\n/** Чем груз уезжает. Двойник в спеке — того же вида. */\nexport type TShip = (intake: string, token: string, shipment: IShipment) => Promise<IShipped>;\n\n/** Адрес без косых черт в конце: их считает сам вызывающий, а не движок разбора образцов. */\nfunction withoutTrailingSlash(address: string): string {\n let end: number = address.length;\n\n while (end > 0 && address[end - 1] === '/') {\n end -= 1;\n }\n\n return address.slice(0, end);\n}\n\n/** Адрес операции приёма. Косая черта в конце адреса приёма второй не становится. */\nexport function intakeUrl(intake: string, operation: string): string {\n return `${withoutTrailingSlash(intake)}/api/intake/${operation}`;\n}\n\n/**\n * Токен дерева из файла, названного настройкой.\n *\n * Путь читается и от корня дерева, и от домашнего каталога: токен обязан лежать вне дерева —\n * конфиг коммитится, а токен переживать историю не должен. Файла нет — пустая строка, и отказ\n * об этом скажет словами.\n */\nfunction tokenFile(root: string, spoken: string): string {\n if (spoken.startsWith('~/')) {\n return join(homedir(), spoken.slice(2));\n }\n\n return isAbsolute(spoken) ? spoken : join(root, spoken);\n}\n\nexport function readToken(root: string, spoken: string): string {\n if (!spoken) {\n return '';\n }\n\n // Абсолютный путь берётся как есть: склеенный с корнем, он ищет токен внутри дерева, где\n // его нет, и отправка отказывает с текстом о ненайденном файле.\n const path: string = tokenFile(root, spoken);\n\n return existsSync(path) ? readFileSync(path, 'utf8').trim() : '';\n}\n\n/** Число из ответа приёма. Не число — пусто: поля есть только у предложений и не у всякого приёма. */\nfunction countOf(said: Record<string, unknown>, field: string): number | undefined {\n return typeof said[field] === 'number' ? said[field] : undefined;\n}\n\n/** Дерево и месяц из ответа приёма. Ответ не тем — пусто: своё устройство приём не пересказывает. */\nfunction acceptedOf(text: string): IIntakeAccepted | null {\n try {\n const said: Record<string, unknown> = JSON.parse(text) as Record<string, unknown>;\n\n return typeof said['tree'] === 'string' && typeof said['month'] === 'string'\n ? {\n tree: said['tree'],\n month: said['month'],\n created: said['created'] === true,\n added: countOf(said, 'added'),\n known: countOf(said, 'known'),\n }\n : null;\n } catch {\n return null;\n }\n}\n\n/** Что сказал приём: его собственное сообщение, а если тело не разбирается — тело как приехало. */\nfunction saidOf(text: string): string {\n try {\n const said: Record<string, unknown> = JSON.parse(text) as Record<string, unknown>;\n\n return typeof said['message'] === 'string' ? said['message'] : text.trim();\n } catch {\n return text.trim();\n }\n}\n\n/** Запрос приёма. Токен уезжает заголовком и в теле не появляется ни разу. */\nexport const httpShip: TShip = async (intake: string, token: string, shipment: IShipment): Promise<IShipped> => {\n let answer: Response;\n\n try {\n answer = await fetch(intakeUrl(intake, shipment.operation), {\n method: 'POST',\n headers: { 'content-type': 'application/json', [TREE_TOKEN_HEADER]: token },\n body: JSON.stringify(shipment.body),\n signal: AbortSignal.timeout(SHIP_TIMEOUT_MS),\n });\n } catch (error: unknown) {\n return { ok: false, status: 0, said: (error as Error).message, accepted: null };\n }\n\n const text: string = await answer.text();\n\n return { ok: answer.ok, status: answer.status, said: saidOf(text), accepted: answer.ok ? acceptedOf(text) : null };\n};\n\n/** Два числа и отбитые строки из ответа приёма. Ответ не тем — пусто. */\n\n/** Запрос правки состояния. Токен уезжает заголовком и в теле не появляется ни разу. */\n\n/** Сколько записей просить одной страницей: столько же приём отдаёт наибольшей страницей. */\nconst OWN_PAGE_SIZE: number = 100;\n\n/** Одна своя запись, как её отдаёт приём. */\nexport interface IOwnRecord {\n readonly id: string;\n /** Род записи словом приёма: предложение либо разбор происшествия. */\n readonly kind: string;\n /** Чем запись названа: имя файла у разбора, имя ресурса у предложения. */\n readonly name: string;\n readonly state: string;\n readonly fixNote: string | null;\n readonly releaseVersion: string | null;\n readonly text: string;\n}\n\n/** Чем кончилось чтение своих записей. Отказ — такой же ответ, как страница: его печатает вызывающий. */\nexport interface IOwnRead {\n readonly ok: boolean;\n readonly status: number;\n readonly said: string;\n readonly rows: readonly IOwnRecord[];\n readonly total: number;\n}\n\n/** Чем читаются свои записи. Двойник в спеке — того же вида. */\nexport type TReadOwn = (intake: string, token: string, kind: string, page: number) => Promise<IOwnRead>;\n\n/** Записи и их число из ответа приёма. Ответ не тем — пустая страница. */\nfunction ownRowsOf(text: string): { rows: readonly IOwnRecord[]; total: number } {\n try {\n const said: Record<string, unknown> = JSON.parse(text) as Record<string, unknown>;\n const rows: unknown = said['rows'];\n\n return {\n rows: Array.isArray(rows) ? (rows as readonly IOwnRecord[]) : [],\n total: typeof said['total'] === 'number' ? said['total'] : 0,\n };\n } catch {\n return { rows: [], total: 0 };\n }\n}\n\n/**\n * Запрос своих записей. Токен уезжает заголовком и в строке запроса не появляется ни разу.\n *\n * Дерево в запросе не называется: приём берёт его из токена, и довод с именем дерева отдал бы\n * записи соседа тому, кто попросит.\n */\nexport const httpReadOwn: TReadOwn = async (intake: string, token: string, kind: string, page: number): Promise<IOwnRead> => {\n const url: string = `${intakeUrl(intake, 'mine')}?kind=${encodeURIComponent(kind)}&page=${page}&size=${OWN_PAGE_SIZE}`;\n let answer: Response;\n\n try {\n answer = await fetch(url, { headers: { [TREE_TOKEN_HEADER]: token }, signal: AbortSignal.timeout(SHIP_TIMEOUT_MS) });\n } catch (error: unknown) {\n return { ok: false, status: 0, said: (error as Error).message, rows: [], total: 0 };\n }\n\n const text: string = await answer.text();\n\n return { ok: answer.ok, status: answer.status, said: saidOf(text), ...(answer.ok ? ownRowsOf(text) : { rows: [], total: 0 }) };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"ship.js","sourceRoot":"","sources":["../../../projects/agent-kit/src/lib/ship.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE7C,OAAO,EAAmB,iBAAiB,EAAE,MAAM,YAAY,CA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MAAM,KAAK,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,EAAE,CAAC,iBAAiB,CAAC,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,CAAC;IACzH,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACtB,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAG,KAAe,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;IACxF,CAAC;IAED,MAAM,IAAI,GAAW,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;IAEzC,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACnI,CAAC,CAAC","sourcesContent":["/**\n * Отправка груза в приём: единственное место пакета, которое ходит в сеть.\n *\n * Ходит оно только по команде человека — ни один гард в сеть не ходит вовсе. Вынесено отдельно,\n * чтобы сборка груза осталась проверяемой: спека подставляет двойник и никуда не стучится.\n *\n * Груз уезжает в закрытый приём, а не в открытую очередь работ: сводка говорит о рабочих\n * привычках команды — чем пользуются, обо что спотыкаются, сколько раз признавали промах, — и в\n * открытой очереди это выложено всему свету.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\n\nimport { IIntakeAccepted, TREE_TOKEN_HEADER } from './cargo.js';\n\n/**\n * Предел ожидания приёма. Без него молчащая — не отказавшая — служба держит отправку до\n * умолчания среды, а это минуты: человек, позвавший команду, видит не отказ, а зависший запуск.\n */\nexport const SHIP_TIMEOUT_MS: number = 15_000;\n\n/** Что уезжает одним запросом: род груза словом, операция приёма и тело. */\nexport interface IShipment {\n /** Род груза словами — его называет отказ: дерево шлёт три рода и должно знать, какой отбит. */\n readonly kind: string;\n /** Последнее звено адреса операции: `summary`, `proposals`, `postmortems`. */\n readonly operation: string;\n readonly body: unknown;\n}\n\n/** Чем кончился один запрос. Отказ — такой же ответ, как принятое: его печатает вызывающий. */\nexport interface IShipped {\n readonly ok: boolean;\n /** Код ответа. Ноль — приём не ответил вовсе: не дозвонились, оборвалось, вышло время. */\n readonly status: number;\n /** Что сказал приём. У неотвеченного запроса — причина, по которой он не состоялся. */\n readonly said: string;\n /** Дерево и месяц записи. Пусто у отказа: приём их называет только у принятого груза. */\n readonly accepted: IIntakeAccepted | null;\n}\n\n/** Чем груз уезжает. Двойник в спеке — того же вида. */\nexport type TShip = (intake: string, token: string, shipment: IShipment) => Promise<IShipped>;\n\n/**\n * Что приём сказал о принятом: месяц записи, судьба самой записи и — у предложений — счёт\n * легшего и уже лежавшего.\n *\n * Без счёта строка одинакова и у прогона, привёзшего новое, и у прогона, у которого всё уже\n * лежало: человек читает второе как первое. Приём, счёта не приславший, оставляет строку\n * прежней — так же читаются сводка и разборы, у которых счёта нет вовсе.\n */\nexport function accepted(shipped: IShipped): string {\n if (!shipped.accepted) {\n return 'принято';\n }\n\n const record: string = `${shipped.accepted.month}${shipped.accepted.created ? ', запись заведена' : ', запись дописана'}`;\n const added: number | undefined = shipped.accepted.added;\n\n return added === undefined ? record : `${record}, принято ${added}, уже лежало ${shipped.accepted.known ?? 0}`;\n}\n\n/** Адрес без косых черт в конце: их считает сам вызывающий, а не движок разбора образцов. */\nfunction withoutTrailingSlash(address: string): string {\n let end: number = address.length;\n\n while (end > 0 && address[end - 1] === '/') {\n end -= 1;\n }\n\n return address.slice(0, end);\n}\n\n/** Адрес операции приёма. Косая черта в конце адреса приёма второй не становится. */\nexport function intakeUrl(intake: string, operation: string): string {\n return `${withoutTrailingSlash(intake)}/api/intake/${operation}`;\n}\n\n/**\n * Токен дерева из файла, названного настройкой.\n *\n * Путь читается и от корня дерева, и от домашнего каталога: токен обязан лежать вне дерева —\n * конфиг коммитится, а токен переживать историю не должен. Файла нет — пустая строка, и отказ\n * об этом скажет словами.\n */\nfunction tokenFile(root: string, spoken: string): string {\n if (spoken.startsWith('~/')) {\n return join(homedir(), spoken.slice(2));\n }\n\n return isAbsolute(spoken) ? spoken : join(root, spoken);\n}\n\nexport function readToken(root: string, spoken: string): string {\n if (!spoken) {\n return '';\n }\n\n // Абсолютный путь берётся как есть: склеенный с корнем, он ищет токен внутри дерева, где\n // его нет, и отправка отказывает с текстом о ненайденном файле.\n const path: string = tokenFile(root, spoken);\n\n return existsSync(path) ? readFileSync(path, 'utf8').trim() : '';\n}\n\n/** Число из ответа приёма. Не число — пусто: поля есть только у предложений и не у всякого приёма. */\nfunction countOf(said: Record<string, unknown>, field: string): number | undefined {\n return typeof said[field] === 'number' ? said[field] : undefined;\n}\n\n/** Дерево и месяц из ответа приёма. Ответ не тем — пусто: своё устройство приём не пересказывает. */\nfunction acceptedOf(text: string): IIntakeAccepted | null {\n try {\n const said: Record<string, unknown> = JSON.parse(text) as Record<string, unknown>;\n\n return typeof said['tree'] === 'string' && typeof said['month'] === 'string'\n ? {\n tree: said['tree'],\n month: said['month'],\n created: said['created'] === true,\n added: countOf(said, 'added'),\n known: countOf(said, 'known'),\n }\n : null;\n } catch {\n return null;\n }\n}\n\n/** Что сказал приём: его собственное сообщение, а если тело не разбирается — тело как приехало. */\nfunction saidOf(text: string): string {\n try {\n const said: Record<string, unknown> = JSON.parse(text) as Record<string, unknown>;\n\n return typeof said['message'] === 'string' ? said['message'] : text.trim();\n } catch {\n return text.trim();\n }\n}\n\n/** Запрос приёма. Токен уезжает заголовком и в теле не появляется ни разу. */\nexport const httpShip: TShip = async (intake: string, token: string, shipment: IShipment): Promise<IShipped> => {\n let answer: Response;\n\n try {\n answer = await fetch(intakeUrl(intake, shipment.operation), {\n method: 'POST',\n headers: { 'content-type': 'application/json', [TREE_TOKEN_HEADER]: token },\n body: JSON.stringify(shipment.body),\n signal: AbortSignal.timeout(SHIP_TIMEOUT_MS),\n });\n } catch (error: unknown) {\n return { ok: false, status: 0, said: (error as Error).message, accepted: null };\n }\n\n const text: string = await answer.text();\n\n return { ok: answer.ok, status: answer.status, said: saidOf(text), accepted: answer.ok ? acceptedOf(text) : null };\n};\n\n/** Два числа и отбитые строки из ответа приёма. Ответ не тем — пусто. */\n\n/** Запрос правки состояния. Токен уезжает заголовком и в теле не появляется ни разу. */\n\n/** Сколько записей просить одной страницей: столько же приём отдаёт наибольшей страницей. */\nconst OWN_PAGE_SIZE: number = 100;\n\n/** Одна своя запись, как её отдаёт приём. */\nexport interface IOwnRecord {\n readonly id: string;\n /** Род записи словом приёма: предложение либо разбор происшествия. */\n readonly kind: string;\n /** Чем запись названа: имя файла у разбора, имя ресурса у предложения. */\n readonly name: string;\n readonly state: string;\n readonly fixNote: string | null;\n readonly releaseVersion: string | null;\n readonly text: string;\n}\n\n/** Чем кончилось чтение своих записей. Отказ — такой же ответ, как страница: его печатает вызывающий. */\nexport interface IOwnRead {\n readonly ok: boolean;\n readonly status: number;\n readonly said: string;\n readonly rows: readonly IOwnRecord[];\n readonly total: number;\n}\n\n/** Чем читаются свои записи. Двойник в спеке — того же вида. */\nexport type TReadOwn = (intake: string, token: string, kind: string, page: number) => Promise<IOwnRead>;\n\n/** Записи и их число из ответа приёма. Ответ не тем — пустая страница. */\nfunction ownRowsOf(text: string): { rows: readonly IOwnRecord[]; total: number } {\n try {\n const said: Record<string, unknown> = JSON.parse(text) as Record<string, unknown>;\n const rows: unknown = said['rows'];\n\n return {\n rows: Array.isArray(rows) ? (rows as readonly IOwnRecord[]) : [],\n total: typeof said['total'] === 'number' ? said['total'] : 0,\n };\n } catch {\n return { rows: [], total: 0 };\n }\n}\n\n/**\n * Запрос своих записей. Токен уезжает заголовком и в строке запроса не появляется ни разу.\n *\n * Дерево в запросе не называется: приём берёт его из токена, и довод с именем дерева отдал бы\n * записи соседа тому, кто попросит.\n */\nexport const httpReadOwn: TReadOwn = async (intake: string, token: string, kind: string, page: number): Promise<IOwnRead> => {\n const url: string = `${intakeUrl(intake, 'mine')}?kind=${encodeURIComponent(kind)}&page=${page}&size=${OWN_PAGE_SIZE}`;\n let answer: Response;\n\n try {\n answer = await fetch(url, { headers: { [TREE_TOKEN_HEADER]: token }, signal: AbortSignal.timeout(SHIP_TIMEOUT_MS) });\n } catch (error: unknown) {\n return { ok: false, status: 0, said: (error as Error).message, rows: [], total: 0 };\n }\n\n const text: string = await answer.text();\n\n return { ok: answer.ok, status: answer.status, said: saidOf(text), ...(answer.ok ? ownRowsOf(text) : { rows: [], total: 0 }) };\n};\n"]}
|