@tduyng/pi-autoresearch 0.0.0-stage → 0.0.2
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/LICENSE +178 -0
- package/README.md +111 -2
- package/package.json +44 -4
- package/src/command.ts +158 -0
- package/src/digest.ts +136 -0
- package/src/experiment.ts +648 -0
- package/src/finalize.ts +245 -0
- package/src/format.ts +118 -0
- package/src/frontmatter.ts +225 -0
- package/src/git.ts +232 -0
- package/src/index.ts +450 -0
- package/src/kickoff.md +57 -0
- package/src/log.ts +251 -0
- package/src/pending.ts +76 -0
- package/src/session.ts +190 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
Use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 tduyng
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tduyng/pi-autoresearch
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An autonomous experiment loop for pi that costs nothing until you type `/autoresearch`.
|
|
4
|
+
Two tools and one log. The model reads the benchmark, decides keep or discard, and the tools do the
|
|
5
|
+
bookkeeping: commit, revert, scope, script hash, noise floor, and one line of context back.
|
|
6
|
+
|
|
7
|
+
## Cold start
|
|
8
|
+
|
|
9
|
+
Nothing is registered at load: no tool, no skill, no system prompt block. The extension adds one slash
|
|
10
|
+
command. The tools are registered and declared to the model only when `/autoresearch` runs, and removed on
|
|
11
|
+
`off`, `clear`, or when `max_runs` is reached.
|
|
12
|
+
|
|
13
|
+
## The loop
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
edit -> run_experiment -> read the output -> log_experiment -> repeat
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`run_experiment` snapshots the working tree, runs `.auto/measure.sh`, parses `METRIC name=value` lines, runs
|
|
20
|
+
the optional checks, and returns the output, the metrics, the changed files, the noise advice, and the
|
|
21
|
+
scope violations. It does not touch git history.
|
|
22
|
+
|
|
23
|
+
`log_experiment` takes `status: keep | discard | crash | checks_failed` and the model's reasoning in `asi`.
|
|
24
|
+
A `keep` commits the files the run touched with a conventional subject built from the description. Every
|
|
25
|
+
other status restores those files. A run inside the noise band, a crash, or a scope violation is reported,
|
|
26
|
+
not auto-decided: the model chooses.
|
|
27
|
+
|
|
28
|
+
## What it adds over the usual loop
|
|
29
|
+
|
|
30
|
+
| Mechanism | Why |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| Model owns keep or discard | a rule cannot know whether the diff caused the gain, or whether simpler code is worth 1% |
|
|
33
|
+
| Full benchmark output | phase timings and errors reach the model, so the next hypothesis comes from data |
|
|
34
|
+
| Noise floor from median absolute deviation | advice that separates jitter from a real win; confidence never overrides the model |
|
|
35
|
+
| Pending measurement | one run between the two tools, crash-safe on disk, so a restart can still log it |
|
|
36
|
+
| Scope globs in frontmatter | a keep cannot touch files outside the declared scope |
|
|
37
|
+
| Benchmark script hash | editing the benchmark to move the number voids the comparison; `/autoresearch rebaseline` starts a new segment |
|
|
38
|
+
| Worktree lock and dirty baseline | one loop per worktree, and files another session left dirty are never committed or reverted |
|
|
39
|
+
| Finalize in temporary worktrees | kept runs become branches without moving HEAD under another session |
|
|
40
|
+
| Compaction digest from disk | the prompt body, recent runs, dead ends and ideas survive a context reset, no LLM call |
|
|
41
|
+
| Conventional commits | `type(scope): summary`, at most 72 characters, one `Metric:` trailer, built by the tool from validated parts |
|
|
42
|
+
| Lazy tool registration | zero tokens at cold start |
|
|
43
|
+
|
|
44
|
+
## Files
|
|
45
|
+
|
|
46
|
+
`.auto/prompt.md` carries the frontmatter and the objective:
|
|
47
|
+
|
|
48
|
+
```markdown
|
|
49
|
+
---
|
|
50
|
+
name: vitest startup
|
|
51
|
+
metric: total_ms
|
|
52
|
+
unit: ms
|
|
53
|
+
direction: lower
|
|
54
|
+
command: bash .auto/measure.sh
|
|
55
|
+
scope: [vitest.config.ts, test/**]
|
|
56
|
+
max_runs: 40
|
|
57
|
+
min_gain: 0.5
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
What is optimized, the constraints, and what a good change looks like.
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`min_gain` is the smallest relative improvement the advice treats as real, in percent. It never blocks a keep.
|
|
64
|
+
|
|
65
|
+
| File | Purpose |
|
|
66
|
+
| --- | --- |
|
|
67
|
+
| `.auto/prompt.md` | frontmatter config plus the objective and what has been tried |
|
|
68
|
+
| `.auto/measure.sh` | benchmark, prints `METRIC name=value` |
|
|
69
|
+
| `.auto/log.jsonl` | append-only record |
|
|
70
|
+
| `.auto/checks.sh` | optional correctness checks, run after a passing benchmark |
|
|
71
|
+
| `.auto/ideas.md` | optional backlog of ideas not tried yet |
|
|
72
|
+
| `.auto/pending.json` | the run waiting for a decision |
|
|
73
|
+
| `.auto/lock.json` | the session that owns this worktree |
|
|
74
|
+
|
|
75
|
+
`.auto/` is added to the repository's common `.git/info/exclude` on the first run, so none of it lands in a
|
|
76
|
+
commit, including from a linked worktree.
|
|
77
|
+
|
|
78
|
+
Run it in an interactive pi session or through RPC. `pi -p` exits as soon as the slash command returns,
|
|
79
|
+
before the loop's first turn, so a print run cannot drive the loop.
|
|
80
|
+
|
|
81
|
+
## Commands
|
|
82
|
+
|
|
83
|
+
| Command | Effect |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `/autoresearch <goal>` | start a session, or resume the one in `.auto/` |
|
|
86
|
+
| `/autoresearch status` | print the digest |
|
|
87
|
+
| `/autoresearch off` | stop and remove the tools |
|
|
88
|
+
| `/autoresearch rebaseline` | accept a changed benchmark script as a new baseline |
|
|
89
|
+
| `/autoresearch finalize` | split kept runs into independent branches from the merge-base |
|
|
90
|
+
| `/autoresearch clear` | delete the log and stop |
|
|
91
|
+
|
|
92
|
+
`finalize` groups kept runs by file overlap and creates one branch per group from the merge-base in
|
|
93
|
+
temporary worktrees. The current worktree is never checked out to another branch. It verifies that the
|
|
94
|
+
union of the branches matches the original branch before reporting.
|
|
95
|
+
|
|
96
|
+
## Worktrees and other sessions
|
|
97
|
+
|
|
98
|
+
One loop owns a worktree at a time. `/autoresearch` takes `.auto/lock.json`, and a second session in the same
|
|
99
|
+
worktree is refused before it can run anything. Files that were already dirty when the loop started are
|
|
100
|
+
recorded in the lock and never committed or reverted.
|
|
101
|
+
|
|
102
|
+
For a second loop on the same repository, use a separate git worktree. Each worktree has its own `.auto/`,
|
|
103
|
+
its own branch, and its own log. The first run on trunk creates `autoresearch/<name>-<timestamp>` in a git
|
|
104
|
+
worktree at `~/worktrees/<repo>/autoresearch-<name>-<timestamp>`, and the shared checkout stays on trunk. Start
|
|
105
|
+
pi in that directory to run the loop. An existing feature branch is used as it is.
|
|
106
|
+
|
|
107
|
+
## Compaction and restarts
|
|
108
|
+
|
|
109
|
+
While the loop is active, `session_before_compact` replaces pi's LLM summary with a deterministic digest
|
|
110
|
+
built from `.auto/`: the prompt body, the recent runs, kept runs, dead ends, ideas, and any pending
|
|
111
|
+
measurement. After a restart of the same session, the loop re-arms from the session's activation entry and
|
|
112
|
+
sends one short resume message. A fresh session never auto-activates.
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tduyng/pi-autoresearch",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Autonomous experiment loop with zero cold-start cost: measure, decide, commit or revert, with scope and benchmark guards.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi",
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"pi-coding-agent",
|
|
10
|
+
"autoresearch",
|
|
11
|
+
"experiment",
|
|
12
|
+
"optimization",
|
|
13
|
+
"benchmark"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-autoresearch#readme",
|
|
16
|
+
"bugs": "https://gitlab.com/tduyng/pi-agent/-/issues",
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
|
+
"author": "tduyng",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://gitlab.com/tduyng/pi-agent.git",
|
|
22
|
+
"directory": "extensions/pi-autoresearch"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"!src/**/*.test.ts",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@earendil-works/pi-ai": "*",
|
|
33
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"pi": {
|
|
39
|
+
"extensions": [
|
|
40
|
+
"./src/index.ts"
|
|
41
|
+
]
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"ata-validator": "^1.62.1"
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/command.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { randomBytes } from 'node:crypto'
|
|
3
|
+
import * as fs from 'node:fs'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import * as path from 'node:path'
|
|
6
|
+
|
|
7
|
+
const RETAINED_BYTES = 128 * 1024
|
|
8
|
+
const TEMP_FILE_THRESHOLD_BYTES = 128 * 1024
|
|
9
|
+
const TEMP_FILE_LIMIT_BYTES = 20 * 1024 * 1024
|
|
10
|
+
const TAIL_LINES = 40
|
|
11
|
+
const TICK_MS = 5000
|
|
12
|
+
|
|
13
|
+
export interface CommandResult {
|
|
14
|
+
exitCode: number | null
|
|
15
|
+
timedOut: boolean
|
|
16
|
+
seconds: number
|
|
17
|
+
output: string
|
|
18
|
+
tail: string
|
|
19
|
+
totalBytes: number
|
|
20
|
+
fullOutputPath: string | null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface CommandOptions {
|
|
24
|
+
cwd: string
|
|
25
|
+
timeoutSeconds: number
|
|
26
|
+
signal: AbortSignal | undefined
|
|
27
|
+
onTick: ((seconds: number) => void) | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface Capture {
|
|
31
|
+
chunks: Buffer[]
|
|
32
|
+
retainedBytes: number
|
|
33
|
+
totalBytes: number
|
|
34
|
+
fullOutputPath: string | null
|
|
35
|
+
stream: fs.WriteStream | null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function killTree(pid: number): void {
|
|
39
|
+
try {
|
|
40
|
+
process.kill(-pid, 'SIGTERM')
|
|
41
|
+
} catch {
|
|
42
|
+
try {
|
|
43
|
+
process.kill(pid, 'SIGTERM')
|
|
44
|
+
} catch {
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function tempFilePath(): string {
|
|
51
|
+
return path.join(tmpdir(), `pi-autoresearch-${randomBytes(6).toString('hex')}.log`)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function retain(capture: Capture, data: Buffer): void {
|
|
55
|
+
capture.chunks.push(data)
|
|
56
|
+
capture.retainedBytes += data.length
|
|
57
|
+
while (capture.retainedBytes > RETAINED_BYTES && capture.chunks.length > 1) {
|
|
58
|
+
const removed = capture.chunks.shift()
|
|
59
|
+
if (removed === undefined) break
|
|
60
|
+
capture.retainedBytes -= removed.length
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function startStream(capture: Capture): void {
|
|
65
|
+
capture.fullOutputPath = tempFilePath()
|
|
66
|
+
capture.stream = fs.createWriteStream(capture.fullOutputPath)
|
|
67
|
+
for (const chunk of capture.chunks) capture.stream.write(chunk)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function writeFull(capture: Capture, data: Buffer): void {
|
|
71
|
+
if (capture.stream === null) return
|
|
72
|
+
if (capture.totalBytes > TEMP_FILE_LIMIT_BYTES) return
|
|
73
|
+
capture.stream.write(data)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function captureData(capture: Capture, data: Buffer): void {
|
|
77
|
+
capture.totalBytes += data.length
|
|
78
|
+
if (capture.stream === null && capture.totalBytes > TEMP_FILE_THRESHOLD_BYTES) startStream(capture)
|
|
79
|
+
writeFull(capture, data)
|
|
80
|
+
retain(capture, data)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function tailOf(text: string): string {
|
|
84
|
+
return text.split('\n').slice(-TAIL_LINES).join('\n').trim()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function runCommand(command: string, options: CommandOptions): Promise<CommandResult> {
|
|
88
|
+
return new Promise<CommandResult>((resolve, reject) => {
|
|
89
|
+
const started = Date.now()
|
|
90
|
+
const capture: Capture = {
|
|
91
|
+
chunks: [],
|
|
92
|
+
retainedBytes: 0,
|
|
93
|
+
totalBytes: 0,
|
|
94
|
+
fullOutputPath: null,
|
|
95
|
+
stream: null
|
|
96
|
+
}
|
|
97
|
+
let timedOut = false
|
|
98
|
+
const child = spawn('bash', ['-c', command], {
|
|
99
|
+
cwd: options.cwd,
|
|
100
|
+
detached: true,
|
|
101
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
const finishStream = (): void => {
|
|
105
|
+
if (capture.stream !== null) capture.stream.end()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const tick = setInterval(() => {
|
|
109
|
+
if (options.onTick === undefined) return
|
|
110
|
+
options.onTick((Date.now() - started) / 1000)
|
|
111
|
+
}, TICK_MS)
|
|
112
|
+
|
|
113
|
+
const timeout =
|
|
114
|
+
options.timeoutSeconds > 0
|
|
115
|
+
? setTimeout(() => {
|
|
116
|
+
timedOut = true
|
|
117
|
+
if (child.pid !== undefined) killTree(child.pid)
|
|
118
|
+
}, options.timeoutSeconds * 1000)
|
|
119
|
+
: null
|
|
120
|
+
|
|
121
|
+
const onAbort = (): void => {
|
|
122
|
+
if (child.pid !== undefined) killTree(child.pid)
|
|
123
|
+
else child.kill()
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (options.signal !== undefined) {
|
|
127
|
+
if (options.signal.aborted) onAbort()
|
|
128
|
+
else options.signal.addEventListener('abort', onAbort, { once: true })
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
child.stdout?.on('data', (data: Buffer) => captureData(capture, data))
|
|
132
|
+
child.stderr?.on('data', (data: Buffer) => captureData(capture, data))
|
|
133
|
+
|
|
134
|
+
child.on('error', (error: Error) => {
|
|
135
|
+
clearInterval(tick)
|
|
136
|
+
if (timeout !== null) clearTimeout(timeout)
|
|
137
|
+
finishStream()
|
|
138
|
+
reject(error)
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
child.on('close', (code: number | null) => {
|
|
142
|
+
clearInterval(tick)
|
|
143
|
+
if (timeout !== null) clearTimeout(timeout)
|
|
144
|
+
if (options.signal !== undefined) options.signal.removeEventListener('abort', onAbort)
|
|
145
|
+
finishStream()
|
|
146
|
+
const text = Buffer.concat(capture.chunks).toString('utf8')
|
|
147
|
+
resolve({
|
|
148
|
+
exitCode: code,
|
|
149
|
+
timedOut,
|
|
150
|
+
seconds: (Date.now() - started) / 1000,
|
|
151
|
+
output: text,
|
|
152
|
+
tail: tailOf(text),
|
|
153
|
+
totalBytes: capture.totalBytes,
|
|
154
|
+
fullOutputPath: capture.fullOutputPath
|
|
155
|
+
})
|
|
156
|
+
})
|
|
157
|
+
})
|
|
158
|
+
}
|
package/src/digest.ts
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { ResearchConfig } from './frontmatter.js'
|
|
2
|
+
import {
|
|
3
|
+
baselineMetric,
|
|
4
|
+
bestMetric,
|
|
5
|
+
confidence,
|
|
6
|
+
deadEndHypotheses,
|
|
7
|
+
lastRun,
|
|
8
|
+
noiseFloor,
|
|
9
|
+
runsInSegment,
|
|
10
|
+
runsWithoutGain,
|
|
11
|
+
type LogState,
|
|
12
|
+
type Run
|
|
13
|
+
} from './log.js'
|
|
14
|
+
import { formatMetric, formatPercent, truncateAtWord } from './format.js'
|
|
15
|
+
|
|
16
|
+
const MAX_DIGEST_CHARS = 5000
|
|
17
|
+
const KEPT_LIMIT = 5
|
|
18
|
+
const DEAD_END_LIMIT = 15
|
|
19
|
+
const RECENT_LIMIT = 24
|
|
20
|
+
const LINE_LIMIT = 80
|
|
21
|
+
const BODY_LIMIT = 1400
|
|
22
|
+
const IDEAS_LIMIT = 800
|
|
23
|
+
|
|
24
|
+
export interface DigestExtras {
|
|
25
|
+
body?: string
|
|
26
|
+
ideas?: string
|
|
27
|
+
pending?: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function counts(state: LogState): string {
|
|
31
|
+
const runs = runsInSegment(state)
|
|
32
|
+
const kept = runs.filter((run) => run.status === 'keep').length
|
|
33
|
+
const crashed = runs.filter((run) => run.status === 'crash' || run.status === 'checks_failed').length
|
|
34
|
+
const discarded = runs.length - kept - crashed
|
|
35
|
+
const parts = [`${kept} keep`, `${discarded} discard`]
|
|
36
|
+
if (crashed > 0) parts.push(`${crashed} crash`)
|
|
37
|
+
return parts.join(', ')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function runLine(run: Run, baseline: number | null, unit: string): string {
|
|
41
|
+
const delta = baseline === null ? '' : ` ${formatPercent(run.metric, baseline)}`
|
|
42
|
+
return `#${run.run} ${run.status} ${formatMetric(run.metric, unit)}${delta} ${truncateAtWord(run.description, LINE_LIMIT)}`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function keptRuns(state: LogState): readonly Run[] {
|
|
46
|
+
const kept = runsInSegment(state).filter((run) => run.status === 'keep')
|
|
47
|
+
return kept.slice(-KEPT_LIMIT).toReversed()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function recentRuns(state: LogState): readonly Run[] {
|
|
51
|
+
return runsInSegment(state).slice(-RECENT_LIMIT)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function deadEndLine(state: LogState): string {
|
|
55
|
+
const hypotheses = deadEndHypotheses(state, DEAD_END_LIMIT).map((hypothesis) =>
|
|
56
|
+
truncateAtWord(hypothesis, LINE_LIMIT)
|
|
57
|
+
)
|
|
58
|
+
return hypotheses.length === 0 ? 'none yet' : hypotheses.join(' | ')
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function buildDigest(
|
|
62
|
+
state: LogState,
|
|
63
|
+
config: ResearchConfig | null,
|
|
64
|
+
scriptChanged: boolean,
|
|
65
|
+
extras: DigestExtras = {}
|
|
66
|
+
): string {
|
|
67
|
+
const unit = config?.unit ?? state.config?.metricUnit ?? ''
|
|
68
|
+
const metricName = config?.metric ?? state.config?.metricName ?? 'metric'
|
|
69
|
+
const direction = config?.direction ?? state.config?.bestDirection ?? 'lower'
|
|
70
|
+
const baseline = baselineMetric(state)
|
|
71
|
+
const best = bestMetric(state)
|
|
72
|
+
const floor = noiseFloor(state)
|
|
73
|
+
const score = confidence(state)
|
|
74
|
+
const runs = runsInSegment(state)
|
|
75
|
+
const last = lastRun(state)
|
|
76
|
+
const budget = config?.maxRuns ?? 0
|
|
77
|
+
const remaining = budget > 0 ? Math.max(0, budget - runs.length) : null
|
|
78
|
+
|
|
79
|
+
const lines = [
|
|
80
|
+
'# Autoresearch digest (generated from .auto, not an LLM summary)',
|
|
81
|
+
`goal: ${config?.name ?? state.config?.name ?? 'autoresearch'}`,
|
|
82
|
+
`metric: ${metricName} (${direction} is better) | baseline ${baseline === null ? '-' : formatMetric(baseline, unit)} | best ${best === null ? '-' : formatMetric(best, unit)}${best === null || baseline === null ? '' : ` (${formatPercent(best, baseline)})`}`,
|
|
83
|
+
`noise: ${floor === null ? 'not enough runs' : `+/-${formatMetric(floor, unit)}`} | confidence ${score === null ? '-' : `${score.toFixed(1)}x`} | benchmark script ${scriptChanged ? 'CHANGED since baseline' : 'unchanged'}`,
|
|
84
|
+
`runs: ${runs.length}${budget > 0 ? ` of ${budget} (${remaining} left)` : ''} | ${counts(state)}${extras.pending === true ? ' | a measurement is pending' : ''}`,
|
|
85
|
+
''
|
|
86
|
+
]
|
|
87
|
+
if (extras.body !== undefined && extras.body.trim().length > 0) {
|
|
88
|
+
lines.push(`rules and objective:\n${truncateAtWord(extras.body.trim(), BODY_LIMIT)}`, '')
|
|
89
|
+
}
|
|
90
|
+
if (extras.ideas !== undefined && extras.ideas.trim().length > 0) {
|
|
91
|
+
lines.push(`ideas not tried:\n${truncateAtWord(extras.ideas.trim(), IDEAS_LIMIT)}`, '')
|
|
92
|
+
}
|
|
93
|
+
lines.push(
|
|
94
|
+
`kept: ${keptRuns(state).map((run) => runLine(run, baseline, unit)).join(' | ') || 'none yet'}`,
|
|
95
|
+
`dead ends: ${deadEndLine(state)}`,
|
|
96
|
+
`recent runs:\n${recentRuns(state).map((run) => runLine(run, baseline, unit)).join('\n') || 'none'}`,
|
|
97
|
+
`last: ${last === null ? 'none' : runLine(last, baseline, unit)}`,
|
|
98
|
+
`you decide keep or discard. The noise floor and confidence are advice. Next: one hypothesis, edit, run_experiment, read the output, log_experiment.`
|
|
99
|
+
)
|
|
100
|
+
return lines.join('\n').slice(0, MAX_DIGEST_CHARS)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function buildResumeMessage(state: LogState, pending: boolean): string {
|
|
104
|
+
if (pending) {
|
|
105
|
+
return 'A measured run is pending. Call log_experiment with keep or discard now, then continue the loop.'
|
|
106
|
+
}
|
|
107
|
+
const runs = runsInSegment(state)
|
|
108
|
+
if (runs.length === 0) {
|
|
109
|
+
return 'No baseline yet. Call run_experiment, read the output, then log_experiment with status keep.'
|
|
110
|
+
}
|
|
111
|
+
const best = bestMetric(state)
|
|
112
|
+
const unit = state.config?.metricUnit ?? ''
|
|
113
|
+
const stuck = runsWithoutGain(state)
|
|
114
|
+
const deadEnds = deadEndHypotheses(state, 4).map((hypothesis) => truncateAtWord(hypothesis, 50))
|
|
115
|
+
const head = `Next iteration: read .auto/prompt.md and the tail of .auto/log.jsonl if you lost context. One hypothesis, edit, run_experiment, then log_experiment with your decision.${best === null ? '' : ` Best ${formatMetric(best, unit)}.`}`
|
|
116
|
+
const hint =
|
|
117
|
+
stuck >= 5 && deadEnds.length > 0
|
|
118
|
+
? ` ${stuck} runs without a gain. Change the mechanism, not the constant. Dead ends: ${deadEnds.join(', ')}. Read the source and profile before the next idea.`
|
|
119
|
+
: ''
|
|
120
|
+
return `${head}${hint}`
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function buildStatusLine(state: LogState, config: ResearchConfig | null): string {
|
|
124
|
+
const unit = config?.unit ?? state.config?.metricUnit ?? ''
|
|
125
|
+
const best = bestMetric(state)
|
|
126
|
+
const baseline = baselineMetric(state)
|
|
127
|
+
const runs = runsInSegment(state).length
|
|
128
|
+
const last = lastRun(state)
|
|
129
|
+
const parts = [`${runs} run${runs === 1 ? '' : 's'}`]
|
|
130
|
+
if (best !== null) {
|
|
131
|
+
parts.push(`best ${formatMetric(best, unit)}`)
|
|
132
|
+
if (baseline !== null && best !== baseline) parts.push(formatPercent(best, baseline))
|
|
133
|
+
}
|
|
134
|
+
if (last !== null) parts.push(`last ${last.status}`)
|
|
135
|
+
return `autoresearch: ${parts.join(' | ')}`
|
|
136
|
+
}
|