@wp-operations/wp-code 0.0.0 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,339 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, write to the Free Software Foundation, Inc.,
308
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
+
310
+ Also add information on how to contact you by electronic and paper mail.
311
+
312
+ If the program is interactive, make it output a short notice like this
313
+ when it starts in an interactive mode:
314
+
315
+ Gnomovision version 69, Copyright (C) year name of author
316
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317
+ This is free software, and you are welcome to redistribute it
318
+ under certain conditions; type `show c' for details.
319
+
320
+ The hypothetical commands `show w' and `show c' should show the appropriate
321
+ parts of the General Public License. Of course, the commands you use may
322
+ be called something other than `show w' and `show c'; they could even be
323
+ mouse-clicks or menu items--whatever suits your program.
324
+
325
+ You should also get your employer (if you work as a programmer) or your
326
+ school, if any, to sign a "copyright disclaimer" for the program, if
327
+ necessary. Here is a sample; alter the names:
328
+
329
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
+
332
+ <signature of Ty Coon>, 1 April 1989
333
+ Ty Coon, President of Vice
334
+
335
+ This General Public License does not permit incorporating your program into
336
+ proprietary programs. If your program is a subroutine library, you may
337
+ consider it more useful to permit linking proprietary applications with the
338
+ library. If this is what you want to do, use the GNU Lesser General
339
+ Public License instead of this License.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
1
  # @wp-operations/wp-code
2
2
 
3
- Reserved. Under development — not yet functional.
3
+ The wp-operations coding agent in your terminal. It runs the same Build mode the platform runs: it shows a model one app, gets back a change set, checks it with the platform's guardrails, and on your yes commits it to the app's work branch (`vibe/{slug}`). It never touches your working tree or your checked-out branch.
4
+
5
+ ```bash
6
+ npm install -g @wp-operations/wp-code
7
+ export ANTHROPIC_API_KEY=…
8
+ cd my-platform
9
+ wp-code service-apps/shop "Add a footer note under the content" --format=anthropic --model=<model id>
10
+ git push origin vibe/shop # the platform's preview picks it up
11
+ ```
12
+
13
+ Inside an app folder you can leave out `<kind>/<slug>`.
14
+
15
+ ## How a run goes
16
+
17
+ 1. It reads the app from `vibe/{slug}` if that branch exists, otherwise from HEAD. It reads files only, never `vendor/`, `node_modules/`, `.git/` or `.local/`.
18
+ 2. The model sees the platform rules, the app's file list, and the files you name with `--files=` or mention in the prompt (at most 12 files, 120 KB each).
19
+ 3. If the model answers with `needs`, wp-code reads those files and asks again, up to 3 rounds. If it answers with `questions`, nothing changes and the questions are printed.
20
+ 4. The change set must pass these guardrails, or the run fails and nothing is committed:
21
+ - it stays inside the app folder, never in `vendor/`, `node_modules/`, `.git/` or `.github/`;
22
+ - it never rewrites an existing file the model was not shown;
23
+ - every written file is whole and under 400 KB;
24
+ - it changes at most 30 files;
25
+ - an answer cut off by the token limit is discarded.
26
+ 5. You review the summary and the file list, then confirm. The commit goes to the work branch through git plumbing: no checkout, no index change, no push. `--yes` skips the question. `--apply` writes into the working tree instead.
27
+
28
+ `--mode=plan` and `--mode=chat` only answer; they change nothing.
29
+
30
+ ## Models
31
+
32
+ | Option | Default |
33
+ |---|---|
34
+ | `--format` | `openai` (any OpenAI-compatible `/chat/completions`) or `anthropic` (`/messages`) |
35
+ | `--model` | required |
36
+ | `--base-url` | `https://api.openai.com/v1` / `https://api.anthropic.com/v1` |
37
+ | `--key-env` | `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` |
38
+ | `--max-tokens`, `--temperature` | 8192, 0.2 |
39
+ | `--branch` | `vibe/{slug}` (`{kind}` also works) |
40
+ | `--rules=<file>` | extra platform rules |
41
+
42
+ You can set defaults in `wp-operations.json` at the repository root. Keys are never stored there.
43
+
44
+ ```json
45
+ { "code": { "format": "anthropic", "model": "…", "branch": "vibe/{slug}" } }
46
+ ```
47
+
48
+ ## License
49
+
50
+ GPL-2.0-or-later.
package/cli.js CHANGED
@@ -1,2 +1,4 @@
1
1
  #!/usr/bin/env node
2
- console.log('wp-code: not yet released.');
2
+ import { main } from './src/main.js';
3
+
4
+ await main();
package/package.json CHANGED
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "name": "@wp-operations/wp-code",
3
- "version": "0.0.0",
4
- "description": "Reserved. Under development — not yet functional.",
3
+ "version": "0.1.0",
4
+ "description": "The wp-operations coding agent in your terminal: asks an OpenAI-compatible or Anthropic model for a reviewed change set to a platform app and commits it to the app's work branch.",
5
5
  "type": "module",
6
+ "main": "src/main.js",
6
7
  "bin": {
7
8
  "wp-code": "cli.js"
8
9
  },
9
10
  "files": [
10
11
  "cli.js",
12
+ "src",
13
+ "LICENSE",
11
14
  "README.md"
12
15
  ],
13
16
  "license": "GPL-2.0-or-later",
@@ -24,5 +27,17 @@
24
27
  },
25
28
  "publishConfig": {
26
29
  "access": "public"
27
- }
30
+ },
31
+ "dependencies": {
32
+ "@wp-operations/wp-ide": "^0.3.0"
33
+ },
34
+ "keywords": [
35
+ "wordpress",
36
+ "ai",
37
+ "agent",
38
+ "coding-agent",
39
+ "anthropic",
40
+ "openai",
41
+ "wp-operations"
42
+ ]
28
43
  }
package/src/agent.js ADDED
@@ -0,0 +1,127 @@
1
+ export const MAX_FILES = 30;
2
+ export const MAX_BYTES = 400000;
3
+ export const MAX_SHOWN = 12;
4
+ export const MAX_SHOWN_BYTES = 120000;
5
+ export const MODES = ['build', 'plan', 'chat'];
6
+ const BLOCKED = /(^|\/)(\.git|vendor|node_modules)(\/|$)|^\.github\//;
7
+ const SAFE_PATH = /^[A-Za-z0-9._/@ -]+$/;
8
+
9
+ export class ProposalError extends Error {}
10
+
11
+ export function rules(extra = '') {
12
+ return [
13
+ 'Rules you must follow without exception:',
14
+ '1. Do exactly what the person asked and nothing more. No extra features, files, refactors, renames or "improvements" they did not request.',
15
+ '2. Never invent file contents, functions, hooks, APIs, packages, options or paths. Use only what is shown below or what is standard WordPress/PHP/JS.',
16
+ '3. If you need a file you have not been shown, do not guess it: list its path in "needs" and change nothing.',
17
+ '4. If the request is ambiguous, ask in "questions" and change nothing.',
18
+ '5. You cannot run commands, install, deploy, push or publish. You only propose; a person reviews every change before it is committed.',
19
+ '6. Stay inside this app folder. Never touch vendor/, node_modules/, .git/ or .github/.',
20
+ '7. Say "I don\'t know" instead of guessing.',
21
+ extra.trim() ? `\nPlatform rules:\n${extra.trim()}` : '',
22
+ ].join('\n');
23
+ }
24
+
25
+ export function format(mode) {
26
+ if (mode === 'build') {
27
+ return 'Answer with one JSON object and nothing else, in this shape: {"summary": "what you changed and why, in plain words", "changes": [{"path": "relative/path.php", "action": "write" | "delete", "content": "the complete new file content for write"}], "needs": ["paths you must read first"], "questions": ["questions for the person"]}. "content" must be the whole file, never a fragment or a placeholder. When "needs" or "questions" is not empty, "changes" must be empty.';
28
+ }
29
+ if (mode === 'plan') {
30
+ return 'Do not write code. Answer with a short numbered plan: the steps, the files each step touches (existing or new), and anything you need to know first.';
31
+ }
32
+ return 'Answer the question in plain words. Do not propose code changes unless asked; use short code snippets only to explain.';
33
+ }
34
+
35
+ export function context({ app, packages, tree, files }) {
36
+ const lines = [
37
+ `Apps are WordPress themes kept in the platform repository and deployed into full WordPress sites by GitHub Actions. Plugins live in ${packages}/ and are required by apps through composer path repositories. Content comes from the platform CMS API.`,
38
+ `App: ${app.slug}. Folder: ${app.path} (${app.label}).`,
39
+ ];
40
+ if (tree.length) {
41
+ lines.push(`Files in the app folder (paths relative to it):\n${tree.slice(0, 400).join('\n')}${tree.length > 400 ? `\n… ${tree.length - 400} more` : ''}`);
42
+ } else {
43
+ lines.push('The app folder is empty.');
44
+ }
45
+ for (const [path, content] of Object.entries(files)) {
46
+ lines.push(`File ${path}:\n\`\`\`\n${content}\n\`\`\``);
47
+ }
48
+ return lines.join('\n\n');
49
+ }
50
+
51
+ export function system({ mode, extraRules, app, packages, tree, files }) {
52
+ return `You are the coding agent of the wp-operations platform.\n\n${rules(extraRules)}\n\n${format(mode)}\n\n${context({ app, packages, tree, files })}`;
53
+ }
54
+
55
+ /**
56
+ * Picks the files to show: the ones asked for, then any path mentioned in
57
+ * the prompt, at most 12 text files of at most 120 KB each.
58
+ */
59
+ export function pickFiles(tree, prompt, wanted, read) {
60
+ const files = {};
61
+ for (const path of tree) {
62
+ if (wanted.includes(path) || prompt.includes(path)) {
63
+ const content = read(path);
64
+ if (typeof content === 'string' && !content.slice(0, 8000).includes('\0') && Buffer.byteLength(content) <= MAX_SHOWN_BYTES) {
65
+ files[path] = content;
66
+ }
67
+ }
68
+ if (Object.keys(files).length >= MAX_SHOWN) break;
69
+ }
70
+ return files;
71
+ }
72
+
73
+ /**
74
+ * Validates a build answer with the platform's guardrails: stays inside the
75
+ * app, never rewrites an existing file it was not shown, whole-file content
76
+ * under 400 KB, at most 30 files, nothing proposed while it needs files or
77
+ * has questions.
78
+ */
79
+ export function proposal(text, tree, seen) {
80
+ const json = text.trim().replace(/^```(?:json)?\s*|\s*```$/g, '');
81
+ let data;
82
+ try {
83
+ data = JSON.parse(json);
84
+ } catch {
85
+ data = null;
86
+ }
87
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
88
+ throw new ProposalError('The model did not return a valid change set, so nothing was proposed. Try again or rephrase.');
89
+ }
90
+
91
+ const changes = new Map();
92
+ for (const change of Array.isArray(data.changes) ? data.changes : []) {
93
+ const path = String(change?.path ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
94
+ const action = change?.action === 'delete' ? 'delete' : 'write';
95
+ if (path === '' || path.includes('..') || BLOCKED.test(path) || !SAFE_PATH.test(path)) {
96
+ throw new ProposalError(`The model tried to change "${path}", which is outside this app. Nothing was proposed.`);
97
+ }
98
+ const exists = tree.includes(path);
99
+ if (exists && !seen.includes(path)) {
100
+ throw new ProposalError(`The model tried to rewrite ${path} without reading it first. Nothing was proposed. Mention the file by its path so it is included.`);
101
+ }
102
+ if (action === 'delete' && !exists) continue;
103
+ const content = String(change?.content ?? '');
104
+ if (action === 'write' && (content.trim() === '' || Buffer.byteLength(content) > MAX_BYTES)) {
105
+ throw new ProposalError(`The model returned empty or oversized content for ${path}. Nothing was proposed.`);
106
+ }
107
+ changes.set(path, { path, action, content: action === 'write' ? content : '', new: !exists });
108
+ }
109
+ if (changes.size > MAX_FILES) {
110
+ throw new ProposalError(`The model proposed ${changes.size} files; the limit is ${MAX_FILES}. Ask for a smaller step.`);
111
+ }
112
+
113
+ const list = (value) => (Array.isArray(value) ? value.map(String).filter(Boolean) : []);
114
+ const needs = list(data.needs);
115
+ const questions = list(data.questions);
116
+ return {
117
+ summary: String(data.summary ?? ''),
118
+ changes: needs.length || questions.length ? [] : [...changes.values()],
119
+ needs,
120
+ questions,
121
+ };
122
+ }
123
+
124
+ export function commitMessage(slug, summary) {
125
+ const words = (summary || 'vibe changes').trim().split(/\s+/);
126
+ return `${slug}: ${words.slice(0, 14).join(' ')}${words.length > 14 ? '…' : ''}`;
127
+ }
package/src/main.js ADDED
@@ -0,0 +1,217 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import readline from 'readline/promises';
4
+ import { fileURLToPath, pathToFileURL } from 'url';
5
+ import { MODES, ProposalError, commitMessage, pickFiles, proposal, system } from './agent.js';
6
+ import { ProviderError, complete, resolveProvider } from './provider.js';
7
+ import { RepoError, applyToWorkingTree, baseRef, commitToBranch, isRepo, source, workBranch } from './repo.js';
8
+
9
+ const here = path.dirname(fileURLToPath(import.meta.url));
10
+ const pkg = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.json'), 'utf8'));
11
+ const MAX_ROUNDS = 3;
12
+
13
+ export const HELP = `wp-code v${pkg.version}: the platform's coding agent, from your terminal.
14
+
15
+ Usage:
16
+ wp-code [<kind>/<slug>] "<what to change>" [options]
17
+
18
+ Run it inside a platform repository (made by "wp-ops init"). Without
19
+ <kind>/<slug> it uses the app folder you are in.
20
+
21
+ It reads the app from its work branch (vibe/{slug} by default, or the
22
+ current HEAD when that branch does not exist yet), asks the model for a
23
+ change set, checks it with the platform's guardrails, shows it, and on your
24
+ yes commits it to the work branch. Your working tree and checked-out branch
25
+ are never touched. Push the branch yourself when you want the platform's
26
+ preview to pick it up.
27
+
28
+ Options:
29
+ --mode=build|plan|chat build proposes a change set (default); plan and chat only answer
30
+ --files=a.php,b.css files to show the model (paths relative to the app)
31
+ --format=openai|anthropic
32
+ --model=<id> required (or "code.model" in wp-operations.json)
33
+ --base-url=<url> default https://api.openai.com/v1 or https://api.anthropic.com/v1
34
+ --key-env=<NAME> env variable holding the API key (default OPENAI_API_KEY / ANTHROPIC_API_KEY)
35
+ --max-tokens=8192 --temperature=0.2
36
+ --branch=vibe/{slug} work branch template ({slug}, {kind})
37
+ --rules=<file> extra platform rules added to the instructions
38
+ --apply write the files into the working tree instead of committing
39
+ --yes do not ask before committing or applying
40
+ --json print the validated change set as JSON and stop
41
+
42
+ Defaults can live in wp-operations.json at the repository root:
43
+ { "code": { "format": "anthropic", "model": "…", "branch": "vibe/{slug}" } }`;
44
+
45
+ function parseArgs(argv) {
46
+ const positional = [];
47
+ const options = {};
48
+ for (const arg of argv) {
49
+ if (!arg.startsWith('--')) {
50
+ positional.push(arg);
51
+ continue;
52
+ }
53
+ const body = arg.slice(2);
54
+ const eq = body.indexOf('=');
55
+ if (eq >= 0) options[body.slice(0, eq)] = body.slice(eq + 1);
56
+ else options[body] = true;
57
+ }
58
+ return { positional, options };
59
+ }
60
+
61
+ async function loadIde() {
62
+ try {
63
+ return await import('@wp-operations/wp-ide');
64
+ } catch (error) {
65
+ if (error?.code !== 'ERR_MODULE_NOT_FOUND') throw error;
66
+ const local = path.resolve(here, '..', '..', 'wp-ide', 'dist', 'index.js');
67
+ if (!fs.existsSync(local)) throw new Error('@wp-operations/wp-ide is not installed.');
68
+ return import(pathToFileURL(local).href);
69
+ }
70
+ }
71
+
72
+ function findRoot(start, hasLayout) {
73
+ let current = path.resolve(start);
74
+ for (;;) {
75
+ if (hasLayout(current)) return current;
76
+ const parent = path.dirname(current);
77
+ if (parent === current) throw new RepoError('No .github/platform.json found from here upwards. Run wp-code inside a platform repository.');
78
+ current = parent;
79
+ }
80
+ }
81
+
82
+ function resolveApp(root, ide, positional, cwd) {
83
+ const layout = ide.readLayout(root);
84
+ const apps = ide.listApps(root, layout);
85
+ const first = positional[0] ?? '';
86
+ const named = apps.find((app) => app.path === ide.folder(first) || `${app.kind}/${app.slug}` === first);
87
+ if (named) return { app: named, layout, prompt: positional.slice(1).join(' ') };
88
+ const relative = path.relative(root, cwd).split(path.sep).join('/');
89
+ const inside = apps.find((app) => relative === app.path || relative.startsWith(`${app.path}/`));
90
+ if (inside) return { app: inside, layout, prompt: positional.join(' ') };
91
+ throw new RepoError(`Name the app as <kind>/<slug> (${apps.map((app) => app.path).join(', ') || 'no apps yet'}) or run wp-code inside its folder.`);
92
+ }
93
+
94
+ async function confirm(question) {
95
+ if (!process.stdin.isTTY) return false;
96
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
97
+ try {
98
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
99
+ } finally {
100
+ rl.close();
101
+ }
102
+ }
103
+
104
+ function printProposal(result, out) {
105
+ if (result.summary) out(`\n${result.summary}\n`);
106
+ for (const question of result.questions) out(` ? ${question}`);
107
+ if (result.needs.length) out(` needs: ${result.needs.join(', ')}`);
108
+ for (const change of result.changes) {
109
+ const lines = change.action === 'write' ? `${change.content.split('\n').length} lines` : '';
110
+ out(` ${change.action === 'delete' ? '-' : change.new ? '+' : '~'} ${change.path}${lines ? ` (${lines})` : ''}`);
111
+ }
112
+ }
113
+
114
+ export async function run(argv = process.argv.slice(2), { cwd = process.cwd(), out = console.log, fetchImpl, ask = confirm } = {}) {
115
+ const { positional, options } = parseArgs(argv);
116
+ if (options.help || options.h || positional[0] === 'help' || !positional.length) {
117
+ out(HELP);
118
+ return { status: positional.length || options.help ? 0 : 1 };
119
+ }
120
+ if (options.version) {
121
+ out(pkg.version);
122
+ return { status: 0 };
123
+ }
124
+
125
+ const ide = await loadIde();
126
+ const root = findRoot(cwd, ide.hasLayout);
127
+ const { app, layout, prompt } = resolveApp(root, ide, positional, cwd);
128
+ if (!prompt.trim()) throw new RepoError('Say what to change, e.g. wp-code service-apps/shop "Add a footer menu".');
129
+
130
+ const config = ide.readJson(path.join(root, 'wp-operations.json'))?.code ?? {};
131
+ const mode = String(options.mode ?? config.mode ?? 'build');
132
+ if (!MODES.includes(mode)) throw new RepoError(`--mode must be one of ${MODES.join(', ')}.`);
133
+ const provider = resolveProvider({
134
+ format: options.format ?? config.format,
135
+ model: options.model ?? config.model,
136
+ baseUrl: options['base-url'] ?? config.base_url,
137
+ keyEnv: options['key-env'] ?? config.key_env,
138
+ maxTokens: options['max-tokens'] ?? config.max_tokens,
139
+ temperature: options.temperature ?? config.temperature,
140
+ });
141
+ const extraRules = options.rules ? fs.readFileSync(path.resolve(cwd, options.rules), 'utf8') : String(config.rules ?? '');
142
+
143
+ const apply = Boolean(options.apply);
144
+ const git = isRepo(root);
145
+ if (!apply && mode === 'build' && !git) throw new RepoError(`${root} is not a git repository. Use --apply, or run "git init" and commit first.`);
146
+ const branch = workBranch(options.branch ?? config.branch, app);
147
+ let base = null;
148
+ if (!apply && git) {
149
+ try {
150
+ base = baseRef(root, branch);
151
+ } catch (error) {
152
+ if (mode === 'build') throw error;
153
+ }
154
+ }
155
+ const { tree, read } = source(root, app.path, base ? base.sha : null);
156
+ out(`wp-code · ${app.path} · ${base ? (base.exists ? branch : `HEAD (new branch ${branch})`) : 'working tree'} · ${provider.model}`);
157
+
158
+ const wanted = String(options.files ?? '').split(',').map((file) => file.trim()).filter(Boolean);
159
+ let files = pickFiles(tree, prompt, wanted, read);
160
+ const messages = [{ role: 'user', content: prompt }];
161
+ let result;
162
+ let tokens = 0;
163
+
164
+ for (let round = 1; round <= MAX_ROUNDS; round++) {
165
+ const answer = await complete(provider, system({ mode, extraRules, app, packages: layout.packages, tree, files }), messages, fetchImpl);
166
+ tokens += answer.tokensIn + answer.tokensOut;
167
+ if (mode !== 'build') {
168
+ out(`\n${answer.text}\n`);
169
+ out(`(${tokens} tokens)`);
170
+ return { status: 0, text: answer.text };
171
+ }
172
+ result = proposal(answer.text, tree, Object.keys(files));
173
+ const fetchable = result.needs.filter((file) => tree.includes(file) && !(file in files));
174
+ if (!result.needs.length || result.questions.length || !fetchable.length || round === MAX_ROUNDS) break;
175
+ const more = pickFiles(tree, '', fetchable, read);
176
+ if (!Object.keys(more).length) break;
177
+ out(` reading ${Object.keys(more).join(', ')}`);
178
+ files = { ...files, ...more };
179
+ }
180
+
181
+ if (options.json) {
182
+ out(JSON.stringify(result, null, 2));
183
+ return { status: 0, proposal: result };
184
+ }
185
+ printProposal(result, out);
186
+ out(`(${tokens} tokens)`);
187
+ if (!result.changes.length) {
188
+ out(result.questions.length || result.needs.length ? '\nNothing changed: answer the questions or name the files, then run again.' : '\nNo changes proposed.');
189
+ return { status: 0, proposal: result };
190
+ }
191
+
192
+ const target = apply ? `write ${result.changes.length} file(s) into ${app.path}` : `commit ${result.changes.length} file(s) to ${branch}`;
193
+ if (!options.yes && !(await ask(`\n${target[0].toUpperCase()}${target.slice(1)}?`))) {
194
+ out('Nothing committed.');
195
+ return { status: 0, proposal: result };
196
+ }
197
+ if (apply) {
198
+ applyToWorkingTree(root, app.path, result.changes);
199
+ out(`Wrote ${result.changes.length} file(s). Review them with git diff.`);
200
+ return { status: 0, proposal: result };
201
+ }
202
+ const commit = commitToBranch(root, branch, app.path, result.changes, commitMessage(app.slug, result.summary));
203
+ out(`Committed ${commit.sha.slice(0, 7)} to ${branch}. Publish it for the platform preview: git push origin ${branch}`);
204
+ return { status: 0, proposal: result, commit };
205
+ }
206
+
207
+ export async function main() {
208
+ try {
209
+ const { status } = await run();
210
+ process.exitCode = status;
211
+ } catch (error) {
212
+ const known = error instanceof ProviderError || error instanceof ProposalError || error instanceof RepoError;
213
+ console.error(`wp-code: ${error.message}`);
214
+ if (!known && process.env.DEBUG) console.error(error);
215
+ process.exitCode = 1;
216
+ }
217
+ }
@@ -0,0 +1,116 @@
1
+ export const FORMATS = ['openai', 'anthropic'];
2
+
3
+ const DEFAULT_BASE = {
4
+ openai: 'https://api.openai.com/v1',
5
+ anthropic: 'https://api.anthropic.com/v1',
6
+ };
7
+
8
+ const DEFAULT_KEY_ENV = {
9
+ openai: 'OPENAI_API_KEY',
10
+ anthropic: 'ANTHROPIC_API_KEY',
11
+ };
12
+
13
+ export class ProviderError extends Error {}
14
+
15
+ export function resolveProvider(input = {}) {
16
+ const format = input.format || 'openai';
17
+ if (!FORMATS.includes(format)) {
18
+ throw new ProviderError(`Unknown format "${format}". Use ${FORMATS.join(' or ')}.`);
19
+ }
20
+ const model = String(input.model || '').trim();
21
+ if (!model) {
22
+ throw new ProviderError('Choose a model: --model=<id>, or "code.model" in wp-operations.json.');
23
+ }
24
+ const keyEnv = input.keyEnv || DEFAULT_KEY_ENV[format];
25
+ const maxTokens = Number(input.maxTokens ?? 8192);
26
+ const temperature = Number(input.temperature ?? 0.2);
27
+ if (!Number.isInteger(maxTokens) || maxTokens < 256 || maxTokens > 200000) {
28
+ throw new ProviderError('--max-tokens must be a whole number from 256 to 200000.');
29
+ }
30
+ if (!(temperature >= 0 && temperature <= 1)) {
31
+ throw new ProviderError('--temperature must be between 0 and 1.');
32
+ }
33
+ return {
34
+ format,
35
+ model,
36
+ baseUrl: String(input.baseUrl || DEFAULT_BASE[format]).replace(/\/+$/, ''),
37
+ keyEnv,
38
+ maxTokens,
39
+ temperature,
40
+ timeoutMs: Number(input.timeoutMs ?? 120000),
41
+ };
42
+ }
43
+
44
+ /**
45
+ * One completion against an OpenAI-compatible /chat/completions or an
46
+ * Anthropic /messages endpoint. Answers cut off by the token limit are
47
+ * refused, exactly like the platform engine.
48
+ */
49
+ export async function complete(provider, system, messages, fetchImpl = globalThis.fetch) {
50
+ const key = String(process.env[provider.keyEnv] ?? '').trim();
51
+ if (!key) {
52
+ throw new ProviderError(`No API key: set the ${provider.keyEnv} environment variable.`);
53
+ }
54
+ const anthropic = provider.format === 'anthropic';
55
+ const body = {
56
+ model: provider.model,
57
+ max_tokens: provider.maxTokens,
58
+ temperature: provider.temperature,
59
+ };
60
+ let url;
61
+ const headers = { 'Content-Type': 'application/json', 'User-Agent': 'wp-operations' };
62
+ if (anthropic) {
63
+ body.system = system;
64
+ body.messages = messages;
65
+ url = `${provider.baseUrl}/messages`;
66
+ headers['x-api-key'] = key;
67
+ headers['anthropic-version'] = '2023-06-01';
68
+ } else {
69
+ body.messages = [{ role: 'system', content: system }, ...messages];
70
+ url = `${provider.baseUrl}/chat/completions`;
71
+ headers.Authorization = `Bearer ${key}`;
72
+ }
73
+
74
+ let response;
75
+ try {
76
+ response = await fetchImpl(url, {
77
+ method: 'POST',
78
+ headers,
79
+ body: JSON.stringify(body),
80
+ signal: AbortSignal.timeout(provider.timeoutMs),
81
+ });
82
+ } catch (error) {
83
+ throw new ProviderError(`${provider.model} could not be reached at ${url}: ${error.message}`);
84
+ }
85
+ const text = await response.text();
86
+ let data = null;
87
+ try {
88
+ data = JSON.parse(text);
89
+ } catch {}
90
+ if (!response.ok || !data || typeof data !== 'object') {
91
+ const message = data?.error?.message ?? data?.message ?? '';
92
+ throw new ProviderError(`${provider.model} returned ${response.status}${message ? `: ${message}` : '.'}`);
93
+ }
94
+
95
+ let output;
96
+ let stop;
97
+ let tokensIn;
98
+ let tokensOut;
99
+ if (anthropic) {
100
+ output = (Array.isArray(data.content) ? data.content : [])
101
+ .map((part) => (part && part.type === 'text' ? String(part.text ?? '') : ''))
102
+ .join('');
103
+ stop = String(data.stop_reason ?? '');
104
+ tokensIn = Number(data.usage?.input_tokens ?? 0);
105
+ tokensOut = Number(data.usage?.output_tokens ?? 0);
106
+ } else {
107
+ output = String(data.choices?.[0]?.message?.content ?? '');
108
+ stop = String(data.choices?.[0]?.finish_reason ?? '');
109
+ tokensIn = Number(data.usage?.prompt_tokens ?? 0);
110
+ tokensOut = Number(data.usage?.completion_tokens ?? 0);
111
+ }
112
+ if (stop === 'length' || stop === 'max_tokens') {
113
+ throw new ProviderError('The answer was cut off by the model token limit, so it was discarded. Ask for a smaller change or raise --max-tokens.');
114
+ }
115
+ return { text: output.trim(), tokensIn, tokensOut, model: provider.model };
116
+ }
package/src/repo.js ADDED
@@ -0,0 +1,150 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { execFileSync } from 'child_process';
5
+
6
+ const SKIP = new Set(['.git', 'vendor', 'node_modules', '.local']);
7
+
8
+ export class RepoError extends Error {}
9
+
10
+ function git(root, args, input, env) {
11
+ try {
12
+ return execFileSync('git', args, {
13
+ cwd: root,
14
+ input,
15
+ encoding: 'utf8',
16
+ stdio: ['pipe', 'pipe', 'pipe'],
17
+ maxBuffer: 64 * 1024 * 1024,
18
+ env: env ? { ...process.env, ...env } : process.env,
19
+ });
20
+ } catch (error) {
21
+ throw new RepoError(`git ${args[0]} failed: ${String(error.stderr || error.message).trim()}`);
22
+ }
23
+ }
24
+
25
+ function tryGit(root, args) {
26
+ try {
27
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
28
+ } catch {
29
+ return '';
30
+ }
31
+ }
32
+
33
+ export function isRepo(root) {
34
+ return tryGit(root, ['rev-parse', '--is-inside-work-tree']) === 'true';
35
+ }
36
+
37
+ export function workBranch(template, app) {
38
+ const name = String(template || 'vibe/{slug}')
39
+ .replace(/\{slug\}/g, app.slug)
40
+ .replace(/\{kind\}/g, app.kind)
41
+ .replace(/[^A-Za-z0-9._/-]/g, '-');
42
+ return name || `vibe/${app.slug}`;
43
+ }
44
+
45
+ /**
46
+ * The files an app has on a ref (or in the working tree when ref is null),
47
+ * relative to the app folder, skipping vendor, node_modules, .git and .local.
48
+ */
49
+ export function source(root, appPath, ref) {
50
+ if (ref) {
51
+ const prefix = `${appPath}/`;
52
+ const tree = git(root, ['ls-tree', '-r', '--name-only', '-z', ref, '--', prefix])
53
+ .split('\0')
54
+ .filter((file) => file.startsWith(prefix))
55
+ .map((file) => file.slice(prefix.length))
56
+ .filter((file) => !file.split('/').some((part) => SKIP.has(part)))
57
+ .sort();
58
+ const read = (file) => {
59
+ try {
60
+ return execFileSync('git', ['show', `${ref}:${prefix}${file}`], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
61
+ } catch {
62
+ return null;
63
+ }
64
+ };
65
+ return { tree, read };
66
+ }
67
+ const base = path.join(root, appPath);
68
+ const tree = [];
69
+ const walk = (dir) => {
70
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
71
+ if (SKIP.has(entry.name)) continue;
72
+ const full = path.join(dir, entry.name);
73
+ if (entry.isDirectory()) walk(full);
74
+ else if (entry.isFile()) tree.push(path.relative(base, full).split(path.sep).join('/'));
75
+ }
76
+ };
77
+ if (fs.existsSync(base)) walk(base);
78
+ const read = (file) => {
79
+ try {
80
+ return fs.readFileSync(path.join(base, file), 'utf8');
81
+ } catch {
82
+ return null;
83
+ }
84
+ };
85
+ return { tree: tree.sort(), read };
86
+ }
87
+
88
+ /**
89
+ * The ref an agent run builds on: the work branch when it already exists,
90
+ * otherwise the current HEAD.
91
+ */
92
+ export function baseRef(root, branch) {
93
+ if (tryGit(root, ['check-ref-format', '--branch', branch]) === '') {
94
+ throw new RepoError(`"${branch}" is not a valid branch name.`);
95
+ }
96
+ const existing = tryGit(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`]);
97
+ if (existing) return { ref: `refs/heads/${branch}`, sha: existing, exists: true };
98
+ const head = tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);
99
+ if (!head) throw new RepoError('The repository has no commits yet. Commit once, then run wp-code again.');
100
+ return { ref: head, sha: head, exists: false };
101
+ }
102
+
103
+ /**
104
+ * Commits a change set to the work branch without touching the working
105
+ * tree, the index or the checked-out branch (git plumbing on a temporary
106
+ * index). Refuses when the work branch is the one checked out.
107
+ */
108
+ export function commitToBranch(root, branch, appPath, changes, message) {
109
+ const current = tryGit(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
110
+ if (current === branch) {
111
+ throw new RepoError(`${branch} is checked out here; switch branches or use --apply to write the files instead.`);
112
+ }
113
+ const base = baseRef(root, branch);
114
+ const indexFile = path.join(os.tmpdir(), `wp-code-index-${process.pid}-${Date.now()}`);
115
+ const env = { GIT_INDEX_FILE: indexFile };
116
+ try {
117
+ git(root, ['read-tree', base.sha], undefined, env);
118
+ for (const change of changes) {
119
+ const file = `${appPath}/${change.path}`;
120
+ if (change.action === 'delete') {
121
+ git(root, ['update-index', '--force-remove', '--', file], undefined, env);
122
+ continue;
123
+ }
124
+ const blob = git(root, ['hash-object', '-w', '--stdin'], change.content).trim();
125
+ const existing = tryGit(root, ['ls-tree', base.sha, '--', file]);
126
+ const mode = existing.startsWith('100755') ? '100755' : '100644';
127
+ git(root, ['update-index', '--add', '--cacheinfo', `${mode},${blob},${file}`], undefined, env);
128
+ }
129
+ const tree = git(root, ['write-tree'], undefined, env).trim();
130
+ const commit = git(root, ['commit-tree', tree, '-p', base.sha, '-F', '-'], message, env).trim();
131
+ git(root, ['update-ref', '-m', 'wp-code', `refs/heads/${branch}`, commit, base.exists ? base.sha : '0'.repeat(base.sha.length)]);
132
+ return { sha: commit, branch, parent: base.sha, files: changes.length };
133
+ } finally {
134
+ fs.rmSync(indexFile, { force: true });
135
+ }
136
+ }
137
+
138
+ export function applyToWorkingTree(root, appPath, changes) {
139
+ const base = path.join(root, appPath);
140
+ for (const change of changes) {
141
+ const file = path.join(base, ...change.path.split('/'));
142
+ if (!file.startsWith(base + path.sep)) throw new RepoError(`Refusing to write outside ${appPath}: ${change.path}`);
143
+ if (change.action === 'delete') {
144
+ fs.rmSync(file, { force: true });
145
+ } else {
146
+ fs.mkdirSync(path.dirname(file), { recursive: true });
147
+ fs.writeFileSync(file, change.content);
148
+ }
149
+ }
150
+ }