graftfork 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +23 -2
  3. package/graft.mjs +447 -0
  4. package/package.json +12 -4
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # graftfork
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The command line for [Graft](https://graftfork.com). Graft keeps your changes to an open-source project on each
4
+ upstream release: it moves your changes onto the new release, runs your tests, and keeps the moved branch for you
5
+ only if every change lands and the tests pass. Otherwise your copy stays where it was and Graft says why.
6
+
7
+ This package is a thin client for graftfork.com's HTTP API. Syncs run on graftfork.com, not on your machine.
8
+
9
+ ```
10
+ npm install -g graftfork # Node 22.18 or newer; the command is `graft`
11
+ export GRAFT_TOKEN=graft_... # make a token at https://graftfork.com/app#settings
12
+
13
+ graft copies # your copies and where each one is
14
+ graft connect you/project # connect a repository Graft's GitHub app is installed on
15
+ graft sync # start a sync now (inside the clone, or pass the copy)
16
+ graft why # why the copy stayed, and what to do next
17
+ graft pull # fetch the latest move as graft/<release>; your branch is untouched
18
+ graft upstream "fix the parser" # Graft builds that one change alone on your release and runs your tests;
19
+ # this fetches graft/upstream/<change>. Nothing is pushed: you open the PR
20
+ graft upstream-pr <build> <url> # the pull request you opened; Graft tells you when it's merged
21
+ ```
22
+
23
+ Also `graft whoami`, `graft status` and `graft usage`; `--json` prints the API's answers as they are. API docs:
24
+ https://graftfork.com/docs/api. Support by email: support@graftfork.com. Apache-2.0.
package/graft.mjs ADDED
@@ -0,0 +1,447 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/client/cli.ts
4
+ import { spawnSync as spawnSync3 } from "node:child_process";
5
+ import { readFileSync } from "node:fs";
6
+ import { parseArgs } from "node:util";
7
+
8
+ // src/pull.ts
9
+ import { spawnSync } from "node:child_process";
10
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ var git = (cwd, args) => spawnSync("git", args, { cwd, encoding: "utf8" });
14
+ function repoOfRemote(url) {
15
+ const m = url.trim().match(/[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/);
16
+ return m ? `${m[1]}/${m[2]}` : null;
17
+ }
18
+ async function pull(o) {
19
+ const f = o.fetchImpl ?? fetch;
20
+ if (!o.token) return { ok: false, message: "graft pull needs a personal API token: make one at graftfork.com/app#settings, then set GRAFT_TOKEN or pass --token." };
21
+ if (git(o.cwd, ["rev-parse", "--git-dir"]).status !== 0) return { ok: false, message: "Run graft pull inside your clone of the copy." };
22
+ const headers = { authorization: `Bearer ${o.token}` };
23
+ const get = async (path) => {
24
+ const r = await f(`${o.api}${path}`, { headers });
25
+ const body = await r.json().catch(() => ({}));
26
+ if (!r.ok) throw new Error(body?.error?.message ?? `graftfork.com answered ${r.status}`);
27
+ return body;
28
+ };
29
+ try {
30
+ let id = o.copy && /^[A-Za-z0-9_-]{8,64}$/.test(o.copy) && !o.copy.includes("/") ? o.copy : null;
31
+ if (!id) {
32
+ const repo = o.copy ?? repoOfRemote(git(o.cwd, ["remote", "get-url", "origin"]).stdout ?? "");
33
+ if (!repo) return { ok: false, message: "Couldn't tell which copy this is: pass --copy owner/name." };
34
+ const { copies } = await get("/api/v1/copies");
35
+ const c = copies.find((x) => String(x.repo).toLowerCase() === repo.toLowerCase());
36
+ if (!c) return { ok: false, message: `${repo} isn't one of your copies on Graft.` };
37
+ id = c.id;
38
+ }
39
+ const t = await get(`/api/v1/copies/${id}/take`);
40
+ const r = await f(t.download);
41
+ if (!r.ok) return { ok: false, message: `Downloading the move failed (${r.status}). Try again; the link is made fresh each time.` };
42
+ const dir = mkdtempSync(join(tmpdir(), "graft-pull-"));
43
+ const file = join(dir, "move.bundle");
44
+ try {
45
+ writeFileSync(file, new Uint8Array(await r.arrayBuffer()));
46
+ const v = git(o.cwd, ["bundle", "verify", "-q", file]);
47
+ if (v.status !== 0) {
48
+ return { ok: false, message: `This clone is missing what the move builds on (${v.stderr.trim().split("\n").pop()}). Bring ${t.copy.branch} up to date (git fetch origin ${t.copy.branch}), then run graft pull again.` };
49
+ }
50
+ const fetched = git(o.cwd, ["fetch", "-q", file, `+refs/heads/${t.branch}:refs/heads/${t.branch}`]);
51
+ if (fetched.status !== 0) return { ok: false, message: `git fetch failed: ${fetched.stderr.trim().split("\n").pop()}` };
52
+ } finally {
53
+ rmSync(dir, { recursive: true, force: true });
54
+ }
55
+ const sha = git(o.cwd, ["rev-parse", "--short", t.branch]).stdout.trim();
56
+ return { ok: true, branch: t.branch, message: `Fetched ${t.branch} (${sha}): ${t.release ? `your changes on ${t.release}` : "the branch Graft delivered"}. Your branch is untouched.
57
+ Switch with: git switch ${t.branch}
58
+ Or take it into ${t.copy.branch}: git checkout ${t.copy.branch} && git merge --ff-only ${t.branch}` };
59
+ } catch (e) {
60
+ return { ok: false, message: e.message };
61
+ }
62
+ }
63
+
64
+ // src/client/upstream.ts
65
+ import { spawnSync as spawnSync2 } from "node:child_process";
66
+ import { mkdtempSync as mkdtempSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
67
+ import { tmpdir as tmpdir2 } from "node:os";
68
+ import { join as join2 } from "node:path";
69
+ var git2 = (cwd, args) => spawnSync2("git", args, { cwd, encoding: "utf8" });
70
+ async function upstream(o) {
71
+ const started = await o.call("POST", `/api/v1/copies/${o.copyId}/upstream`, { change: o.change });
72
+ let u = started.upstream;
73
+ if (o.noWait) return { ok: true, message: `${started.message ?? "Building."}
74
+ Build: ${u.id}. Check it with graft upstream-status ${u.id}.` };
75
+ const until = Date.now() + (o.waitMs ?? 30 * 6e4);
76
+ while (u.status === "queued" || u.status === "running") {
77
+ if (Date.now() > until) return { ok: false, message: `Still building after ${Math.round((o.waitMs ?? 30 * 6e4) / 6e4)} minutes. Check it later with graft upstream-status ${u.id}.` };
78
+ await new Promise((r) => setTimeout(r, o.pollMs ?? 1e4));
79
+ u = (await o.call("GET", `/api/v1/upstreams/${u.id}`)).upstream;
80
+ }
81
+ if (u.status !== "built") return { ok: false, message: `Not built: ${u.note ?? "the build failed"}` };
82
+ return take(o, u);
83
+ }
84
+ async function take(o, u) {
85
+ if (!u.downloads?.bundle) return { ok: false, message: `Built ${u.branch}, but Graft doesn't keep it any more. Build it again with graft upstream.` };
86
+ if (git2(o.cwd, ["rev-parse", "--git-dir"]).status !== 0) return { ok: false, message: `Built ${u.branch}. Run this inside your clone of the copy to fetch it, or download it: ${u.downloads.bundle}` };
87
+ const r = await o.fetchImpl(u.downloads.bundle);
88
+ if (!r.ok) return { ok: false, message: `Downloading the branch failed (${r.status}). Try again; graft upstream-status makes a fresh link.` };
89
+ const dir = mkdtempSync2(join2(tmpdir2(), "graft-upstream-"));
90
+ const file = join2(dir, "upstream.bundle");
91
+ try {
92
+ writeFileSync2(file, new Uint8Array(await r.arrayBuffer()));
93
+ const v = git2(o.cwd, ["bundle", "verify", "-q", file]);
94
+ if (v.status !== 0) return { ok: false, message: `This clone is missing what the branch builds on (${v.stderr.trim().split("\n").pop()}). Bring your copy's branch up to date, then run it again.` };
95
+ const f = git2(o.cwd, ["fetch", "-q", file, `+refs/heads/${u.branch}:refs/heads/${u.branch}`]);
96
+ if (f.status !== 0) return { ok: false, message: `git fetch failed: ${f.stderr.trim().split("\n").pop()}` };
97
+ } finally {
98
+ rmSync2(dir, { recursive: true, force: true });
99
+ }
100
+ let saved = "";
101
+ if (o.patchDir && u.downloads.patch) {
102
+ const p = await o.fetchImpl(u.downloads.patch);
103
+ if (p.ok) {
104
+ const path = join2(o.patchDir, `${String(u.branch).split("/").pop()}.patch`);
105
+ writeFileSync2(path, await p.text());
106
+ saved = `
107
+ The patch, for projects that take them by email: ${path}`;
108
+ }
109
+ }
110
+ const t = u.tests ?? {};
111
+ const pr = u.pullRequest ?? {};
112
+ return {
113
+ ok: true,
114
+ branch: u.branch,
115
+ message: [
116
+ `Fetched ${u.branch}: only "${u.change?.subject}" on ${u.release}${t.ran ? `; your tests: ${t.verdict ?? "ran"}` : "; no tests ran"}.${saved}`,
117
+ "Nothing was pushed. To send it, from your account:",
118
+ ...(u.commands ?? []).slice(2).map((c) => ` ${c}`),
119
+ `Pull request title: ${pr.title}`,
120
+ "Pull request text:",
121
+ ...String(pr.body ?? "").split("\n").map((l) => ` ${l}`),
122
+ `Then: graft upstream-pr ${u.id} <the pull request's URL>, and Graft tells you when it's merged.`
123
+ ].join("\n")
124
+ };
125
+ }
126
+
127
+ // src/client/cli.ts
128
+ var USAGE = `graft: the command line for graftfork.com (a thin client; syncs run on graftfork.com)
129
+
130
+ graft whoami the token's account and scopes
131
+ graft copies your copies and where each one is
132
+ graft connect <owner/name> connect a repository (Graft's GitHub app must be installed on it)
133
+ [--branch <b> --upstream <owner/name or URL> --base <release tag>] [--tags <pattern>]
134
+ graft sync [copy] start a sync now
135
+ graft status [copy] a copy and its latest runs
136
+ graft why [copy] why the copy stayed, and what to do next
137
+ graft pull [copy] fetch the latest move as graft/<release> in your clone
138
+ graft upgrade <dependency> [version] [--copy <copy>]
139
+ upgrade a dependency (npm or Python), delivered only if the tests pass
140
+ graft upgrades [id] your upgrades, or one with what its tests said
141
+ graft upstream <change> [copy] build one change alone on your release, tested; fetch graft/upstream/<change>
142
+ [--patch <dir>] [--no-wait] (nothing is pushed: you open the pull request yourself)
143
+ graft upstream-status <build> an upstream build's status, tests and links
144
+ graft upstream-pr <build> <url> the pull request you opened upstream; Graft checks it until it's merged
145
+ graft usage this month's syncs and agent work
146
+ graft verify-record <file> check a run's signed record (from /app or GET /api/v1/runs/{id}/record),
147
+ or an organization's agent change record
148
+ graft agent-record <org> an organization's signed agent change record, as JSON
149
+ [--from <YYYY-MM-DD> --to <YYYY-MM-DD>] (save it: graft agent-record <org> > record.json)
150
+ graft check <base> <head> check a change against the project's own tests (no push, no agent)
151
+ [--pr <n>] [--repo <owner/name> | --clone-url <url>] [--wait]
152
+ graft checks [id] your recent change checks, or one check's result
153
+ graft regen connect <owner/name or URL> --branch <b> --record <path> --impl <dir> --lang ts|py [--builds 1-3] [--on-push]
154
+ connect a spec (a duramen record): Graft rebuilds its implementation blind
155
+ graft regen run <spec> rebuild it now
156
+ graft regen status [id] your specs, a spec's rebuilds, or one rebuild and how to take it
157
+
158
+ [copy] is a copy id or owner/name; left out, it's this clone's origin remote.
159
+ Token: GRAFT_TOKEN or --token (make one at https://graftfork.com/app#settings). --json prints raw answers.`;
160
+ var ApiError = class extends Error {
161
+ };
162
+ async function run(argv, io) {
163
+ const { values: a, positionals } = parseArgs({
164
+ args: argv,
165
+ allowPositionals: true,
166
+ strict: false,
167
+ options: { token: { type: "string" }, api: { type: "string" }, json: { type: "boolean" }, patch: { type: "string" }, "no-wait": { type: "boolean" }, branch: { type: "string" }, upstream: { type: "string" }, base: { type: "string" }, tags: { type: "string" }, from: { type: "string" }, to: { type: "string" }, repo: { type: "string" }, "clone-url": { type: "string" }, pr: { type: "string" }, wait: { type: "boolean" }, copy: { type: "string" }, record: { type: "string" }, impl: { type: "string" }, lang: { type: "string" }, builds: { type: "string" }, "on-push": { type: "boolean" }, help: { type: "boolean", short: "h" } }
168
+ });
169
+ const [cmd, arg, arg2] = positionals;
170
+ if (!cmd || a.help || cmd === "help") {
171
+ io.out(USAGE);
172
+ return cmd || a.help ? 0 : 1;
173
+ }
174
+ const api = String(a.api ?? io.env.GRAFT_API ?? "https://graftfork.com").replace(/\/+$/, "");
175
+ if (cmd === "verify-record") return verify(arg, api, io);
176
+ const token = a.token ?? io.env.GRAFT_TOKEN;
177
+ if (!token) {
178
+ io.out("graft needs a personal API token: make one at https://graftfork.com/app#settings, then set GRAFT_TOKEN or pass --token.");
179
+ return 1;
180
+ }
181
+ const call = async (method, path, body) => {
182
+ const r = await io.fetch(`${api}${path}`, { method, headers: { authorization: `Bearer ${token}`, ...body && { "content-type": "application/json" } }, ...body && { body: JSON.stringify(body) } });
183
+ const b = await r.json().catch(() => ({}));
184
+ if (!r.ok) throw new ApiError(b?.error?.message ?? `graftfork.com answered ${r.status}`);
185
+ return b;
186
+ };
187
+ const show = (b, text) => io.out(a.json ? JSON.stringify(b, null, 1) : text);
188
+ const copyId = async (given) => {
189
+ if (given && !given.includes("/") && /^[A-Za-z0-9_-]{8,64}$/.test(given)) return given;
190
+ const repo = given ?? repoOfRemote(spawnSync3("git", ["remote", "get-url", "origin"], { cwd: io.cwd, encoding: "utf8" }).stdout ?? "");
191
+ if (!repo) throw new ApiError("Couldn't tell which copy: give its id or owner/name, or run this inside its clone.");
192
+ const { copies } = await call("GET", "/api/v1/copies");
193
+ const c = copies.find((x) => String(x.repo).toLowerCase() === repo.toLowerCase());
194
+ if (!c) throw new ApiError(`${repo} isn't one of your copies on Graft. Connect it with: graft connect ${repo}`);
195
+ return c.id;
196
+ };
197
+ try {
198
+ if (cmd === "whoami") {
199
+ const b = await call("GET", "/api/v1/token");
200
+ show(b, `${b.email}: scopes ${b.scopes.join(", ")}`);
201
+ } else if (cmd === "copies") {
202
+ const b = await call("GET", "/api/v1/copies");
203
+ const rows = b.copies.map((c) => `${c.id} ${c.repo} ${c.branch ?? ""} on ${c.base ?? "?"}${c.last ? ` last: ${c.last.status}${c.last.release ? ` ${c.last.release}` : ""}` : " never synced"}`);
204
+ show(b, rows.length ? rows.join("\n") : "No copies yet. Connect one with: graft connect <owner/name>");
205
+ } else if (cmd === "connect") {
206
+ if (!arg) {
207
+ io.out("graft connect <owner/name> [--branch <b> --upstream <repo> --base <tag>] [--tags <pattern>]");
208
+ return 1;
209
+ }
210
+ const b = await call("POST", "/api/v1/copies", { repo: arg, ...a.branch && { branch: a.branch }, ...a.upstream && { upstream: a.upstream }, ...a.base && { base: a.base }, ...a.tags && { tags: a.tags } });
211
+ show(b, `${b.message ?? "Connected."}
212
+ Copy id: ${b.copyId}`);
213
+ } else if (cmd === "sync") {
214
+ const b = await call("POST", `/api/v1/copies/${await copyId(arg)}/sync`);
215
+ show(b, `${b.message}
216
+ Run: ${b.run}`);
217
+ } else if (cmd === "status") {
218
+ const b = await call("GET", `/api/v1/copies/${await copyId(arg)}`);
219
+ const c = b.copy;
220
+ const runs = (b.recentRuns ?? []).map((r) => ` ${r.at ?? r.created_at ?? ""} ${r.status}${r.release ? ` ${r.release}` : ""}${r.note ? `: ${r.note}` : ""}`);
221
+ show(b, [`${c.repo} ${c.branch ?? ""} on ${c.base ?? "?"}, following ${c.upstream ?? "?"}`, ...runs.length ? ["Recent runs:", ...runs] : ["No runs yet."]].join("\n"));
222
+ } else if (cmd === "why") {
223
+ const b = await call("GET", `/api/v1/copies/${await copyId(arg)}/explain`);
224
+ const stuck = (b.stuck ?? []).map((s) => ` ${s.change}: ${s.why}`);
225
+ show(b, [b.headline, ...stuck.length ? ["Stuck:", ...stuck] : [], ...b.action ? [`What to do: ${b.action}`] : [], ...b.command ? [` ${b.command}`] : [], `Next: ${b.next?.why ?? ""}`].filter(Boolean).join("\n"));
226
+ } else if (cmd === "pull") {
227
+ const r = await pull({ cwd: io.cwd, copy: arg, token, api, fetchImpl: io.fetch });
228
+ io.out(r.message);
229
+ return r.ok ? 0 : 1;
230
+ } else if (cmd === "agent-record") {
231
+ if (!arg) {
232
+ io.out("graft agent-record <organization id> [--from <YYYY-MM-DD> --to <YYYY-MM-DD>]");
233
+ return 1;
234
+ }
235
+ const q = new URLSearchParams({ ...a.from && { from: String(a.from) }, ...a.to && { to: String(a.to) } }).toString();
236
+ const b = await call("GET", `/api/v1/orgs/${encodeURIComponent(arg)}/agent-record${q ? `?${q}` : ""}`);
237
+ io.out(JSON.stringify(b, null, 1));
238
+ } else if (cmd === "check") {
239
+ return await check(positionals[1], positionals[2]);
240
+ } else if (cmd === "checks") {
241
+ if (arg) {
242
+ const b = await call("GET", `/api/v1/checks/${encodeURIComponent(arg)}`);
243
+ show(b, checkText(b.check));
244
+ } else {
245
+ const b = await call("GET", "/api/v1/checks");
246
+ const rows = b.checks.map((c) => `${c.id} ${c.repo} ${c.head} vs ${c.base}${c.pr ? ` (#${c.pr})` : ""} ${c.outcome ?? c.status}`);
247
+ show(b, [...rows.length ? rows : ["No change checks yet. Start one with: graft check <base> <head>"], ...b.usage ? [`${b.usage.used} of ${b.usage.limit} checks this month.`] : []].join("\n"));
248
+ }
249
+ } else if (cmd === "upgrade") {
250
+ if (!arg) {
251
+ io.out("graft upgrade <dependency> [version] [--copy <copy id or owner/name>]");
252
+ return 1;
253
+ }
254
+ const b = await call("POST", "/api/v1/upgrades", { copy_id: await copyId(a.copy), dependency: arg, ...positionals[2] && { version: positionals[2] } });
255
+ show(b, `${b.message}
256
+ Upgrade: ${b.upgrade} (graft upgrades ${b.upgrade})`);
257
+ } else if (cmd === "upgrades") {
258
+ if (arg) {
259
+ const { upgrade: u } = await call("GET", `/api/v1/upgrades/${encodeURIComponent(arg)}`);
260
+ const lines = [`${u.dependency} ${u.from ?? ""} to ${u.version ?? u.requested} on ${u.repo ?? "?"}: ${u.status}`, ...u.why ? [` ${u.why}`] : []];
261
+ if (u.tests?.newFailures?.length) lines.push("Broken by the upgrade:", ...u.tests.newFailures.map((f) => ` ${f}`));
262
+ if (u.fix) lines.push(`Graft's agent: ${u.fix.applied ? `changed ${(u.fix.files ?? []).join(", ")}` : `not used (${u.fix.why})`}`);
263
+ if (u.delivered) lines.push(`Delivered as ${u.delivered.branch}. Take it in your clone with: graft pull ${u.run}`);
264
+ if (u.prUrl) lines.push(`Pull request: ${u.prUrl}`);
265
+ show({ upgrade: u }, lines.join("\n"));
266
+ } else {
267
+ const b = await call("GET", "/api/v1/upgrades");
268
+ const rows = b.upgrades.map((u) => `${u.id} ${u.repo ?? "?"} ${u.dependency} to ${u.version ?? u.requested}: ${u.status}`);
269
+ show(b, rows.length ? rows.join("\n") : "No upgrades yet. Start one with: graft upgrade <dependency> [version]");
270
+ }
271
+ } else if (cmd === "upstream") {
272
+ if (!arg) {
273
+ io.out("graft upstream <change> [copy] [--patch <dir>] [--no-wait]: the change's subject (or part of it), or its number in the latest move");
274
+ return 1;
275
+ }
276
+ const r = await upstream({ cwd: io.cwd, copyId: await copyId(arg2), change: arg, call, fetchImpl: io.fetch, noWait: !!a["no-wait"], ...a.patch && { patchDir: String(a.patch) }, ...io.env.GRAFT_POLL_MS && { pollMs: Number(io.env.GRAFT_POLL_MS) } });
277
+ io.out(r.message);
278
+ return r.ok ? 0 : 1;
279
+ } else if (cmd === "upstream-status") {
280
+ if (!arg) {
281
+ io.out("graft upstream-status <build>");
282
+ return 1;
283
+ }
284
+ const b = await call("GET", `/api/v1/upstreams/${encodeURIComponent(arg)}`);
285
+ const u = b.upstream;
286
+ const pr = u.pullRequest ?? {};
287
+ show(b, [`${u.change?.subject} on ${u.release}: ${u.status}${u.phase ? ` (${u.phase})` : ""}${u.note ? `. ${u.note}` : ""}`, ...(u.commands ?? []).map((c) => ` ${c}`), ...pr.url ? [`Pull request: ${pr.url}${pr.state ? ` (${pr.state})` : ""}`] : []].join("\n"));
288
+ } else if (cmd === "upstream-pr") {
289
+ if (!arg || !arg2) {
290
+ io.out("graft upstream-pr <build> <https://github.com/owner/name/pull/123>");
291
+ return 1;
292
+ }
293
+ const b = await call("POST", `/api/v1/upstreams/${encodeURIComponent(arg)}/pr`, { url: arg2 });
294
+ show(b, b.message);
295
+ } else if (cmd === "regen") {
296
+ return await regen(arg, arg2, a, call, show, io);
297
+ } else if (cmd === "usage") {
298
+ const b = await call("GET", "/api/v1/usage");
299
+ show(b, `${b.plan}: ${b.syncs?.used ?? 0} of ${b.syncs?.limit ?? "?"} syncs this month; Graft's agent $${Number(b.graftAgentUsd ?? 0).toFixed(2)}. Resets ${b.resetsOn}.`);
300
+ } else {
301
+ io.out(USAGE);
302
+ return 1;
303
+ }
304
+ return 0;
305
+ } catch (e) {
306
+ io.out(e instanceof ApiError ? e.message : `graft: ${e.message}`);
307
+ return 1;
308
+ }
309
+ async function check(base, head) {
310
+ const pr = a.pr === void 0 ? void 0 : Number(a.pr);
311
+ if ((!base || !head) && pr === void 0) {
312
+ io.out("graft check <base> <head> [--pr <n>] [--repo <owner/name> | --clone-url <url>] [--wait]");
313
+ return 1;
314
+ }
315
+ let where;
316
+ if (a.repo) where = { repo: a.repo };
317
+ else if (a["clone-url"]) where = { clone_url: a["clone-url"] };
318
+ else {
319
+ const remote = (spawnSync3("git", ["remote", "get-url", "origin"], { cwd: io.cwd, encoding: "utf8" }).stdout ?? "").trim();
320
+ const repo = repoOfRemote(remote);
321
+ if (/github\.com[:/]/.test(remote) && repo) where = { repo };
322
+ else if (/^https:\/\//.test(remote) && !/@/.test(remote.split("/")[2] ?? "")) where = { clone_url: remote };
323
+ else {
324
+ io.out("Couldn't tell which repository: pass --repo <owner/name> or --clone-url <url>, or run this inside its clone.");
325
+ return 1;
326
+ }
327
+ }
328
+ const b = await call("POST", "/api/v1/checks", { ...where, ...base && { base }, ...head && { head }, ...pr !== void 0 && { pr } });
329
+ if (!a.wait) {
330
+ show(b, `${b.message}
331
+ Check: ${b.check} (graft checks ${b.check})`);
332
+ return 0;
333
+ }
334
+ const sleep = io.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
335
+ for (let i = 0; i < 200; i++) {
336
+ const c = (await call("GET", `/api/v1/checks/${encodeURIComponent(b.check)}`)).check;
337
+ if (!["queued", "running"].includes(c.status)) {
338
+ show({ check: c }, checkText(c));
339
+ return c.outcome === "pass" ? 0 : c.outcome === "fail" ? 1 : 2;
340
+ }
341
+ await sleep(15e3);
342
+ }
343
+ io.out(`Still running. Read it later with: graft checks ${b.check}`);
344
+ return 2;
345
+ }
346
+ }
347
+ function checkText(c) {
348
+ const word = c.outcome === "pass" ? "PASS" : c.outcome === "fail" ? "FAIL" : c.outcome === "could_not_run" ? "COULD NOT RUN" : String(c.status).toUpperCase();
349
+ const sha = (r) => r?.sha ? ` (${String(r.sha).slice(0, 7)})` : "";
350
+ return [
351
+ `${word}: ${c.repo} ${c.head}${sha(c.headRun)} against ${c.base}${sha(c.baseRun)}${c.pr ? `, pull request #${c.pr}` : ""}`,
352
+ ...c.reason ? [c.reason] : [],
353
+ ...(c.newFailures ?? []).length ? ["New failures:", ...c.newFailures.map((f) => ` ${f}`)] : [],
354
+ ...(c.alreadyFailing ?? []).length ? [`${c.alreadyFailing.length} already failing on the base (not counted against the change).`] : [],
355
+ ...(c.testFilesChanged ?? []).length ? [`The change edits files that shape the tests: ${c.testFilesChanged.join(", ")}. Read them before trusting the result.`] : []
356
+ ].join("\n");
357
+ }
358
+ async function regen(sub, id, a, call, show, io) {
359
+ const line = (r) => `${r.id} ${r.status}${r.phase ? ` (${r.phase})` : ""}${r.suite?.total ? ` suite ${r.suite.passed}/${r.suite.total}` : ""}${r.choicesDiffer ? ` ${r.choicesDiffer} choice(s) differ` : ""}${r.why ? `: ${r.why}` : ""}`;
360
+ if (sub === "connect") {
361
+ if (!id || !a.record || !a.impl || !a.lang || !a.branch) {
362
+ io.out("graft regen connect <owner/name or https URL> --branch <b> --record <path> --impl <dir> --lang ts|py [--builds 1-3] [--on-push]");
363
+ return 1;
364
+ }
365
+ const b = await call("POST", "/api/v1/regen", { .../^https:\/\//.test(id) ? { clone_url: id } : { repo: id }, branch: a.branch, record: a.record, impl: a.impl, lang: a.lang, ...a.builds && { builds: Number(a.builds) }, ...a["on-push"] && { on_push: true } });
366
+ show(b, `${b.message ?? "Connected."}
367
+ Spec id: ${b.id}`);
368
+ } else if (sub === "run") {
369
+ if (!id) {
370
+ io.out("graft regen run <spec id>");
371
+ return 1;
372
+ }
373
+ const b = await call("POST", `/api/v1/regen/${encodeURIComponent(id)}/run`);
374
+ show(b, `${b.message}
375
+ Rebuild: ${b.run}`);
376
+ } else if (sub === "status") {
377
+ if (!id) {
378
+ const b = await call("GET", "/api/v1/regen");
379
+ const rows = b.specs.map((s) => `${s.id} ${s.repo} ${s.branch}: ${s.record} -> ${s.impl} (${s.lang})${s.last ? `
380
+ last: ${line(s.last)}` : "\n never rebuilt"}`);
381
+ show(b, rows.length ? rows.join("\n") : b.available ? "No specs yet. Connect one with: graft regen connect <owner/name> --branch main --record spec/ --impl impl --lang ts" : "Rebuilding from a spec is on Premium, Team and Enterprise.");
382
+ return 0;
383
+ }
384
+ const spec = await call("GET", `/api/v1/regen/${encodeURIComponent(id)}`).catch(() => null);
385
+ if (spec) {
386
+ show(spec, [`${spec.spec.repo} ${spec.spec.branch}: ${spec.spec.record} -> ${spec.spec.impl} (${spec.spec.lang})`, ...spec.runs.length ? spec.runs.map((r) => ` ${line(r)}`) : [" No rebuilds yet."]].join("\n"));
387
+ return 0;
388
+ }
389
+ const { run: run2 } = await call("GET", `/api/v1/regen/runs/${encodeURIComponent(id)}`);
390
+ const differ = run2.choicesDiff?.previous;
391
+ const lines = [line(run2), ...run2.builds.map((b) => ` build ${b.n}: ${b.verdict?.why ?? b.note ?? b.status}`)];
392
+ if (differ) for (const [k, label] of [["changed", "chosen differently"], ["added", "new"], ["removed", "gone"]]) for (const c of differ[k]) lines.push(` ${label}: ${c.title}`);
393
+ if (run2.take) lines.push("Take it, in your clone:", ...run2.take.commands.map((c) => ` ${c}`));
394
+ show({ run: run2 }, lines.join("\n"));
395
+ } else {
396
+ io.out("graft regen connect|run|status (graft help)");
397
+ return 1;
398
+ }
399
+ return 0;
400
+ }
401
+ var unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
402
+ async function verify(file, api, io) {
403
+ if (!file) {
404
+ io.out("graft verify-record <file>");
405
+ return 1;
406
+ }
407
+ let e;
408
+ try {
409
+ e = JSON.parse(readFileSync(file, "utf8"));
410
+ } catch {
411
+ io.out(`${file} isn't a Graft record (not JSON).`);
412
+ return 1;
413
+ }
414
+ if (e?.graft_record !== 1 || e.alg !== "Ed25519" || typeof e.payload !== "string" || typeof e.signature !== "string") {
415
+ io.out(`${file} isn't a Graft record.`);
416
+ return 1;
417
+ }
418
+ const { keys } = await (await io.fetch(`${api}/.well-known/graft-record-key`)).json();
419
+ const k = keys.find((x) => x.id === e.key);
420
+ if (!k) {
421
+ io.out(`NOT valid: signed with a key Graft doesn't publish (${e.key}).`);
422
+ return 1;
423
+ }
424
+ let good = false;
425
+ try {
426
+ const pub = await crypto.subtle.importKey("raw", unb64(k.public), { name: "Ed25519" }, false, ["verify"]);
427
+ good = await crypto.subtle.verify({ name: "Ed25519" }, pub, unb64(e.signature), new TextEncoder().encode(e.payload));
428
+ } catch {
429
+ }
430
+ if (!good) {
431
+ io.out("NOT valid: the record was changed after Graft signed it, or Graft didn't sign it.");
432
+ return 1;
433
+ }
434
+ const r = JSON.parse(e.payload);
435
+ if (r.graft_agent_record === 1) {
436
+ io.out(`Valid: signed by graftfork.com (key ${k.id}). Agent change record for ${r.org?.name ?? r.org?.id}, ${r.range?.from} to ${r.range?.to}: ${(r.changes ?? []).length} change(s) in ${r.counts?.runs ?? 0} run(s), ${(r.agent_actions ?? []).length} agent action(s).`);
437
+ return 0;
438
+ }
439
+ io.out(`Valid: signed by graftfork.com (key ${k.id}). Run ${r.run}, ${r.outcome}${r.upstream?.to ? ` onto ${r.upstream.to}` : ""}, ${(r.changes ?? []).length} change(s).`);
440
+ return 0;
441
+ }
442
+ if (process.argv[1] && /graft(\.mjs)?$|client[/\\]cli\.ts$/.test(process.argv[1])) {
443
+ process.exitCode = await run(process.argv.slice(2), { env: process.env, cwd: process.cwd(), fetch, out: (s) => console.log(s) });
444
+ }
445
+ export {
446
+ run
447
+ };
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "graftfork",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "The command line for graftfork.com: connect a copy, sync it, see why it stayed, and take each move. A thin client; syncs run on graftfork.com.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://graftfork.com/docs/api",
7
+ "bugs": { "email": "support@graftfork.com" },
8
+ "author": "Craig Merry",
9
+ "type": "module",
10
+ "bin": { "graft": "graft.mjs" },
11
+ "files": ["graft.mjs", "LICENSE", "README.md"],
12
+ "engines": { "node": ">=22.18" },
13
+ "keywords": ["fork", "git", "upstream", "releases", "graftfork"]
14
+ }