@henryqw/pi-pr 9.0.6 → 9.1.1
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-APACHE-2.0 +202 -0
- package/NOTICE.md +24 -0
- package/README.md +39 -3
- package/docs/git-workflows-tested.md +119 -0
- package/extensions/git-commit.ts +132 -0
- package/extensions/pr-command.ts +20 -1
- package/extensions/pr-comment-sweep.ts +4 -3
- package/extensions/pr-create.ts +27 -18
- package/extensions/pr-publish-work.ts +10 -15
- package/extensions/pr.ts +75 -5
- package/package.json +7 -3
- package/skills/git-commit/SKILL.md +18 -0
- package/skills/git-pr/SKILL.md +18 -0
- package/skills/pi-pr-fix-ci/SKILL.md +1 -1
- package/skills/update-from-main/SKILL.md +95 -0
- package/skills/update-from-main/scripts/update_from_main.py +752 -0
- package/skills/update-from-main/scripts/validate.py +17 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Licence scope and source notices
|
|
2
|
+
|
|
3
|
+
This package contains files under two licences. This is not a choice of licence for each file.
|
|
4
|
+
|
|
5
|
+
- The existing pi-pr extension code, package-owned PR skills, and tests use the MIT licence in `LICENSE`.
|
|
6
|
+
- The imported files listed below and their modifications use Apache-2.0. `LICENSE-APACHE-2.0` is an exact copy of the original source licence. These files are not relicensed as MIT.
|
|
7
|
+
|
|
8
|
+
## Imported source
|
|
9
|
+
|
|
10
|
+
Source: Henry Wang's `HenryQW/skills` repository, <https://github.com/HenryQW/skills>.
|
|
11
|
+
The read-only source snapshot inspected for these notices is commit `6857c81611ab8e7aaacf4233452a0841d7df79a9`.
|
|
12
|
+
Each source path below is relative to that repository. Each package path is relative to this package.
|
|
13
|
+
|
|
14
|
+
| Source path | Package path | Modification notice |
|
|
15
|
+
| --- | --- | --- |
|
|
16
|
+
| `git-commit/SKILL.md` | `skills/git-commit/SKILL.md` | Modified for pi-pr: use the shared native scoped commit tool, content/index checks, and uncertain-outcome rules. |
|
|
17
|
+
| `git-pr/SKILL.md` | `skills/git-pr/SKILL.md` | Modified for pi-pr: replace shell publication with bounded native dispatch, explicit base intent, upstream consent, and exact PR reuse. |
|
|
18
|
+
| `update-from-main/SKILL.md` | `skills/update-from-main/SKILL.md` | Modified for pi-pr: packaged helper guidance, bounded check output, exact backup identity, worktree ownership, and retained-backup recovery after success or failure. |
|
|
19
|
+
| `update-from-main/scripts/update_from_main.py` | `skills/update-from-main/scripts/update_from_main.py` | Modified for pi-pr: add collision/race regressions, identify the backup by a unique reflog message, record its owner in per-worktree refs, and apply its exact OID without popping or dropping it. |
|
|
20
|
+
| `update-from-main/scripts/validate.py` | `skills/update-from-main/scripts/validate.py` | Copied validator; added the source, licence, and modification notice header. |
|
|
21
|
+
|
|
22
|
+
The source snapshot has no separate `NOTICE` file and no file-specific copyright notice in these five files. The full original Apache licence, including its appendix, is preserved unchanged. Attribution to the source author and repository is retained here. The unrelated source `agents/openai.yaml` files were not imported.
|
|
23
|
+
|
|
24
|
+
These notices do not change the existing MIT licence for the package-owned code. The package manifest uses `(MIT AND Apache-2.0)` to describe the combined distribution. This notice and both licence files are included in the packed package.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# `@henryqw/pi-pr`
|
|
2
2
|
|
|
3
|
-
See the current branch pull request in the Pi footer. Run `/pr`
|
|
3
|
+
See the current branch pull request in the Pi footer. Run `/pr` for the full PR lifecycle, or ask the agent to commit local work or create/update a PR without authorizing repair or merge.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -27,11 +27,16 @@ Run `/pr` in a GitHub checkout. It reads fresh local and GitHub state, takes the
|
|
|
27
27
|
| Surface | Type | Purpose |
|
|
28
28
|
| --- | --- | --- |
|
|
29
29
|
| `/pr` | command | Human entry point; inspect and act on the current branch's pull request. |
|
|
30
|
+
| `pi_git_commit` | tool | Agent-only local inspection and scoped commits; never pushes. |
|
|
31
|
+
| `pi_git_pr` | tool | Agent-only PR creation/publication; no feedback, CI repair, base rebase, or merge. |
|
|
30
32
|
| `pi_pr_create` | tool | Agent-only guarded creation steps selected by `/pr`. |
|
|
31
33
|
| `pi_pr_fix_ci` | tool | Agent-only guarded GitHub Actions repair. |
|
|
32
34
|
| `pi_pr_publish_work` | tool | Agent-only scoped local work publication. |
|
|
33
35
|
| `pi_pr_sweep` | tool | Agent-only feedback triage and publication. |
|
|
34
36
|
| `pi_pr_update_branch` | tool | Agent-only conflict rebase and publication. |
|
|
37
|
+
| `git-commit` | skill | Agent guidance for standalone scoped Conventional Commits. |
|
|
38
|
+
| `git-pr` | skill | Agent guidance for authorized PR creation or publication. |
|
|
39
|
+
| `update-from-main` | skill | Agent guidance and Python helper for merging exact fetched `origin/main`. |
|
|
35
40
|
| `pi-pr-comment-sweep` | skill | Agent guidance for review feedback. |
|
|
36
41
|
| `pi-pr-create` | skill | Agent guidance for creating a pull request. |
|
|
37
42
|
| `pi-pr-fix-ci` | skill | Agent guidance for failed GitHub Actions. |
|
|
@@ -40,9 +45,40 @@ Run `/pr` in a GitHub checkout. It reads fresh local and GitHub state, takes the
|
|
|
40
45
|
| Footer | ui | Linked PR number and plain-language status. |
|
|
41
46
|
| Widget | ui | Action hint or transient routing status. |
|
|
42
47
|
|
|
43
|
-
`/pr` accepts no flags, prose, or base argument.
|
|
48
|
+
`/pr` accepts no flags, prose, or base argument. For the full lifecycle, start with the command. For a create/update-only request, the agent reads `git-pr` and calls `pi_git_pr`. Both entries establish session-local authority for the same helpers; a direct `pi_pr_*` call cannot establish it. The helper run is bound to the current session and worktree. Its agent tools use plain-object parameter schemas so providers that omit root-union tools can expose them; action-specific arguments are still checked before the workflow runs.
|
|
44
49
|
|
|
45
|
-
The `pi_pr_*` tools are model-only and run one action at a time. Codemode scripts and other tools cannot call them, so a script cannot batch guarded actions or filter the result the model needs for its next safety decision. With `codemode.mode` set to `only`, Pi hides other tools behind `codemode` but keeps these declared, so `/pr` workflows still work.
|
|
50
|
+
The `pi_git_*` and `pi_pr_*` tools are model-only and run one action at a time. Codemode scripts and other tools cannot call them, so a script cannot batch guarded actions or filter the result the model needs for its next safety decision. With `codemode.mode` set to `only`, Pi hides other tools behind `codemode` but keeps these declared, so `/pr` workflows still work.
|
|
51
|
+
|
|
52
|
+
### Local commits and bounded PR publication
|
|
53
|
+
|
|
54
|
+
Ask the agent to commit a scoped change. `git-commit` resolves an explicit local target, the PR base, or the repository default branch. `pi_git_commit` inspects that target and pending work, then commits only reviewed paths. It requires an existing commit and an attached branch. It never fetches, pushes, amends, bypasses hooks, or changes Git configuration.
|
|
55
|
+
|
|
56
|
+
Ask the agent to create or update a PR. `pi_git_pr` permits creation, local publication, and local sync onto the proven PR head. It stops before feedback, CI repair, base rebase, CI waiting, and merge. Local sync can fast-forward or rebase local commits onto the PR head, but not onto the base. Existing PRs retain their base, title, and body, including an exact-head PR that appears between push and publication. The tool never retargets them. An explicit `base` must match the existing PR base or the configured/default creation base. To select another creation base, explicitly authorize the branch's repository-local `gh-merge-base` setting first.
|
|
57
|
+
|
|
58
|
+
An inferred target requires specific permission to configure this repository's branch upstream. Without it, the tool stops before linking or creation. `allowUpstream: true` records this consent for one invocation; it never permits global configuration changes. It is not required for an already configured target.
|
|
59
|
+
|
|
60
|
+
All commit callers use the same literal-path staging and commit parent/tree checks. Standalone, creation, and local-publication inspections also detect file-byte and index changes even when Git status letters stay the same. Unrelated staging, partial staging, `.context/`, and common secret filenames block a commit. Filename checks cannot detect every secret: the agent must inspect content and ownership. Hooks run normally. An uncertain commit or push must not be replayed without checking its actual outcome.
|
|
61
|
+
|
|
62
|
+
### Agent arguments
|
|
63
|
+
|
|
64
|
+
- `pi_git_commit`: `{ action: "inspect", target: "<local-ref-or-OID>" }` returns `inspectionId`, `head`, `targetOid`, `mergeBase`, and `paths`. Then use `{ action: "commit", inspectionId: "<returned-ID>", ownedPaths: ["<exact-path>"], message: "fix: <subject>" }`. A successful commit returns `head` and consumes the inspection. Inspect again for another coherent group. Subjects are limited to 72 characters; bodies and footers are allowed.
|
|
65
|
+
- `pi_git_pr`: `{ base?: "<exact-base-ref>", allowUpstream?: true }`. Omit `base` when the user gave no explicit base. Set `allowUpstream` only after specific consent. The result has `nextStep` and can include a proven `url`, `blocker`, or `handoff`. With `handoff`, end the turn: native settlement loads the reserved package skill with its run ID. Do not guess IDs or start another PR entry. Authorization continues across handoffs, but expires when the invocation ends.
|
|
66
|
+
|
|
67
|
+
### Standalone merge from main
|
|
68
|
+
|
|
69
|
+
Ask to update the current branch from main. `update-from-main` runs its packaged Python helper once. It requires Python 3.9 or newer and Git with `fetch --porcelain`. Unlike the `/pr` base-update route, this helper **merges**, not rebases. It fetches before local mutation and uses the exact OID from fetch output. It backs up tracked and untracked changes; when ignored paths collide with the source tree, the backup also includes ignored files. It never pushes.
|
|
70
|
+
|
|
71
|
+
Each backup has a unique Git reflog message, so another linked worktree's stash push cannot change its identity. Before it stashes, the helper records ownership in the per-worktree ref `refs/worktree/update-from-main/pending/<token>`, then replaces it with `refs/worktree/update-from-main/backup` at the captured OID. Restoration always applies the captured OID with `--index`. The helper never pops or drops a stash. Backups stay retained after success as well as conflict, hook, or submodule failures.
|
|
72
|
+
|
|
73
|
+
A retained backup blocks further runs only in the worktree that owns it, also after a branch switch; other worktrees can update. Report the backup OID, and restore from it rather than from a later `origin/main`. After the user verifies restored bytes and staging and explicitly asks, complete recovery with `git update-ref -d refs/worktree/update-from-main/backup <oid>`. This keeps the stash entry. An interrupted run leaves the `pending` ref and blocks its worktree until recovery. Backups from earlier helper versions have no recorded owner and block every worktree until the user drops them or the confirmed owner adopts them; adoption keeps the stash entry. Removing a worktree removes its ownership refs but not its stash entries. See the packaged `update-from-main` skill for the exact recovery and adoption commands.
|
|
74
|
+
|
|
75
|
+
### Local acceptance checks
|
|
76
|
+
|
|
77
|
+
From this source checkout, run `pnpm --filter @henryqw/pi-pr test:git-workflows`. It uses existing Node tests, temporary real Git repositories, and controlled GitHub responses, with no live GitHub writes. See [executed cases and independent acceptance instructions](./docs/git-workflows-tested.md) for the commands, tested boundaries, and limits.
|
|
78
|
+
|
|
79
|
+
### Licences
|
|
80
|
+
|
|
81
|
+
Existing pi-pr code uses MIT. The imported `git-commit`, `git-pr`, and `update-from-main` skills and the Python helper/validator use Apache-2.0, including their modifications. See [licence scope, source identity, and modification notices](./NOTICE.md). Both licence files are included in the package.
|
|
46
82
|
|
|
47
83
|
## Flow
|
|
48
84
|
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# Git workflow consolidation checks
|
|
2
|
+
|
|
3
|
+
## Candidate and scope
|
|
4
|
+
|
|
5
|
+
The candidate includes checkpoints `36008cb0c6fabf94e7d8ddee3c2b302c8fffd121` and `8506d67ce276138b213ab42637cb6afae9eb2322`, applied in that order, then the completion changes. This report covers checks run in `/Users/henry/Git/pi-harness/.worktrees/subagent-46a5a4b61cc1fd6e8b66ea3a`.
|
|
6
|
+
|
|
7
|
+
- `pi_git_commit` is the standalone local entry. Creation, local publication, and feedback commits share literal-path staging and parent/tree checks. CI guidance uses the standalone commit entry with the captured PR head as its target.
|
|
8
|
+
- `git-pr` now calls `pi_git_pr`, not a second shell workflow or a request to run `/pr`. Its authorization permits creation, local publication, and sync onto the PR head. It excludes feedback, CI repair, base rebase, CI waiting, and merge. `/pr` retains its full lifecycle.
|
|
9
|
+
- `update-from-main` remains a standalone merge of the exact fetched OID. Recovery keeps backups. The original `/Users/henry/Git/skills` sources stayed read-only during isolated validation. Source retirement is a separate step after Main acceptance.
|
|
10
|
+
- The package manifest publishes all eight skills and their helpers. The root local manifest also declares the same skill directory. `@henryqw/pi-pr` moves from `9.0.3` to `9.1.0` for the new callable workflows and skills. No other package needs a release.
|
|
11
|
+
|
|
12
|
+
## Executed cases
|
|
13
|
+
|
|
14
|
+
| Check | Actual coverage |
|
|
15
|
+
| --- | --- |
|
|
16
|
+
| `git-commit.test.ts` | Real temporary Git repositories: local-only commits, coherent groups, literal filenames, message bodies, remaining unrelated work, coherent staged renames/deletions, unrelated staging, partial staging, same-status byte drift, branch movement, active Git operations, context/secret paths, cancellation, failed hooks, lost successful responses, and hooks that change the committed tree. Uncertain attempts cannot replay. |
|
|
17
|
+
| Creation and local-publication tests | Shared byte/index inspection and staging, rename scope, clean verification, exact captured OID and lease, frozen checks, failed checks, divergent local commits, and consumed uncertain commits/pushes. Creation tests also cover explicit base match/mismatch, PR reuse, upstream recovery, and title/body races. Git mutation cases use temporary repositories or strict command mocks; GitHub responses are controlled. |
|
|
18
|
+
| Feedback sweep tests | Real temporary Git repositories with controlled GitHub responses: scope and authority checks, preserved partial staging, literal add/delete paths, exact parent/tree recovery, and lost-response reconciliation. Existing recovery, feedback, validation, and resolution tests remain active. |
|
|
19
|
+
| `pr-native.test.ts` | Native `AgentSession`, `ExtensionRunner`, and settlement methods: hidden skill dispatch, no editable queue guidance, full-lifecycle continuation, bounded create/publication handoff without UI, and no unauthorized feedback continuation. Workflow bodies and GitHub discovery are controlled in these tests. |
|
|
20
|
+
| `native source Git tools` in `pr.test.ts` | Registered source tools with real commit/publication helpers in a temporary repository. Standalone commit does not push; explicit base mismatch stops; active PR authority blocks a second commit entry; native settlement supplies the package skill; validation and exact-lease/OID publication write only a local bare repository; a merge-ready PR is not merged. GitHub discovery and repository identity are controlled responses, not live API reads. |
|
|
21
|
+
| Merge helper self-test | Real temporary repositories: a merge with staged/untracked restoration, tracked stash conflict, untracked and ignored upstream-path collisions, ignored newline filenames, merge-conflict recovery using the captured OID after upstream advances, retained-backup rerun rejection, fetch failure before local mutation, tracking-ref movement after fetch, up-to-date/main/detached refusal, dirty submodule restoration, required submodule update recovery, and failed merge-hook recovery. Only fetch lock-race responses and tracking-ref movement are injected. |
|
|
22
|
+
| Installed Pi resource probe | Pi `1.0.2` `DefaultPackageManager.resolveExtensionSources` and `loadSkills` resolve the package and root local manifests. Both return the extension entry and all eight skills, with no skill diagnostics. The probe uses in-memory settings and a temporary agent directory; it does not load models or write user configuration. |
|
|
23
|
+
|
|
24
|
+
## Fixes and check history
|
|
25
|
+
|
|
26
|
+
The checkpoint baseline passed 426 package tests, the feedback self-test, and the copied Python validator. This worker did not rely on the prior worker's reported 129 focused tests.
|
|
27
|
+
|
|
28
|
+
The source commit tool did not trigger the documented presentation refresh: the event handler recognized only shell commits. It now refreshes after a successful `pi_git_commit` commit, but not inspection or failure. The existing projection test covers this boundary.
|
|
29
|
+
|
|
30
|
+
A real Git probe also found that `git add -A -- old.txt new.txt` fails with exit 128 after a staged rename: the old path is already absent from the index. The shared staging helper now leaves fully staged paths unchanged and adds only unstaged/untracked selected paths. It still rejects unrelated and partially staged work first. Real cases cover complete staged renames in standalone, creation, and publication commits, plus staged deletion in standalone and sweep commits.
|
|
31
|
+
|
|
32
|
+
Added cases also establish same-status byte-drift rejection in both PR inspection callers, partial-stage preservation in the sweep, untracked collision backup preservation in the merge helper, and a registered-tool commit/publication exercise. No merge algorithm or PR lease/recovery path was replaced.
|
|
33
|
+
|
|
34
|
+
During development, typecheck rejected an unsafe test-only boundary-entry access. The test now checks the entry before reading its content. The first source-tool probe expected the wrong no-action notification text; that redundant assertion was removed. These were test defects, not successful workflow claims. The four focused Git cases then passed.
|
|
35
|
+
|
|
36
|
+
Checks on the previous candidate `6a4d39d`, before the independent review corrections (these are not revision rerun results):
|
|
37
|
+
|
|
38
|
+
| Command | Result |
|
|
39
|
+
| --- | --- |
|
|
40
|
+
| `pnpm --filter @henryqw/pi-pr test` | Exit 0: 428 Node tests, feedback self-test, and merge helper self-test passed. |
|
|
41
|
+
| `pnpm --filter @henryqw/pi-pr typecheck` | Exit 0. |
|
|
42
|
+
| `python3 extensions/pi-pr/skills/update-from-main/scripts/validate.py` | Exit 0 on the checkpoint baseline; the final expanded helper also passed through the package test command. |
|
|
43
|
+
| `pnpm run docs:validate` | Exit 0: README structure, 49 docs-related tests, and link checks passed. |
|
|
44
|
+
| `pnpm run check:package-versions` | Exit 0. |
|
|
45
|
+
| `pnpm install --lockfile-only --offline --ignore-scripts` | Exit 0; version/resource edits need no dependency resolution change, so `pnpm-lock.yaml` is unchanged. |
|
|
46
|
+
| `cd extensions/pi-pr && npm pack --dry-run --ignore-scripts --json` | Exit 0: 35 published files at `9.1.0`; an assertion probe confirmed all eight skills, source entry, shared commit helper, both Python scripts, report, and README SVG. No tarball was created. |
|
|
47
|
+
| `git diff --check` | Exit 0. |
|
|
48
|
+
|
|
49
|
+
Output was captured in temporary logs. Success summaries were limited to 20 lines; failure output was limited to 80 lines or 8 KiB. The installed-authority resource probe ran with `node --input-type=module` and imported `DefaultPackageManager`, `SettingsManager`, and `loadSkills` directly from the Pi `1.0.2` path given below.
|
|
50
|
+
|
|
51
|
+
## Independent evidence on the previous candidate
|
|
52
|
+
|
|
53
|
+
The parent supplied the following exact-source acceptance results for the previous tree. This worker has not rerun these independent probes on the revision or inspected raw worker sessions.
|
|
54
|
+
|
|
55
|
+
- First agent: 22 passing tests, including five registered-source guidance probes. These used real local commits, native handoff, checks, and local exact-OID/lease pushes. Commands and saved logs are under `/tmp/pi-git-acceptance-c2e9d284.Y5SPGS`. Its collector rejected valid final ancestry across a custom record; the cases and unchanged identity were recovered from saved evidence. The collector failure is not proof that the native workflow failed.
|
|
56
|
+
- Second agent: four successful subprocess fixtures. Safe evidence is `/tmp/pi-update-main-acceptance.ZXSHb1/report.txt` and `probe-results.json`: partial-index/untracked byte restoration; ignored upstream collision backup; conflict recovery using the original OID after main advanced, with retained-backup rerun refusal; and fetch failure preserving all state. `acceptance.py` exited 1 after the first two cases because macOS `sed` rejected `--`. `resume.py` inspected and continued the same fixture and returned 0; it did not restart or rerun an uncertain merge.
|
|
57
|
+
- The old success result that popped the backup is invalid under the corrected retention policy. These prior fixtures do not prove the new concurrent-stash behavior.
|
|
58
|
+
- The second task overall FAILED because its environment probe disclosed a credential, despite its passing Git fixtures. The parent notified the user. No token value is in the safe reports or fixtures. This revision does not inspect or reproduce credential output and does not change pi-subagent.
|
|
59
|
+
|
|
60
|
+
## Review corrections and revision evidence
|
|
61
|
+
|
|
62
|
+
1. The merge helper no longer captures `refs/stash` after push or checks it before `pop stash@{0}`. Native stash pushes use a unique run message; the helper finds its OID in the native stash reflog. Restoration always uses `git stash apply --index <captured-OID>`. Every backup stays retained after success or failure until verified explicit user removal. Legacy named backups still block another run. Exact fetched-main OID and merge/conflict/hook/submodule recovery are unchanged.
|
|
63
|
+
2. The registered bounded entry passes `preserveExistingMetadata` into the shared creator. An exact-head PR that appears after push is validated for open lifecycle, repository/ref/OID, and base, then reused without edit/create. Full `/pr` keeps its metadata-update behavior. Controlled regressions exercise bounded reuse, full metadata update, and rejection of a different base or head. The entry-boundary test checks that bounded authority reaches the creator.
|
|
64
|
+
3. The package now declares `(MIT AND Apache-2.0)`. `LICENSE` still applies to existing MIT code. `LICENSE-APACHE-2.0` is byte-for-byte equal to the read-only original `/Users/henry/Git/skills/LICENSE`. `NOTICE.md` identifies source commit `6857c81611ab8e7aaacf4233452a0841d7df79a9`, lists the imported paths and modifications, and scopes Apache versus MIT. Each imported skill/helper/validator has a source and modification notice. The source has no separate NOTICE file for these paths. Both licences and the notice are published.
|
|
65
|
+
|
|
66
|
+
The smallest real-Git race regressions use another linked worktree. One inserts its stash push after this helper's push but before backup capture. The other inserts its push immediately before restoration. Both verify partial-index and binary untracked bytes, the original backup OID, the peer backup's OID/content, and two retained stack entries. Legacy-backup refusal and successful-restoration rerun refusal are also checked. No automatic stack deletion is used.
|
|
67
|
+
|
|
68
|
+
Focused commands run on this revision:
|
|
69
|
+
|
|
70
|
+
- `python3 extensions/pi-pr/skills/update-from-main/scripts/validate.py`: exit 0, including both real-Git races and recovery checks.
|
|
71
|
+
- `pnpm --filter @henryqw/pi-pr exec node --test --test-name-pattern='metadata when an exact PR appears|agent PR entry carries base' test/pr-create.test.ts test/pr.test.ts`: initially three cases passed before adding the two mismatched-authority cases; the complete final package run below covers those added cases.
|
|
72
|
+
|
|
73
|
+
Final checks run on this revision:
|
|
74
|
+
|
|
75
|
+
| Command | Result and local log |
|
|
76
|
+
| --- | --- |
|
|
77
|
+
| `pnpm --filter @henryqw/pi-pr test` | Exit 0: 432 Node tests plus feedback and expanded merge self-tests. Log: `/var/folders/6y/58h3_t417xdb67x996096jjr0000gn/T/tmp.jXV17CCNcZ`. |
|
|
78
|
+
| `pnpm --filter @henryqw/pi-pr typecheck` | Exit 0. Log: `/var/folders/6y/58h3_t417xdb67x996096jjr0000gn/T/tmp.vtgSindNDY`. |
|
|
79
|
+
| `pnpm run docs:validate` | Exit 0: structure, 49 docs tests, and link checks. Log: `/var/folders/6y/58h3_t417xdb67x996096jjr0000gn/T/tmp.JW98lXOnhR`. |
|
|
80
|
+
| `pnpm install --lockfile-only --offline --ignore-scripts` | Exit 0; lockfile remains unchanged. Log: `/var/folders/6y/58h3_t417xdb67x996096jjr0000gn/T/tmp.BcSv0ViqC9`. |
|
|
81
|
+
| `pnpm run check:package-versions` | Exit 0. Log: `/var/folders/6y/58h3_t417xdb67x996096jjr0000gn/T/tmp.lTNTARDRvY`. |
|
|
82
|
+
| `cd extensions/pi-pr && npm pack --dry-run --ignore-scripts --json` | Exit 0; 37 files. Assertions verified both licences, NOTICE.md, all eight skills, Python helper/validator, source entries, report and SVG. The Apache licence equals the original bytes. No tarball was created. Log: `/var/folders/6y/58h3_t417xdb67x996096jjr0000gn/T/tmp.jYi8Xk2CQl`. |
|
|
83
|
+
| `git diff --check` | Exit 0. |
|
|
84
|
+
|
|
85
|
+
The release stays `@henryqw/pi-pr@9.1.0`; no other package releases. Main owns root-wide combined validation and final independent acceptance. These revision checks do not rerun the prior independent collectors or fixture scripts. Live GitHub, live models, TUI behavior, and manual backup removal remain untested.
|
|
86
|
+
|
|
87
|
+
## Main acceptance
|
|
88
|
+
|
|
89
|
+
Main accepted and promoted runtime candidate `62711f2643bd73c26d2fe29925e00c758c21df65`, with the same source tree as revision `274695fe84b7da903d998edc3b21d85c2b509651`.
|
|
90
|
+
|
|
91
|
+
- `pnpm --filter @henryqw/pi-pr test:git-workflows`: exit 0 on that exact integration candidate. Log: `/tmp/pi-pr-main-acceptance.zKbmC8`.
|
|
92
|
+
- Guarded final checks: `pnpm test`, `pnpm run docs:validate`, `pnpm run check:package-versions`, `git diff --check`, and `npm pack --dry-run --json` from `extensions/pi-pr` all returned exit 0. The runtime candidate stayed unchanged.
|
|
93
|
+
- The guarded exact-candidate review and the separate final reviewer both returned `PASS`.
|
|
94
|
+
- This section is a report-only update after promotion. It does not claim another model-driven package run, live GitHub write, or replay of the previous independent fixture scripts. Credential replacement and removal of installed standalone skill copies remain user actions.
|
|
95
|
+
|
|
96
|
+
## Independent acceptance entry
|
|
97
|
+
|
|
98
|
+
From the exact candidate checkout, with existing workspace dependencies and Python 3.9+ installed, run:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
log=$(mktemp)
|
|
102
|
+
pnpm --filter @henryqw/pi-pr test:git-workflows >"$log" 2>&1
|
|
103
|
+
rc=$?
|
|
104
|
+
echo "git-workflows exit=$rc log=$log"
|
|
105
|
+
if [ "$rc" -eq 0 ]; then tail -20 "$log"; else tail -80 "$log" | tail -c 8192; fi
|
|
106
|
+
exit "$rc"
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
This entry uses the existing Node test runner and Python validator, not a new framework. It runs the standalone commit, native dispatch, real local publication, registered source-tool, and merge recovery exercises. Temporary repositories and agent directories are removed. Any unknown GitHub mutation in the source-tool exercise fails the test; the only push destination is its temporary bare repository. No credentials, external repository, model request, or persistent Pi setting is needed.
|
|
110
|
+
|
|
111
|
+
Main can give separate acceptance workers the source `extensions/pi-pr/extensions/pr.ts` and the packaged `skills/git-commit`, `skills/git-pr`, or `skills/update-from-main` guidance. Use only controlled temporary Git/GitHub contexts. Compare the resulting commits, index, backup OIDs, and native handoff with the cases above. Use returned inspection/run IDs, never fabricated authority. Run the helper once per fixture; inspect and restore retained backups rather than rerun. Main owns the independent agent-guidance exercise and source retirement after acceptance.
|
|
112
|
+
|
|
113
|
+
## Limits
|
|
114
|
+
|
|
115
|
+
- Automated native tests use the workspace-pinned Pi `1.0.0` dependency. The installed `1.0.2` authority is `/Users/henry/.pi/agent/install/releases/1.0.2/node_modules/@earendil-works/pi-coding-agent`; its documentation and declarations were inspected, and its resource APIs were probed. Live model-driven use of the packaged tools and TUI behavior were not tested.
|
|
116
|
+
- Controlled GitHub responses test authorization and command boundaries. They do not prove live GitHub authentication, repository policy, network transport, or GitHub Enterprise behavior.
|
|
117
|
+
- A user request and upstream consent are agent guidance requirements; a Boolean tool field cannot prove that a person gave consent. Ownership, secret-content detection, check adequacy, and semantic conflict resolution still need agent/user judgment.
|
|
118
|
+
- The acceptance entry is available for later local runs. Main's exact-candidate acceptance and root-wide checks are recorded above. Package typecheck passed on the revision; no new claim is made for unchanged packages' typechecks.
|
|
119
|
+
- No live GitHub change, external push, npm publication, or persistent user configuration edit was made. Source retirement is permitted only after acceptance; installed standalone copies are not removed automatically.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { createReadStream } from "node:fs";
|
|
3
|
+
import { lstat, readlink } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { spawnBounded, type Exec, type ExecOptions } from "@henryqw/pi-process";
|
|
6
|
+
import { inspectWorktreeState, parseNulPaths, parseStatusSnapshot, readHead, requiredOid, requiredText, runChecked, validatePaths, withWorktreeLock } from "./pr-execution.ts";
|
|
7
|
+
|
|
8
|
+
export type PendingCommit = { head: string; status: string; integrity: string };
|
|
9
|
+
|
|
10
|
+
export function commitPaths(input: string[]): string[] {
|
|
11
|
+
const paths = validatePaths(input, "Commit paths");
|
|
12
|
+
if (!paths.length) throw new Error("Commit paths must not be empty");
|
|
13
|
+
for (const path of paths) {
|
|
14
|
+
const parts = path.split("/");
|
|
15
|
+
if (parts.some((part) => !part || part === "." || part === ".git" || part === ".context") || path.includes("\0")) {
|
|
16
|
+
throw new Error("Commit paths must be canonical and must exclude .git/ and .context/");
|
|
17
|
+
}
|
|
18
|
+
if (parts.some((part) => /^(?:\.env(?:\..*)?|credentials(?:\..*)?|id_(?:rsa|dsa|ecdsa|ed25519)|.*\.(?:pem|key|p12|pfx))$/i.test(part))) {
|
|
19
|
+
throw new Error("Commit paths include a possible secret; remove it from the commit scope");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return paths;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Integrity includes file bytes, symlink targets, modes, and the index, not only status letters. */
|
|
26
|
+
export async function inspectPendingCommit(exec: Exec, options: ExecOptions): Promise<PendingCommit> {
|
|
27
|
+
if (await inspectWorktreeState(exec, options) === "operation") throw new Error("Git operation in progress");
|
|
28
|
+
const head = await readHead(exec, options);
|
|
29
|
+
const status = (await runChecked(exec, "git", ["status", "--porcelain=v2", "-z", "--untracked-files=all"], options)).stdout;
|
|
30
|
+
const hash = createHash("sha256").update(status);
|
|
31
|
+
hash.update((await runChecked(exec, "git", ["diff", "--cached", "--binary", "--no-ext-diff", "--no-textconv"], options)).stdout);
|
|
32
|
+
for (const path of validatePaths([...parseStatusSnapshot(status).keys()], "Pending paths")) {
|
|
33
|
+
const absolute = join(options.cwd, path);
|
|
34
|
+
let stat;
|
|
35
|
+
try { stat = await lstat(absolute); }
|
|
36
|
+
catch (error) {
|
|
37
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") { hash.update("deleted\0"); continue; }
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
hash.update(`${path}\0${stat.mode}\0`);
|
|
41
|
+
if (stat.isSymbolicLink()) hash.update(await readlink(absolute));
|
|
42
|
+
else if (stat.isFile()) for await (const chunk of createReadStream(absolute)) {
|
|
43
|
+
options.signal?.throwIfAborted();
|
|
44
|
+
hash.update(chunk);
|
|
45
|
+
}
|
|
46
|
+
else throw new Error("Pending directories or submodules need a separate ownership decision");
|
|
47
|
+
hash.update("\0");
|
|
48
|
+
}
|
|
49
|
+
return { head, status, integrity: hash.digest("hex") };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function requirePendingCommit(exec: Exec, options: ExecOptions, pending: PendingCommit): Promise<void> {
|
|
53
|
+
const current = await inspectPendingCommit(exec, options);
|
|
54
|
+
if (current.head !== pending.head || current.status !== pending.status || current.integrity !== pending.integrity) {
|
|
55
|
+
throw new Error("Pending work changed after inspection; review it again");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Call under the worktree lock. Never replace unrelated or partially staged work. */
|
|
60
|
+
export async function stageCommitPaths(exec: Exec, options: ExecOptions, input: string[]): Promise<void> {
|
|
61
|
+
const paths = commitPaths(input);
|
|
62
|
+
const staged = parseNulPaths((await runChecked(exec, "git", ["diff", "--cached", "--no-renames", "--name-only", "-z"], options)).stdout, "Staged paths");
|
|
63
|
+
if (staged.some((path) => !paths.includes(path))) throw new Error("Unrelated staged changes require an ownership decision");
|
|
64
|
+
const unstaged = parseNulPaths((await runChecked(exec, "git", ["diff", "--no-renames", "--name-only", "-z"], options)).stdout, "Unstaged paths");
|
|
65
|
+
if (staged.some((path) => unstaged.includes(path))) throw new Error("Partially staged changes require an ownership decision; staging was preserved");
|
|
66
|
+
// Keep coherent staging, including deletions and both sides of a rename. Deleted paths
|
|
67
|
+
// are no longer in the index, so adding them again can fail with an unmatched pathspec.
|
|
68
|
+
const toStage = paths.filter((path) => !staged.includes(path));
|
|
69
|
+
if (toStage.length) await runChecked(exec, "git", ["--literal-pathspecs", "add", "-A", "--", ...toStage], options);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function validateCommitMessage(message: string): void {
|
|
73
|
+
if (typeof message !== "string" || !/^(?:feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\([^\r\n()]+\))?!?: [^\r\n]+(?:\n[\s\S]*)?$/.test(message) || message.split("\n")[0]!.length > 72 || message.length > 16_384 || message.includes("\0")) {
|
|
74
|
+
throw new Error("Use a Conventional Commit message with a subject of at most 72 characters");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function commitStagedPaths(exec: Exec, options: ExecOptions, message: string): Promise<void> {
|
|
79
|
+
validateCommitMessage(message);
|
|
80
|
+
const parent = await readHead(exec, options);
|
|
81
|
+
const tree = requiredOid((await runChecked(exec, "git", ["write-tree"], options)).stdout.trim(), "commit tree");
|
|
82
|
+
await runChecked(exec, "git", ["commit", "-m", message], options);
|
|
83
|
+
const actual = (await runChecked(exec, "git", ["show", "-s", "--format=%P %T", "HEAD"], options)).stdout.trim();
|
|
84
|
+
if (actual !== `${parent} ${tree}`) throw new Error("Commit parent or tree changed, possibly by a hook; inspect the actual commit and do not replay it");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
type Options = { cwd: string; agentDir?: string; exec?: Exec };
|
|
88
|
+
|
|
89
|
+
/** A single session/worktree owns this object. Unknown mutations consume it until manual review. */
|
|
90
|
+
export class GitCommitter {
|
|
91
|
+
private pending?: PendingCommit & { inspectionId: string; branch: string };
|
|
92
|
+
private uncertain = false;
|
|
93
|
+
private readonly exec: Exec;
|
|
94
|
+
private readonly options: Options;
|
|
95
|
+
constructor(options: Options) { this.options = options; this.exec = options.exec ?? spawnBounded; }
|
|
96
|
+
|
|
97
|
+
async inspect(target: string, signal?: AbortSignal) {
|
|
98
|
+
if (this.uncertain) throw new Error("Commit outcome needs manual review; do not replay it. Reload only after review");
|
|
99
|
+
requiredText(target, "target");
|
|
100
|
+
return withWorktreeLock(this.options.cwd, async () => {
|
|
101
|
+
const options = { cwd: this.options.cwd, signal };
|
|
102
|
+
const branch = requiredText((await runChecked(this.exec, "git", ["branch", "--show-current"], options)).stdout.trim(), "attached branch");
|
|
103
|
+
const targetOid = requiredOid((await runChecked(this.exec, "git", ["rev-parse", "--verify", "--end-of-options", `${target}^{commit}`], options)).stdout.trim(), "target OID");
|
|
104
|
+
const pending = await inspectPendingCommit(this.exec, options);
|
|
105
|
+
const mergeBase = requiredOid((await runChecked(this.exec, "git", ["merge-base", pending.head, targetOid], options)).stdout.trim(), "merge base");
|
|
106
|
+
const inspectionId = randomUUID();
|
|
107
|
+
this.pending = { ...pending, inspectionId, branch };
|
|
108
|
+
return { inspectionId, head: pending.head, targetOid, mergeBase, paths: [...parseStatusSnapshot(pending.status).keys()] };
|
|
109
|
+
}, { agentDir: this.options.agentDir, signal });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async commit(inspectionId: string, pathsInput: string[], message: string, signal?: AbortSignal) {
|
|
113
|
+
const pending = this.pending;
|
|
114
|
+
if (!pending || pending.inspectionId !== inspectionId || this.uncertain) throw new Error("Commit inspection is absent, stale, or consumed");
|
|
115
|
+
const paths = commitPaths(pathsInput);
|
|
116
|
+
if (paths.some((path) => !parseStatusSnapshot(pending.status).has(path))) throw new Error("Commit paths must be reviewed pending paths");
|
|
117
|
+
validateCommitMessage(message);
|
|
118
|
+
return withWorktreeLock(this.options.cwd, async () => {
|
|
119
|
+
const options = { cwd: this.options.cwd, signal };
|
|
120
|
+
if ((await runChecked(this.exec, "git", ["branch", "--show-current"], options)).stdout.trim() !== pending.branch) throw new Error("Commit branch changed");
|
|
121
|
+
await requirePendingCommit(this.exec, options, pending);
|
|
122
|
+
// Stage validation can fail without consuming an attempt. No commit has run yet.
|
|
123
|
+
await stageCommitPaths(this.exec, options, paths);
|
|
124
|
+
this.pending = undefined;
|
|
125
|
+
this.uncertain = true;
|
|
126
|
+
await commitStagedPaths(this.exec, options, message);
|
|
127
|
+
const head = await readHead(this.exec, options);
|
|
128
|
+
this.uncertain = false;
|
|
129
|
+
return { head };
|
|
130
|
+
}, { agentDir: this.options.agentDir, signal });
|
|
131
|
+
}
|
|
132
|
+
}
|
package/extensions/pr-command.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
loadCurrentPullRequest,
|
|
13
13
|
samePullRequestSnapshot,
|
|
14
14
|
type CurrentPullRequest,
|
|
15
|
+
type CurrentPullRequestDiscovery,
|
|
15
16
|
} from "./pr-github.ts";
|
|
16
17
|
import {
|
|
17
18
|
deriveNextStep,
|
|
@@ -39,10 +40,14 @@ type WorkflowLaunchAction = "prepare" | "inspect" | "rebase" | "start" | "resume
|
|
|
39
40
|
type WorkflowReservationResult = { runId: string; action: WorkflowLaunchAction };
|
|
40
41
|
|
|
41
42
|
type PrCommandPi = Pick<ExtensionAPI, "exec" | "getCommands" | "sendUserMessage">;
|
|
43
|
+
export type PublicationRequest = { base?: string; allowUpstream: boolean };
|
|
44
|
+
|
|
42
45
|
export type PrCommandInvocation = ((nextStep: NextStep) => void) & {
|
|
43
46
|
sessionGeneration: number;
|
|
44
47
|
assertCurrent(): void;
|
|
45
48
|
run?: PrRun;
|
|
49
|
+
publication?: PublicationRequest;
|
|
50
|
+
onDiscovery?: (discovery: CurrentPullRequestDiscovery) => void;
|
|
46
51
|
staleRediscoveries?: number;
|
|
47
52
|
replanAuthority?: CurrentPullRequest;
|
|
48
53
|
};
|
|
@@ -245,6 +250,7 @@ export function createPrCommandHandler(
|
|
|
245
250
|
if (args.trim()) throw new Error("/pr does not accept arguments");
|
|
246
251
|
const discovery = await load(pi, ctx);
|
|
247
252
|
onRouteResolved?.assertCurrent();
|
|
253
|
+
onRouteResolved?.onDiscovery?.(discovery);
|
|
248
254
|
if (discovery.kind === "current") onRouteResolved?.run?.observeRemote(discovery.pullRequest.head.oid);
|
|
249
255
|
if (onRouteResolved?.replanAuthority && (discovery.kind !== "current" ||
|
|
250
256
|
!samePullRequestSnapshot(onRouteResolved.replanAuthority, discovery.pullRequest))) {
|
|
@@ -254,6 +260,10 @@ export function createPrCommandHandler(
|
|
|
254
260
|
!isSameConfirmedMerge(linkedAuthority, discovery.pullRequest))) {
|
|
255
261
|
throw new Error("Link branch continuation cancelled: configured pull request context changed");
|
|
256
262
|
}
|
|
263
|
+
const publication = onRouteResolved?.publication;
|
|
264
|
+
if (publication?.base && discovery.kind === "current" && publication.base !== discovery.pullRequest.base.ref) {
|
|
265
|
+
throw new Error(`Requested base ${publication.base} differs from current PR base ${discovery.pullRequest.base.ref}; no retargeting is authorized`);
|
|
266
|
+
}
|
|
257
267
|
let nextStep = deriveNextStep(discovery);
|
|
258
268
|
if (discovery.kind === "current" && discovery.pullRequest.lifecycle === "open" &&
|
|
259
269
|
!discovery.pullRequest.conditions.draft && discovery.pullRequest.target.provenance === "configured" &&
|
|
@@ -267,13 +277,22 @@ export function createPrCommandHandler(
|
|
|
267
277
|
nextStep = "sweep";
|
|
268
278
|
onRouteResolved?.assertCurrent();
|
|
269
279
|
}
|
|
270
|
-
if (discovery.kind === "current" && (nextStep === "merge" || nextStep === "none" || nextStep === "wait-ci") &&
|
|
280
|
+
if (!publication && discovery.kind === "current" && (nextStep === "merge" || nextStep === "none" || nextStep === "wait-ci") &&
|
|
271
281
|
discovery.pullRequest.lifecycle === "open" && !discovery.pullRequest.conditions.draft &&
|
|
272
282
|
discovery.pullRequest.target.provenance === "configured" &&
|
|
273
283
|
discovery.pullRequest.local.worktree === "clean" && discovery.pullRequest.local.head === "equal") {
|
|
274
284
|
if (await needsFeedback(discovery.pullRequest, { cwd: ctx.cwd, signal: ctx.signal, load })) nextStep = "sweep";
|
|
275
285
|
onRouteResolved?.assertCurrent();
|
|
276
286
|
}
|
|
287
|
+
if (publication) {
|
|
288
|
+
if ((nextStep === "link-branch" || nextStep === "create" && discovery.kind === "none" && discovery.creationTarget.provenance === "inferred") && !publication.allowUpstream) {
|
|
289
|
+
throw new Error("Publication needs repository-local upstream configuration; ask for permission, then set allowUpstream: true");
|
|
290
|
+
}
|
|
291
|
+
if (!["create", "publish-work", "sync-local", "link-branch", "none"].includes(nextStep)) {
|
|
292
|
+
ctx.ui.notify(`Create/update authorization stops before ${nextStep}${discovery.kind === "current" ? `: ${discovery.pullRequest.url.href}` : ""}; use /pr only for the full lifecycle`, "info");
|
|
293
|
+
nextStep = "none";
|
|
294
|
+
}
|
|
295
|
+
}
|
|
277
296
|
onRouteResolved?.(nextStep);
|
|
278
297
|
if (discovery.kind === "inactive") return nextStep;
|
|
279
298
|
if (discovery.kind === "blocked") {
|