forgedock 1.53.0 → 1.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +51 -0
- package/README.md +8 -2
- package/bin/auth/app-manifest.mjs +89 -0
- package/bin/auth/app-manifest.test.mjs +75 -0
- package/bin/auth/app-token.mjs +258 -0
- package/bin/auth/app-token.test.mjs +240 -0
- package/bin/brand.mjs +7 -0
- package/bin/config-history.mjs +151 -0
- package/bin/config-schema.mjs +115 -0
- package/bin/demo.mjs +65 -11
- package/bin/engine/outcome-codes.mjs +6 -3
- package/bin/engine/telemetry-seam.mjs +8 -2
- package/bin/engine/telemetry-seam.test.mjs +17 -0
- package/bin/engine-cli.mjs +57 -20
- package/bin/first-run.mjs +122 -0
- package/bin/forgedock.mjs +128 -146
- package/bin/help-text.mjs +144 -0
- package/bin/hooks/pre-tool-use.mjs +7 -0
- package/bin/journey.mjs +82 -83
- package/bin/lean/acceptance.mjs +313 -0
- package/bin/lean/acceptance.test.mjs +215 -0
- package/bin/lean/activation.mjs +18 -0
- package/bin/lean/activation.test.mjs +23 -1
- package/bin/lean/batch-health.mjs +74 -1
- package/bin/lean/batch-health.test.mjs +54 -1
- package/bin/lean/batch.test.mjs +11 -9
- package/bin/lean/branchlock.mjs +54 -0
- package/bin/lean/branchlock.test.mjs +49 -0
- package/bin/lean/ceiling.mjs +72 -0
- package/bin/lean/ceiling.test.mjs +54 -0
- package/bin/lean/ci-budget.mjs +366 -0
- package/bin/lean/ci-budget.test.mjs +167 -0
- package/bin/lean/conformance.e2e.test.mjs +7 -0
- package/bin/lean/conformance.mjs +77 -19
- package/bin/lean/conformance.test.mjs +129 -3
- package/bin/lean/context.mjs +35 -6
- package/bin/lean/context.test.mjs +27 -1
- package/bin/lean/depcache.mjs +25 -1
- package/bin/lean/depcache.test.mjs +26 -0
- package/bin/lean/e2e.mjs +18 -2
- package/bin/lean/e2e.test.mjs +26 -1
- package/bin/lean/effects.mjs +40 -11
- package/bin/lean/execution.test.mjs +24 -0
- package/bin/lean/facts.mjs +3 -3
- package/bin/lean/facts.test.mjs +5 -0
- package/bin/lean/fixround.mjs +14 -0
- package/bin/lean/fixround.test.mjs +25 -2
- package/bin/lean/gh-assoc.test.mjs +2 -1
- package/bin/lean/integration.mjs +100 -9
- package/bin/lean/integration.test.mjs +98 -0
- package/bin/lean/issuewatch-parity.mjs +64 -0
- package/bin/lean/issuewatch-parity.test.mjs +127 -0
- package/bin/lean/issuewatch-release.test.mjs +1 -1
- package/bin/lean/issuewatch.mjs +34 -5
- package/bin/lean/issuewatch.test.mjs +3 -2
- package/bin/lean/lean.mjs +316 -74
- package/bin/lean/lean.test.mjs +397 -24
- package/bin/lean/mechfix.mjs +136 -0
- package/bin/lean/mechfix.test.mjs +95 -0
- package/bin/lean/orchestrate.mjs +20 -2
- package/bin/lean/phaseledger.mjs +47 -5
- package/bin/lean/phaseledger.test.mjs +30 -1
- package/bin/lean/precheck.mjs +23 -4
- package/bin/lean/precheck.test.mjs +14 -1
- package/bin/lean/prereq.mjs +28 -0
- package/bin/lean/prereq.test.mjs +20 -0
- package/bin/lean/probe.mjs +4 -2
- package/bin/lean/prodparity.mjs +52 -0
- package/bin/lean/prodparity.test.mjs +67 -0
- package/bin/lean/prompts.mjs +69 -12
- package/bin/lean/recovery.test.mjs +1 -1
- package/bin/lean/release-io.test.mjs +42 -0
- package/bin/lean/release-postmerge.mjs +6 -0
- package/bin/lean/release-preflight.mjs +58 -0
- package/bin/lean/release-preflight.test.mjs +114 -0
- package/bin/lean/release-rehearsal.mjs +8 -7
- package/bin/lean/release-review.mjs +67 -11
- package/bin/lean/release-review.test.mjs +128 -1
- package/bin/lean/release-snapshot.mjs +188 -0
- package/bin/lean/release-snapshot.test.mjs +190 -0
- package/bin/lean/release.mjs +87 -13
- package/bin/lean/release.test.mjs +104 -0
- package/bin/lean/render.mjs +1 -1
- package/bin/lean/replan.mjs +184 -0
- package/bin/lean/replan.test.mjs +110 -0
- package/bin/lean/resume.mjs +9 -7
- package/bin/lean/resume.test.mjs +16 -0
- package/bin/lean/schedd.mjs +34 -1
- package/bin/lean/schedd.test.mjs +21 -1
- package/bin/lean/selfreview.mjs +94 -0
- package/bin/lean/selfreview.test.mjs +58 -1
- package/bin/lean/selftest-gate.mjs +22 -0
- package/bin/lean/selftest-gate.test.mjs +18 -1
- package/bin/lean/selftest-journey.mjs +234 -0
- package/bin/lean/selftest-journey.test.mjs +130 -0
- package/bin/lean/selftest-live.mjs +2 -1
- package/bin/lean/seqlease.mjs +35 -1
- package/bin/lean/seqlease.test.mjs +15 -0
- package/bin/lean/seqreserve.e2e.test.mjs +135 -0
- package/bin/lean/seqreserve.mjs +73 -0
- package/bin/lean/seqreserve.test.mjs +134 -0
- package/bin/lean/sequence.mjs +35 -6
- package/bin/lean/seqversioned.mjs +147 -0
- package/bin/lean/stagestamp.mjs +28 -0
- package/bin/lean/stagestamp.test.mjs +32 -0
- package/bin/lean/surfaces.mjs +75 -0
- package/bin/lean/surfaces.test.mjs +59 -0
- package/bin/lean/toolplace.mjs +28 -0
- package/bin/lean/toolplace.test.mjs +24 -0
- package/bin/lean/toolstats.mjs +3 -1
- package/bin/lean/toolstats.test.mjs +11 -0
- package/bin/lean/validatebest.mjs +28 -0
- package/bin/lean/validatebest.test.mjs +27 -0
- package/bin/pool/agent.mjs +9 -0
- package/bin/pool/docker.mjs +5 -0
- package/bin/pool/router.mjs +8 -4
- package/bin/prereqs.mjs +111 -0
- package/bin/replay-timelapse.mjs +149 -0
- package/bin/review-staging.mjs +100 -16
- package/bin/review-staging.test.mjs +18 -0
- package/bin/runner.mjs +49 -7
- package/bin/splash-install.mjs +157 -0
- package/bin/stats/aggregate.mjs +8 -1
- package/bin/stats/conformance-outcomes.mjs +100 -19
- package/bin/stats/conformance-outcomes.test.mjs +87 -1
- package/bin/stats/depth.mjs +88 -31
- package/bin/stats/depth.test.mjs +63 -38
- package/bin/stats/efficiency.mjs +26 -5
- package/bin/stats/efficiency.test.mjs +45 -1
- package/bin/stats/first-review.mjs +77 -0
- package/bin/stats/first-review.test.mjs +36 -0
- package/bin/stats/firstmerge.mjs +40 -0
- package/bin/stats/firstmerge.test.mjs +41 -0
- package/bin/stats/github-source.mjs +51 -13
- package/bin/stats/index.mjs +91 -15
- package/bin/stats/local-source.mjs +1 -0
- package/bin/stats/origin.mjs +80 -0
- package/bin/stats/origin.test.mjs +58 -0
- package/bin/stats/render.mjs +3 -1
- package/bin/stats/scoreboard.mjs +137 -0
- package/bin/stats/scoreboard.test.mjs +87 -0
- package/bin/stats/stats.test.mjs +80 -0
- package/bin/tui.mjs +3 -2
- package/commands/bootstrap.md +15 -14
- package/commands/deploy-pr.md +18 -3
- package/commands/forge-stats.md +1 -1
- package/commands/forgedock-ci-setup.md +28 -0
- package/commands/forgedock-init.md +4 -5
- package/commands/issue.md +2 -0
- package/commands/milestone.md +9 -1
- package/commands/replay.md +2 -0
- package/commands/review-pr-staging.md +4 -1
- package/commands/work-on/close.md +8 -0
- package/docs/CI.md +1 -1
- package/docs/CONFIG.md +105 -10
- package/docs/ISSUE-WATCH.md +23 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/REPLAY.md +9 -0
- package/docs/SELFTEST.md +11 -0
- package/docs/STATS.md +19 -2
- package/docs/eval/README.md +6 -0
- package/docs/eval/adversarial-bench.md +68 -0
- package/docs/eval/corpus/adversarial-v1.json +285 -0
- package/docs/eval/feature-bench.md +42 -0
- package/docs/eval/feature-specs/crud-auth/journeys/notes-crud-isolated.mjs +21 -0
- package/docs/eval/feature-specs/crud-auth/journeys/register-login.mjs +12 -0
- package/docs/eval/feature-specs/crud-auth/spec.md +15 -0
- package/docs/site/start-a-new-project.md +2 -1
- package/package.json +5 -2
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +10 -0
- package/plugins/forgedock-splash/README.md +27 -0
- package/plugins/forgedock-splash/hooks/hooks.json +1 -0
- package/plugins/forgedock-splash/hooks/register.tsx +74 -0
- package/plugins/forgedock-splash/hooks/scene.ts +222 -0
- package/plugins/forgedock-splash/types/index.d.ts +10 -0
- package/scripts/bench-adversarial.mjs +216 -0
- package/scripts/bench-feature.mjs +170 -0
- package/scripts/bench-lightlane.mjs +2 -2
- package/scripts/bootstrap-create.mjs +2 -2
- package/scripts/bootstrap-validate.mjs +35 -2
- package/scripts/check-spec-size.sh +4 -3
- package/scripts/check-spec-size.test.sh +3 -0
- package/scripts/plan-validate-live.mjs +40 -6
- package/scripts/review-pr-staging-scope.test.sh +1 -1
- package/scripts/review-staging-post.sh +23 -0
- package/scripts/review-staging-post.test.sh +8 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { test } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { statSync, existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
+
import { resolveAuth, applyAuthEnv, startAuthRefresh, writeState, readState, statePath, deviceFlowLogin, mintViaBroker, assertSecureBroker, authFromCli, doctorAppAuth, clearState, AUTH_REFRESH_COMMANDS } from "./app-token.mjs";
|
|
9
|
+
|
|
10
|
+
const mkEnv = (extra = {}) => ({ FORGE_HOME_DIR: tmpDir("app-auth-"), ...extra });
|
|
11
|
+
const NOW = Date.parse("2026-01-01T00:00:00Z");
|
|
12
|
+
const iso = (ms) => new Date(NOW + ms).toISOString();
|
|
13
|
+
const json = (body, status = 200) => ({ ok: status < 400, status, json: async () => body });
|
|
14
|
+
const brokerState = (o = {}) => ({ mode: "broker", brokerUrl: "https://broker.test", userToken: "ghu_USER", installationId: 7, repositoryIds: [1, 2], ...o });
|
|
15
|
+
|
|
16
|
+
test("no stored login: env untouched, no network (users without the App see no change)", async () => {
|
|
17
|
+
const env = mkEnv({ GH_TOKEN: "personal" });
|
|
18
|
+
const r = await applyAuthEnv({ env, fetch: () => assert.fail("no network"), warn: () => assert.fail("no warning") });
|
|
19
|
+
assert.equal(r.source, "personal");
|
|
20
|
+
assert.equal(env.GH_TOKEN, "personal");
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("cached token with plenty of life is used without calling the broker", async () => {
|
|
24
|
+
const env = mkEnv();
|
|
25
|
+
writeState(brokerState({ token: "ghs_CACHED", expiresAt: iso(30 * 60000) }), env);
|
|
26
|
+
const r = await resolveAuth({ env, now: NOW, fetch: () => assert.fail("no network") });
|
|
27
|
+
assert.deepEqual(r.env, { GH_TOKEN: "ghs_CACHED" });
|
|
28
|
+
assert.equal(r.source, "broker");
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("token under 10 min left is refreshed via the broker with scoped body and persisted 0600", async () => {
|
|
32
|
+
const env = mkEnv();
|
|
33
|
+
writeState(brokerState({ token: "old", expiresAt: iso(5 * 60000) }), env);
|
|
34
|
+
let seen;
|
|
35
|
+
const fetch = async (url, init) => { seen = { url, init }; return json({ token: "ghs_NEW", expires_at: iso(3600000) }); };
|
|
36
|
+
const r = await resolveAuth({ env, now: NOW, fetch });
|
|
37
|
+
assert.equal(r.env.GH_TOKEN, "ghs_NEW");
|
|
38
|
+
assert.equal(seen.url, "https://broker.test/v1/token");
|
|
39
|
+
assert.equal(seen.init.headers.Authorization, "Bearer ghu_USER");
|
|
40
|
+
const body = JSON.parse(seen.init.body);
|
|
41
|
+
assert.deepEqual(body.repository_ids, [1, 2]);
|
|
42
|
+
assert.equal(body.installation_id, 7);
|
|
43
|
+
assert.equal(body.permissions.metadata, "read");
|
|
44
|
+
assert.equal(readState(env).token, "ghs_NEW");
|
|
45
|
+
assert.equal(statSync(statePath(env)).mode & 0o777, 0o600);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("broker outage falls back to personal auth with exactly one warning line and no token leak", async () => {
|
|
49
|
+
const env = mkEnv();
|
|
50
|
+
writeState(brokerState({ token: "old", expiresAt: iso(-1000) }), env);
|
|
51
|
+
const warns = [];
|
|
52
|
+
const r = await applyAuthEnv({ env, now: NOW, fetch: async () => json({}, 503), warn: (m) => warns.push(m) });
|
|
53
|
+
assert.equal(r.source, "personal");
|
|
54
|
+
assert.equal(env.GH_TOKEN, undefined); // no operator token: gh uses the user's own auth
|
|
55
|
+
assert.equal(warns.length, 1);
|
|
56
|
+
assert.ok(!warns[0].includes("\n") && !warns[0].includes("ghu_USER") && !warns[0].includes("old"));
|
|
57
|
+
const thrown = await resolveAuth({ env, now: NOW, fetch: async () => { throw new Error("ECONNREFUSED"); } });
|
|
58
|
+
assert.equal(thrown.source, "personal");
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("FORGEDOCK_NO_APP_AUTH=1 opts out", async () => {
|
|
62
|
+
const env = mkEnv({ FORGEDOCK_NO_APP_AUTH: "1" });
|
|
63
|
+
writeState(brokerState({ token: "t", expiresAt: iso(3600000) }), env);
|
|
64
|
+
assert.deepEqual((await resolveAuth({ env, now: NOW })).env, {});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("device flow: pending, slow_down, then token; denial throws", async () => {
|
|
68
|
+
const replies = [{ device_code: "dc", user_code: "ABCD-1234", verification_uri: "https://github.com/login/device", interval: 1, expires_in: 900 },
|
|
69
|
+
{ error: "authorization_pending" }, { error: "slow_down" }, { access_token: "ghu_X" }];
|
|
70
|
+
const sleeps = []; const calls = [];
|
|
71
|
+
const fetch = async (url, init) => { calls.push({ url, body: JSON.parse(init.body) }); return json(replies.shift()); };
|
|
72
|
+
let shown;
|
|
73
|
+
const t = await deviceFlowLogin({ clientId: "Iv1.abc", fetch, sleep: async (ms) => sleeps.push(ms), onCode: (c) => (shown = c), now: () => NOW });
|
|
74
|
+
assert.equal(t, "ghu_X");
|
|
75
|
+
assert.equal(shown.userCode, "ABCD-1234");
|
|
76
|
+
assert.deepEqual(sleeps, [1000, 1000, 6000]);
|
|
77
|
+
assert.deepEqual(Object.keys(calls[0].body), ["client_id"]); // client id only, no secret
|
|
78
|
+
await assert.rejects(deviceFlowLogin({ clientId: "c", sleep: async () => {}, now: () => NOW,
|
|
79
|
+
fetch: async (u) => json(u.endsWith("code") ? { device_code: "d", user_code: "u" } : { error: "access_denied" }) }), /access_denied/);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("mintViaBroker rejects a response without a token", async () => {
|
|
83
|
+
await assert.rejects(mintViaBroker({ brokerUrl: "https://b", userToken: "u", installationId: 1, fetch: async () => json({}) }), /no token/);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test("auth login stores installation, status and logout work", async () => {
|
|
87
|
+
const env = mkEnv(); const lines = [];
|
|
88
|
+
const fetch = async (url) => {
|
|
89
|
+
if (url.endsWith("/device/code")) return json({ device_code: "d", user_code: "U-1", verification_uri: "https://github.com/login/device", interval: 1 });
|
|
90
|
+
if (url.endsWith("/access_token")) return json({ access_token: "ghu_Z" });
|
|
91
|
+
if (url.includes("/user/installations/9/repositories")) return json({ repositories: [{ id: 41 }] });
|
|
92
|
+
if (url.endsWith("/user/installations")) return json({ installations: [{ id: 9 }] });
|
|
93
|
+
assert.fail(url);
|
|
94
|
+
};
|
|
95
|
+
const code = await authFromCli(["login", "--broker-url", "https://broker.test/", "--client-id", "Iv1.abc"], { env, fetch, out: (m) => lines.push(m), sleep: async () => {} });
|
|
96
|
+
assert.equal(code, 0);
|
|
97
|
+
const s = readState(env);
|
|
98
|
+
assert.deepEqual([s.mode, s.brokerUrl, s.installationId, s.repositoryIds], ["broker", "https://broker.test", 9, [41]]);
|
|
99
|
+
assert.ok(lines.some((l) => l.includes("U-1")));
|
|
100
|
+
assert.ok(!lines.join("\n").includes("ghu_Z"));
|
|
101
|
+
assert.equal(await authFromCli(["logout"], { env, out: () => {} }), 0);
|
|
102
|
+
assert.equal(existsSync(statePath(env)), false);
|
|
103
|
+
assert.equal(await authFromCli(["login"], { env, out: () => {} }), 1);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test("doctorAppAuth reports bot identity and rate limit; warns on fallback; unconfigured is silent", async () => {
|
|
107
|
+
const env = mkEnv();
|
|
108
|
+
assert.deepEqual(await doctorAppAuth({ env }), { configured: false });
|
|
109
|
+
writeState(brokerState({ slug: "rapiercraft-forgedock", token: "t", expiresAt: iso(3600000) }), env);
|
|
110
|
+
const gh = (args) => (args[1] === "rate_limit" ? JSON.stringify({ resources: { core: { limit: 15000 } } }) : "me\n");
|
|
111
|
+
const ok = await doctorAppAuth({ env, now: NOW, gh });
|
|
112
|
+
assert.equal(ok.status, "pass");
|
|
113
|
+
assert.match(ok.detail, /rapiercraft-forgedock\[bot\].*core\.limit 15000/);
|
|
114
|
+
writeState(brokerState({ expiresAt: iso(-1) }), env);
|
|
115
|
+
const bad = await doctorAppAuth({ env, now: NOW, gh, fetch: async () => json({}, 500) });
|
|
116
|
+
assert.equal(bad.status, "warn");
|
|
117
|
+
assert.match(bad.detail, /personal gh auth as me/);
|
|
118
|
+
clearState(env);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("a broker URL that is not https is refused before the user token is sent (loopback http allowed)", async () => {
|
|
122
|
+
let called = false;
|
|
123
|
+
await assert.rejects(mintViaBroker({ brokerUrl: "http://broker.example", userToken: "u", installationId: 1, fetch: async () => { called = true; return json({}); } }), /must be https/);
|
|
124
|
+
assert.equal(called, false);
|
|
125
|
+
assert.doesNotThrow(() => assertSecureBroker("https://broker.test"));
|
|
126
|
+
assert.doesNotThrow(() => assertSecureBroker("http://127.0.0.1:8787"));
|
|
127
|
+
assert.throws(() => assertSecureBroker("ftp://x"), /must be https/);
|
|
128
|
+
const env = mkEnv();
|
|
129
|
+
const lines = [];
|
|
130
|
+
const code = await authFromCli(["login", "--broker-url", "http://broker.example", "--client-id", "c"], { env, fetch: async () => { throw new Error("no network"); }, out: (m) => lines.push(m) });
|
|
131
|
+
assert.equal(code, 1);
|
|
132
|
+
assert.match(lines.join("\n"), /must be https/);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("startAuthRefresh refreshes env.GH_TOKEN past expiry with a fake clock", async () => {
|
|
136
|
+
const env = mkEnv();
|
|
137
|
+
writeState(brokerState({ token: "ghs_OLD", expiresAt: iso(30 * 60000) }), env);
|
|
138
|
+
await applyAuthEnv({ env, now: NOW, fetch: () => assert.fail("no network") });
|
|
139
|
+
assert.equal(env.GH_TOKEN, "ghs_OLD");
|
|
140
|
+
let clock = NOW;
|
|
141
|
+
const timers = [];
|
|
142
|
+
const fetch = async () => json({ token: "ghs_FRESH", expires_at: iso(2 * 3600000) });
|
|
143
|
+
const stop = startAuthRefresh({ env, now: () => clock, fetch, setTimer: (fn, ms) => { const t = { fn, ms }; timers.push(t); return t; }, clearTimer: () => {} });
|
|
144
|
+
assert.equal(timers.length, 1);
|
|
145
|
+
assert.ok(timers[0].ms <= 20 * 60000 + 1000);
|
|
146
|
+
clock = NOW + 31 * 60000; // past the old token's expiry
|
|
147
|
+
await timers[0].fn();
|
|
148
|
+
assert.equal(env.GH_TOKEN, "ghs_FRESH");
|
|
149
|
+
assert.deepEqual({ ...env }.GH_TOKEN, "ghs_FRESH"); // a lane env copied now carries the fresh token
|
|
150
|
+
assert.equal(timers.length, 2);
|
|
151
|
+
stop();
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("startAuthRefresh: an operator-exported GH_TOKEN is never overridden or refreshed", async () => {
|
|
155
|
+
const env = mkEnv({ GH_TOKEN: "operator" });
|
|
156
|
+
writeState(brokerState({ token: "ghs_X", expiresAt: iso(-1000) }), env);
|
|
157
|
+
const r = await applyAuthEnv({ env, now: NOW, fetch: () => assert.fail("no network") });
|
|
158
|
+
assert.equal(r.source, "personal");
|
|
159
|
+
assert.equal(env.GH_TOKEN, "operator");
|
|
160
|
+
const stop = startAuthRefresh({ env, now: () => NOW, fetch: () => assert.fail("no network"), setTimer: () => assert.fail("no timer") });
|
|
161
|
+
stop();
|
|
162
|
+
assert.equal(env.GH_TOKEN, "operator");
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("BYO manifest state is 32 hex chars from crypto, not Math.random", () => {
|
|
166
|
+
const src = readFileSync(new URL("./app-token.mjs", import.meta.url), "utf8");
|
|
167
|
+
assert.match(src, /randomBytes\(16\)\.toString\("hex"\)/);
|
|
168
|
+
assert.ok(!/Math\.random/.test(src));
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// #5392: a child process (auto-spawned schedd) inherits the App GH_TOKEN plus its fingerprint marker and must keep refreshing it.
|
|
172
|
+
const CHILD = `
|
|
173
|
+
import { applyAuthEnv, startAuthRefresh } from ${JSON.stringify(new URL("./app-token.mjs", import.meta.url).href)};
|
|
174
|
+
const NOW = ${NOW};
|
|
175
|
+
const iso = (ms) => new Date(NOW + ms).toISOString();
|
|
176
|
+
const env = process.env;
|
|
177
|
+
const out = { before: env.GH_TOKEN };
|
|
178
|
+
const r = await applyAuthEnv({ env, now: NOW, fetch: async () => { throw new Error("no network"); }, warn: (m) => { out.warning = m; } });
|
|
179
|
+
out.source = r.source; out.operator = Boolean(r.operator); out.afterApply = env.GH_TOKEN ?? null; out.fp = env.FORGEDOCK_APP_TOKEN_FP ?? null;
|
|
180
|
+
let clock = NOW; const timers = [];
|
|
181
|
+
const fetch = async () => ({ ok: true, status: 200, json: async () => ({ token: "ghs_FRESH", expires_at: iso(2 * 3600000) }) });
|
|
182
|
+
const stop = startAuthRefresh({ env, now: () => clock, fetch, setTimer: (fn, ms) => { const t = { fn, ms }; timers.push(t); return t; }, clearTimer: () => {} });
|
|
183
|
+
out.timers = timers.length;
|
|
184
|
+
if (timers.length) { clock = NOW + 31 * 60000; await timers[0].fn(); }
|
|
185
|
+
out.afterRefresh = env.GH_TOKEN ?? null;
|
|
186
|
+
stop();
|
|
187
|
+
process.stdout.write(JSON.stringify(out));
|
|
188
|
+
`;
|
|
189
|
+
async function runChild(childEnv) {
|
|
190
|
+
const { execFileSync } = await import("node:child_process");
|
|
191
|
+
const base = Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "GH_TOKEN" && k !== "FORGEDOCK_APP_TOKEN_FP" && k !== "FORGEDOCK_NO_APP_AUTH"));
|
|
192
|
+
return JSON.parse(execFileSync(process.execPath, ["--input-type=module", "-e", CHILD], { env: { ...base, ...childEnv }, encoding: "utf8" }));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
test("an inherited App token (child process, e.g. auto-spawned schedd) is adopted and refreshed, not treated as operator-owned", async () => {
|
|
196
|
+
const env = mkEnv();
|
|
197
|
+
writeState(brokerState({ token: "ghs_OLD", expiresAt: iso(30 * 60000) }), env);
|
|
198
|
+
await applyAuthEnv({ env, now: NOW, fetch: () => assert.fail("no network") });
|
|
199
|
+
assert.equal(env.GH_TOKEN, "ghs_OLD");
|
|
200
|
+
assert.match(env.FORGEDOCK_APP_TOKEN_FP, /^[0-9a-f]{16}$/);
|
|
201
|
+
assert.notEqual(env.FORGEDOCK_APP_TOKEN_FP, "ghs_OLD");
|
|
202
|
+
const out = await runChild({ ...env }); // what schedd.mjs defaultSpawn hands the daemon: the parent's env
|
|
203
|
+
assert.equal(out.operator, false);
|
|
204
|
+
assert.equal(out.source, "broker");
|
|
205
|
+
assert.equal(out.afterApply, "ghs_OLD");
|
|
206
|
+
assert.equal(out.timers, 1);
|
|
207
|
+
assert.equal(out.afterRefresh, "ghs_FRESH");
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test("a GH_TOKEN exported over the App token (fingerprint mismatch) is still never overridden in a child", async () => {
|
|
211
|
+
const env = mkEnv();
|
|
212
|
+
writeState(brokerState({ token: "ghs_OLD", expiresAt: iso(30 * 60000) }), env);
|
|
213
|
+
await applyAuthEnv({ env, now: NOW, fetch: () => assert.fail("no network") });
|
|
214
|
+
const out = await runChild({ ...env, GH_TOKEN: "operator" });
|
|
215
|
+
assert.equal(out.operator, true);
|
|
216
|
+
assert.equal(out.afterApply, "operator");
|
|
217
|
+
assert.equal(out.timers, 0);
|
|
218
|
+
assert.equal(out.afterRefresh, "operator");
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
test("an inherited App token whose login was removed is dropped with its marker (falls back to own gh auth)", async () => {
|
|
222
|
+
const env = mkEnv();
|
|
223
|
+
writeState(brokerState({ token: "ghs_OLD", expiresAt: iso(30 * 60000) }), env);
|
|
224
|
+
await applyAuthEnv({ env, now: NOW, fetch: () => assert.fail("no network") });
|
|
225
|
+
clearState(env);
|
|
226
|
+
const out = await runChild({ ...env });
|
|
227
|
+
assert.equal(out.operator, false);
|
|
228
|
+
assert.equal(out.source, "personal");
|
|
229
|
+
assert.equal(out.afterApply, null);
|
|
230
|
+
assert.equal(out.fp, null);
|
|
231
|
+
assert.equal(out.timers, 0);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// Long-running lane commands must refresh the App token they adopt, or lanes past expiry 401.
|
|
235
|
+
test("AUTH_REFRESH_COMMANDS covers lane commands and the CLI uses it instead of an inline list", () => {
|
|
236
|
+
for (const c of ["orchestrate", "schedd", "watch", "issue-watch", "prod-watch", "run-issue", "resume-stalled", "run", "bootstrap", "release"]) assert.ok(AUTH_REFRESH_COMMANDS.has(c), c);
|
|
237
|
+
for (const c of ["auth", "gc", "doctor"]) assert.ok(!AUTH_REFRESH_COMMANDS.has(c), c);
|
|
238
|
+
const src = readFileSync(new URL("../forgedock.mjs", import.meta.url), "utf8");
|
|
239
|
+
assert.match(src, /AUTH_REFRESH_COMMANDS\.has\(command\)\) startAuthRefresh\(\)/);
|
|
240
|
+
});
|
package/bin/brand.mjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* The one tagline (#5303). The logo banner, `forgedock --help`, the demo and the setup screen read it from here;
|
|
5
|
+
* package.json "description" must equal it (bin/tests/help-text.test.mjs). The README tagline matches it (bin/tests/help-text.test.mjs); wording chosen to match the PR #5287 headline.
|
|
6
|
+
*/
|
|
7
|
+
export const TAGLINE = "An AI engineering team that ships to production";
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
//
|
|
4
|
+
// bin/config-history.mjs — versioned forge.yaml history (#5315), kept under ~/.forge/config-history/<repo>/ and never in the repo.
|
|
5
|
+
// Layout: <n>.yaml per version plus index.json [{n, at, reason, sha, source?}]. Setup and agent edits record a version instead of
|
|
6
|
+
// leaving forge.yaml.bak-* files behind; rollback records the current file first, so it is itself undoable.
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { basename, dirname, join } from "node:path";
|
|
11
|
+
|
|
12
|
+
/** FORGE_CONFIG_HISTORY_DIR overrides the store root (tests, relocated homes). */
|
|
13
|
+
export function historyRoot(env = process.env) {
|
|
14
|
+
return env.FORGE_CONFIG_HISTORY_DIR || join(env.HOME || env.USERPROFILE || homedir(), ".forge", "config-history");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** `<owner>__<repo>` from the forge.yaml project block, else the checkout directory name. */
|
|
18
|
+
export function historyRepoKey(cwd, text = "") {
|
|
19
|
+
const o = text.match(/^\s+owner:\s+"?([\w.-]+)"?/m)?.[1], r = text.match(/^\s+repo:\s+"?([\w.-]+)"?/m)?.[1];
|
|
20
|
+
return o && r ? `${o}__${r}` : basename(cwd);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const sha = (t) => createHash("sha256").update(t).digest("hex").slice(0, 16);
|
|
24
|
+
const dirOf = (root, repo) => join(root, repo);
|
|
25
|
+
const writeAtomic = (file, data) => { const tmp = `${file}.${process.pid}.tmp`; writeFileSync(tmp, data); renameSync(tmp, file); };
|
|
26
|
+
|
|
27
|
+
export function listVersions({ root = historyRoot(), repo }) {
|
|
28
|
+
try { return JSON.parse(readFileSync(join(dirOf(root, repo), "index.json"), "utf8")); } catch { return []; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Record `text` as the next version; an identical-to-latest text is not recorded again. */
|
|
32
|
+
export function recordVersion({ root = historyRoot(), repo, text, reason, source, now = new Date() }) {
|
|
33
|
+
const dir = dirOf(root, repo);
|
|
34
|
+
mkdirSync(dir, { recursive: true });
|
|
35
|
+
const index = listVersions({ root, repo });
|
|
36
|
+
const last = index[index.length - 1];
|
|
37
|
+
if (last && last.sha === sha(text) && !source) return { n: last.n, recorded: false };
|
|
38
|
+
const n = (last?.n ?? 0) + 1;
|
|
39
|
+
writeAtomic(join(dir, `${n}.yaml`), text);
|
|
40
|
+
index.push({ n, at: now.toISOString(), reason: reason || "edit", sha: sha(text), ...(source ? { source } : {}) });
|
|
41
|
+
writeAtomic(join(dir, "index.json"), JSON.stringify(index, null, 2) + "\n");
|
|
42
|
+
return { n, recorded: true };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function readVersion({ root = historyRoot(), repo, n }) {
|
|
46
|
+
if (!listVersions({ root, repo }).some((v) => v.n === Number(n))) return null;
|
|
47
|
+
return readFileSync(join(dirOf(root, repo), `${Number(n)}.yaml`), "utf8");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Line diff (LCS) as `-`/`+` lines; "" when equal. */
|
|
51
|
+
export function lineDiff(a, b) {
|
|
52
|
+
const x = a.split("\n"), y = b.split("\n");
|
|
53
|
+
const t = Array.from({ length: x.length + 1 }, () => new Array(y.length + 1).fill(0));
|
|
54
|
+
for (let i = x.length - 1; i >= 0; i--) for (let j = y.length - 1; j >= 0; j--) t[i][j] = x[i] === y[j] ? t[i + 1][j + 1] + 1 : Math.max(t[i + 1][j], t[i][j + 1]);
|
|
55
|
+
const out = [];
|
|
56
|
+
let i = 0, j = 0;
|
|
57
|
+
while (i < x.length && j < y.length) {
|
|
58
|
+
if (x[i] === y[j]) { i++; j++; } else if (t[i + 1][j] >= t[i][j + 1]) out.push(`- ${x[i++]}`); else out.push(`+ ${y[j++]}`);
|
|
59
|
+
}
|
|
60
|
+
while (i < x.length) out.push(`- ${x[i++]}`);
|
|
61
|
+
while (j < y.length) out.push(`+ ${y[j++]}`);
|
|
62
|
+
return out.join("\n");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Diff version n against the current file (or against `against`, another version). Null when n is unknown. */
|
|
66
|
+
export function diffVersion({ root = historyRoot(), repo, n, file, against }) {
|
|
67
|
+
const old = readVersion({ root, repo, n });
|
|
68
|
+
const cur = against !== undefined ? readVersion({ root, repo, n: against }) : existsSync(file) ? readFileSync(file, "utf8") : "";
|
|
69
|
+
return old === null || cur === null ? null : lineDiff(old, cur);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Restore version n into `file`; the current content is recorded first (reason "before rollback to n"). */
|
|
73
|
+
export function rollback({ root = historyRoot(), repo, n, file, now }) {
|
|
74
|
+
const old = readVersion({ root, repo, n });
|
|
75
|
+
if (old === null) return { ok: false, error: `no version ${n}` };
|
|
76
|
+
const saved = existsSync(file) ? recordVersion({ root, repo, text: readFileSync(file, "utf8"), reason: `before rollback to ${n}`, now }) : null;
|
|
77
|
+
writeAtomic(file, old);
|
|
78
|
+
return { ok: true, saved: saved?.recorded ? saved.n : null };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const BAK = /^forge\.yaml\.bak([-.].+)?$/;
|
|
82
|
+
|
|
83
|
+
/** Import forge.yaml.bak / .bak-<date>-<reason> files from `dir` (oldest first, once each by file name); deletes them with `del`. */
|
|
84
|
+
export function importBak({ root = historyRoot(), repo, dir, del = false, now }) {
|
|
85
|
+
const names = readdirSync(dir).filter((f) => BAK.test(f)).sort((a, b) => statSync(join(dir, a)).mtimeMs - statSync(join(dir, b)).mtimeMs);
|
|
86
|
+
const seen = new Set(listVersions({ root, repo }).map((v) => v.source).filter(Boolean));
|
|
87
|
+
const imported = [], skipped = [], deleted = [];
|
|
88
|
+
for (const name of names) {
|
|
89
|
+
const file = join(dir, name);
|
|
90
|
+
if (!seen.has(name)) {
|
|
91
|
+
const reason = `imported ${name}`;
|
|
92
|
+
recordVersion({ root, repo, text: readFileSync(file, "utf8"), reason, source: name, now: now ?? new Date(statSync(file).mtimeMs) });
|
|
93
|
+
imported.push(name);
|
|
94
|
+
} else skipped.push(name);
|
|
95
|
+
if (del) { unlinkSync(file); deleted.push(name); }
|
|
96
|
+
}
|
|
97
|
+
return { found: names, imported, skipped, deleted };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Setup/agent edit of forge.yaml: record the current content as a version and move the file away (no .bak in the repo). */
|
|
101
|
+
export function backupToHistory(outputPath, reason, opts = {}) {
|
|
102
|
+
if (!existsSync(outputPath)) return null;
|
|
103
|
+
const text = readFileSync(outputPath, "utf8");
|
|
104
|
+
const repo = historyRepoKey(dirname(outputPath), text);
|
|
105
|
+
const { n } = recordVersion({ root: opts.root, repo, text, reason, now: opts.now });
|
|
106
|
+
unlinkSync(outputPath);
|
|
107
|
+
return { backupName: `config-history ${repo} v${n}` };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** `forgedock config history|diff <n>|rollback <n>|import-bak [--delete]`: returns the exit code. */
|
|
111
|
+
export function runConfigCommand(sub, rest, { cwd, out = (s) => console.log(s), env = process.env, confirm } = {}) {
|
|
112
|
+
const file = join(cwd, "forge.yaml");
|
|
113
|
+
const text = existsSync(file) ? readFileSync(file, "utf8") : "";
|
|
114
|
+
const repo = historyRepoKey(cwd, text), root = historyRoot(env);
|
|
115
|
+
const n = rest.find((a) => /^\d+$/.test(a));
|
|
116
|
+
if (sub === "history") {
|
|
117
|
+
const vs = listVersions({ root, repo });
|
|
118
|
+
if (!vs.length) out(`No config history for ${repo} (${join(root, repo)}).`);
|
|
119
|
+
for (const v of vs) out(` v${v.n} ${v.at} ${v.reason}`);
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
if (sub === "diff" || sub === "rollback") {
|
|
123
|
+
if (!n) { out(`Usage: npx forgedock config ${sub} <n> (see: npx forgedock config history)`); return 1; }
|
|
124
|
+
if (sub === "diff") {
|
|
125
|
+
const d = diffVersion({ root, repo, n, file });
|
|
126
|
+
if (d === null) { out(`No version ${n} for ${repo}.`); return 1; }
|
|
127
|
+
out(d || `v${n} is identical to the current forge.yaml.`);
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
const r = rollback({ root, repo, n, file });
|
|
131
|
+
if (!r.ok) { out(`No version ${n} for ${repo}.`); return 1; }
|
|
132
|
+
out(`Restored forge.yaml from v${n}.${r.saved ? ` The previous content is v${r.saved}.` : ""}`);
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
if (sub === "record") {
|
|
136
|
+
if (!text) { out("No forge.yaml to record."); return 1; }
|
|
137
|
+
const r = recordVersion({ root, repo, text, reason: rest.filter((a) => !a.startsWith("--")).join(" ") || "edit" });
|
|
138
|
+
out(r.recorded ? `Recorded forge.yaml as v${r.n} (${join(root, repo)}).` : `forge.yaml is unchanged since v${r.n}.`);
|
|
139
|
+
return 0;
|
|
140
|
+
}
|
|
141
|
+
if (sub === "import-bak") {
|
|
142
|
+
const del = rest.includes("--delete") || (confirm ? confirm() : false);
|
|
143
|
+
const r = importBak({ root, repo, dir: cwd, del });
|
|
144
|
+
out(`Found ${r.found.length} forge.yaml backup file(s); imported ${r.imported.length}, already imported ${r.skipped.length}.`);
|
|
145
|
+
if (r.found.length && !del) out(" Re-run with --delete to remove them from the repo (they are now in the history).");
|
|
146
|
+
if (r.deleted.length) out(` Deleted ${r.deleted.length} file(s).`);
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
out("Usage: npx forgedock config history | diff <n> | rollback <n> | record [reason] | import-bak [--delete]");
|
|
150
|
+
return 1;
|
|
151
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
//
|
|
4
|
+
// bin/config-schema.mjs — forge.yaml schema check (#5315). A setting nobody reads, or one the active engine path
|
|
5
|
+
// ignores, must never be silent: `forgedock doctor` fails on it and a batch warns at start. Pure: text in, findings out.
|
|
6
|
+
// The sections below mirror docs/CONFIG.md (bin/tests/config-schema.test.mjs fails when a documented section is missing here).
|
|
7
|
+
// Nested keys are only checked where a section is listed in CLOSED; elsewhere only the top level and typed keys are.
|
|
8
|
+
|
|
9
|
+
export const TOP_LEVEL = [
|
|
10
|
+
"project", "paths", "branches", "agents", "repos", "project_board", "orchestration", "orchestrate", "notify", "decisions",
|
|
11
|
+
"hygiene", "pipeline", "execution", "engine", "prod_watch", "selftest", "release", "issue_watch", "followups", "rollouts",
|
|
12
|
+
"post_deploy", "events", "lean", "stats", "verify", "ci", "env", "build", "decomposition", "services", "review", "devdocs",
|
|
13
|
+
"verification", "billing", "adaptive_scripts", "branding", "marketing", "acceptance_probe", "attribution", "autopilot",
|
|
14
|
+
"deploy", "gate", "experiment", "learned", "maintenance", "milestones", "pattern_feeds", "topology", "validate",
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
/** Sections whose direct children are a closed set: another child is an unknown key. */
|
|
18
|
+
export const CLOSED = {
|
|
19
|
+
"verification.ci_local": ["mode", "exclude_jobs", "include_jobs", "extra_commands", "services", "budget_minutes", "max_parallel"],
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** Typed keys: list | number | bool | scalar | {enum:[...]}. */
|
|
23
|
+
export const TYPES = {
|
|
24
|
+
"verification.ci_local.mode": { enum: ["advisory", "blocking"] },
|
|
25
|
+
"verification.ci_local.services": { enum: ["auto", "off"] },
|
|
26
|
+
"verification.ci_local.exclude_jobs": "list",
|
|
27
|
+
"verification.ci_local.include_jobs": "list",
|
|
28
|
+
"verification.ci_local.extra_commands": "list",
|
|
29
|
+
"verification.ci_local.budget_minutes": "number",
|
|
30
|
+
"verification.ci_local.max_parallel": "number",
|
|
31
|
+
"engine.path": { enum: ["core", "full", "lean", "auto"] },
|
|
32
|
+
"billing.enabled": "bool",
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Keys the legacy `full` path never reads (the core path reads them: bin/engine-cli.mjs readEnvConfig, readConformanceMode). */
|
|
36
|
+
export const IGNORED_ON = {
|
|
37
|
+
full: ["env", "verify", "lean", "engine.conformance", "engine.conformance_kinds"],
|
|
38
|
+
core: [],
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const DEPRECATED = {
|
|
42
|
+
"pipeline.token_budget_per_batch": "orchestration.cascade.token_budget",
|
|
43
|
+
"build.diff_size.threshold": "review.depth.extended_weight",
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Indentation scan of forge.yaml: Map of dotted key path -> {kind: "map"|"list"|"scalar", value}. Arrays, block scalars and comments are skipped. */
|
|
47
|
+
export function scanKeys(text) {
|
|
48
|
+
const out = new Map();
|
|
49
|
+
const lines = String(text).split(/\r?\n/);
|
|
50
|
+
const stack = []; // {indent, path}
|
|
51
|
+
let skipAbove = -1; // block scalar body: lines indented deeper than this are values
|
|
52
|
+
for (let i = 0; i < lines.length; i++) {
|
|
53
|
+
const line = lines[i];
|
|
54
|
+
if (/^\s*(#.*)?$/.test(line)) continue;
|
|
55
|
+
const indent = line.match(/^ */)[0].length;
|
|
56
|
+
if (skipAbove >= 0) { if (indent > skipAbove) continue; skipAbove = -1; }
|
|
57
|
+
if (/^\s*-(\s|$)/.test(line)) continue;
|
|
58
|
+
const m = line.match(/^( *)([A-Za-z_][\w.-]*)\s*:(?:\s+(.*))?$/);
|
|
59
|
+
if (!m) continue;
|
|
60
|
+
while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
|
|
61
|
+
const path = [...stack.map((s) => s.key), m[2]].join(".");
|
|
62
|
+
const value = (m[3] ?? "").replace(/\s+#.*$/, "").trim();
|
|
63
|
+
let kind = "scalar";
|
|
64
|
+
if (value === "" || value === "|" || value === ">" || /^[|>][+-]?$/.test(value)) {
|
|
65
|
+
if (/^[|>]/.test(value)) { skipAbove = indent; kind = "scalar"; }
|
|
66
|
+
else {
|
|
67
|
+
const next = lines.slice(i + 1).find((l) => !/^\s*(#.*)?$/.test(l));
|
|
68
|
+
kind = next && /^\s*-(\s|$)/.test(next) && next.match(/^ */)[0].length >= indent ? "list" : "map";
|
|
69
|
+
}
|
|
70
|
+
} else if (value.startsWith("[")) kind = "list";
|
|
71
|
+
out.set(path, { kind, value });
|
|
72
|
+
if (kind === "map") stack.push({ indent, key: m[2] });
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function typeError(spec, { kind, value }) {
|
|
78
|
+
const bare = value.replace(/^["']|["']$/g, "");
|
|
79
|
+
if (spec === "list") return kind === "list" ? "" : "a list";
|
|
80
|
+
if (kind !== "scalar") return "a scalar value";
|
|
81
|
+
if (spec === "number") return /^-?\d+(\.\d+)?$/.test(bare) ? "" : "a number";
|
|
82
|
+
if (spec === "bool") return /^(true|false)$/.test(bare) ? "" : "true or false";
|
|
83
|
+
if (spec && spec.enum) return spec.enum.includes(bare) ? "" : `one of ${spec.enum.join("|")}`;
|
|
84
|
+
return "";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @param {string} text forge.yaml content
|
|
89
|
+
* @param {{path?: string}} [opts] active engine path: core|full|lean|auto (anything but full reads as core)
|
|
90
|
+
* @returns {{level: "error"|"warn", code: string, key: string, message: string}[]}
|
|
91
|
+
*/
|
|
92
|
+
export function validateForgeYaml(text, { path } = {}) {
|
|
93
|
+
const keys = scanKeys(text);
|
|
94
|
+
const active = keys.get("engine.path")?.value.replace(/^["']|["']$/g, "") ?? "";
|
|
95
|
+
const engine = path ?? (active || "core");
|
|
96
|
+
const side = engine === "full" ? "full" : "core";
|
|
97
|
+
const findings = [];
|
|
98
|
+
const add = (level, code, key, message) => findings.push({ level, code, key, message });
|
|
99
|
+
for (const [key, node] of keys) {
|
|
100
|
+
if (!key.includes(".") && !TOP_LEVEL.includes(key)) { add("error", "unknown-key", key, `unknown top-level key "${key}" (nothing reads it; check the spelling against docs/CONFIG.md)`); continue; }
|
|
101
|
+
const parent = key.slice(0, key.lastIndexOf("."));
|
|
102
|
+
if (CLOSED[parent] && !CLOSED[parent].includes(key.slice(parent.length + 1))) { add("error", "unknown-key", key, `unknown key "${key}" (known under ${parent}: ${CLOSED[parent].join(", ")})`); continue; }
|
|
103
|
+
const ignored = IGNORED_ON[side].find((p) => key === p || key.startsWith(p + "."));
|
|
104
|
+
if (ignored && key === ignored) add("error", "ignored-on-path", key, `"${key}" is set but the ${side} engine path (engine.path: ${engine}) never reads it`);
|
|
105
|
+
if (DEPRECATED[key]) add("warn", "deprecated-alias", key, `"${key}" is a deprecated alias; use "${DEPRECATED[key]}"`);
|
|
106
|
+
if (TYPES[key]) {
|
|
107
|
+
const want = typeError(TYPES[key], node);
|
|
108
|
+
if (want) add("error", "wrong-type", key, `"${key}" must be ${want} (got ${node.kind === "scalar" ? JSON.stringify(node.value) : node.kind})`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return findings;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** One line per finding, key named. */
|
|
115
|
+
export const formatFinding = (f) => `${f.level === "error" ? "error" : "warn"}: ${f.message}`;
|
package/bin/demo.mjs
CHANGED
|
@@ -162,8 +162,9 @@ export function demoUsage() {
|
|
|
162
162
|
" --open Launch Claude Code in the demo directory if available.",
|
|
163
163
|
" --no-open Do not launch Claude Code (default).",
|
|
164
164
|
" --run Automatically run the seeded issue through /work-on to a",
|
|
165
|
-
" merged PR
|
|
166
|
-
"
|
|
165
|
+
" merged PR. Uses your logged-in `claude` CLI (subscription),",
|
|
166
|
+
" falling back to ANTHROPIC_API_KEY; opens `forgedock watch`",
|
|
167
|
+
" and ends with the merged PR link and cost.",
|
|
167
168
|
" -h, --help Show this help.",
|
|
168
169
|
].join("\n");
|
|
169
170
|
}
|
|
@@ -227,8 +228,8 @@ export function renderNextSteps({ target, source, claudeAvailable, apiKeyAvailab
|
|
|
227
228
|
if (!apiKeyAvailable) {
|
|
228
229
|
lines.push(
|
|
229
230
|
"",
|
|
230
|
-
"Tip:
|
|
231
|
-
"
|
|
231
|
+
"Tip: re-run with --run to execute the pipeline automatically (uses your",
|
|
232
|
+
"Claude Code login, or ANTHROPIC_API_KEY) and watch a PR merge.",
|
|
232
233
|
);
|
|
233
234
|
}
|
|
234
235
|
|
|
@@ -266,6 +267,39 @@ function defaultLaunch(bin, launchArgs, opts = {}) {
|
|
|
266
267
|
spawn(bin, launchArgs, { stdio: "inherit", ...opts });
|
|
267
268
|
}
|
|
268
269
|
|
|
270
|
+
/** Readiness of the execution backend: CLI first, API key fallback (#5304). */
|
|
271
|
+
async function defaultBackendCheck({ cwd, apiKey }) {
|
|
272
|
+
const { checkExecutionBackend } = await import("./runner.mjs");
|
|
273
|
+
return checkExecutionBackend({ cwd, apiKey });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Start `forgedock watch` for the demo repo, inheriting stdio. Returns the child or null. */
|
|
277
|
+
function defaultSpawnWatch({ forgeHome, cwd, repo }) {
|
|
278
|
+
if (!forgeHome) return null;
|
|
279
|
+
try {
|
|
280
|
+
return spawn(process.execPath, [join(forgeHome, "bin", "forgedock.mjs"), "watch", "--repo", repo], {
|
|
281
|
+
cwd,
|
|
282
|
+
stdio: "inherit",
|
|
283
|
+
});
|
|
284
|
+
} catch {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function stopWatcher(watcher) {
|
|
290
|
+
try {
|
|
291
|
+
watcher?.kill?.();
|
|
292
|
+
} catch { /* already gone */ }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Human cost string from a runCommand result (cost in USD, else token usage). */
|
|
296
|
+
export function formatDemoCost(result) {
|
|
297
|
+
if (Number.isFinite(result?.costUsd)) return `$${result.costUsd.toFixed(2)}`;
|
|
298
|
+
const u = result?.usage;
|
|
299
|
+
if (u) return `${(u.input_tokens || 0) + (u.output_tokens || 0)} tokens`;
|
|
300
|
+
return "unavailable";
|
|
301
|
+
}
|
|
302
|
+
|
|
269
303
|
const defaultLogger = {
|
|
270
304
|
log: (m) => process.stdout.write(`${m}\n`),
|
|
271
305
|
error: (m) => process.stderr.write(`${m}\n`),
|
|
@@ -304,6 +338,9 @@ export async function runDemo(opts = {}) {
|
|
|
304
338
|
commandExists = defaultCommandExists,
|
|
305
339
|
launch = defaultLaunch,
|
|
306
340
|
logger = defaultLogger,
|
|
341
|
+
backendCheck = defaultBackendCheck,
|
|
342
|
+
spawnWatch = defaultSpawnWatch,
|
|
343
|
+
runCommandFn = null,
|
|
307
344
|
} = opts;
|
|
308
345
|
|
|
309
346
|
const parsed = parseDemoArgs(args);
|
|
@@ -393,13 +430,15 @@ export async function runDemo(opts = {}) {
|
|
|
393
430
|
const claudeAvailable = commandExists("claude");
|
|
394
431
|
const apiKeyAvailable = Boolean(apiKey);
|
|
395
432
|
|
|
396
|
-
// --run: drive the seeded issue through /work-on automatically.
|
|
397
|
-
//
|
|
433
|
+
// --run: drive the seeded issue through /work-on automatically. Uses the
|
|
434
|
+
// logged-in `claude` CLI (subscription) first, then ANTHROPIC_API_KEY
|
|
435
|
+
// (#5304); falls back to print-only instructions when neither is usable.
|
|
398
436
|
if (parsed.run) {
|
|
399
|
-
|
|
437
|
+
const backend = await backendCheck({ cwd: target, apiKey });
|
|
438
|
+
if (!backend.ready) {
|
|
400
439
|
logger.log(
|
|
401
|
-
"\
|
|
402
|
-
"
|
|
440
|
+
"\nNo logged-in `claude` CLI and no ANTHROPIC_API_KEY — cannot run the pipeline automatically.\n" +
|
|
441
|
+
"Log in to Claude Code (or export your key) and re-run with --run, or open Claude Code manually:\n",
|
|
403
442
|
);
|
|
404
443
|
logger.log(renderNextSteps({ target, source, claudeAvailable, apiKeyAvailable: false }));
|
|
405
444
|
return { status: "ok", target, source };
|
|
@@ -419,9 +458,9 @@ export async function runDemo(opts = {}) {
|
|
|
419
458
|
"\nRunning /work-on 1 in the demo repo — watch the full pipeline execute…\n",
|
|
420
459
|
);
|
|
421
460
|
|
|
422
|
-
let runCommand;
|
|
461
|
+
let runCommand = runCommandFn;
|
|
423
462
|
try {
|
|
424
|
-
({ runCommand } = await import("./runner.mjs"));
|
|
463
|
+
if (!runCommand) ({ runCommand } = await import("./runner.mjs"));
|
|
425
464
|
} catch {
|
|
426
465
|
logger.error(
|
|
427
466
|
"Could not load bin/runner.mjs. Falling back to manual instructions.",
|
|
@@ -430,6 +469,11 @@ export async function runDemo(opts = {}) {
|
|
|
430
469
|
return { status: "ok", target, source };
|
|
431
470
|
}
|
|
432
471
|
|
|
472
|
+
const watcher = exec("gh", ["auth", "status"], { cwd: target }).status === 0
|
|
473
|
+
? spawnWatch({ forgeHome, cwd: target, repo: demoRepo })
|
|
474
|
+
: null;
|
|
475
|
+
if (!watcher) logger.log("gh is not authenticated — skipping the live view (run `gh auth login`).");
|
|
476
|
+
|
|
433
477
|
try {
|
|
434
478
|
const result = await runCommand({
|
|
435
479
|
commandsDir,
|
|
@@ -439,9 +483,19 @@ export async function runDemo(opts = {}) {
|
|
|
439
483
|
apiKey,
|
|
440
484
|
logger: { log: logger.log, error: logger.error },
|
|
441
485
|
});
|
|
486
|
+
stopWatcher(watcher);
|
|
442
487
|
logger.log(`\nDemo pipeline finished with status: ${result.status}`);
|
|
488
|
+
const pr = exec(
|
|
489
|
+
"gh",
|
|
490
|
+
["pr", "list", "--state", "merged", "--limit", "1", "--json", "url", "-q", ".[0].url"],
|
|
491
|
+
{ cwd: target },
|
|
492
|
+
);
|
|
493
|
+
const prUrl = pr.status === 0 ? pr.stdout.trim() : "";
|
|
494
|
+
logger.log(`Merged PR: ${prUrl || "(not found — check the demo repo's pull requests)"}`);
|
|
495
|
+
logger.log(`Cost: ${formatDemoCost(result)}`);
|
|
443
496
|
return { status: result.status === "ok" ? "ok" : result.status, target, source };
|
|
444
497
|
} catch (err) {
|
|
498
|
+
stopWatcher(watcher);
|
|
445
499
|
if (err.code === "NO_SDK") {
|
|
446
500
|
logger.error(
|
|
447
501
|
"\n@anthropic-ai/sdk is not installed. Install it with:\n" +
|