@hunsu/core 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,157 @@
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, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking systems
52
+ that are managed by, or on behalf of, the Licensor for the purpose of discussing
53
+ and improving the Work, but excluding communication that is conspicuously marked
54
+ or otherwise designated in writing by the copyright owner as "Not a Contribution."
55
+
56
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
57
+ of whom a Contribution has been received by Licensor and subsequently
58
+ incorporated within the Work.
59
+
60
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
61
+ License, each Contributor hereby grants to You a perpetual, worldwide,
62
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
63
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
64
+ sublicense, and distribute the Work and such Derivative Works in Source or
65
+ Object form.
66
+
67
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
68
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
69
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
70
+ license to make, have made, use, offer to sell, sell, import, and otherwise
71
+ transfer the Work, where such license applies only to those patent claims
72
+ licensable by such Contributor that are necessarily infringed by their
73
+ Contribution(s) alone or by combination of their Contribution(s) with the Work
74
+ to which such Contribution(s) was submitted. If You institute patent litigation
75
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
76
+ alleging that the Work or a Contribution incorporated within the Work
77
+ constitutes direct or contributory patent infringement, then any patent licenses
78
+ granted to You under this License for that Work shall terminate as of the date
79
+ such litigation is filed.
80
+
81
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
82
+ Derivative Works thereof in any medium, with or without modifications, and in
83
+ Source or Object form, provided that You meet the following conditions:
84
+
85
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
86
+ this License; and
87
+
88
+ (b) You must cause any modified files to carry prominent notices stating that
89
+ You changed the files; and
90
+
91
+ (c) You must retain, in the Source form of any Derivative Works that You
92
+ distribute, all copyright, patent, trademark, and attribution notices from the
93
+ Source form of the Work, excluding those notices that do not pertain to any part
94
+ of the Derivative Works; and
95
+
96
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
97
+ any Derivative Works that You distribute must include a readable copy of the
98
+ attribution notices contained within such NOTICE file, excluding those notices
99
+ that do not pertain to any part of the Derivative Works, in at least one of the
100
+ following places: within a NOTICE text file distributed as part of the Derivative
101
+ Works; within the Source form or documentation, if provided along with the
102
+ Derivative Works; or, within a display generated by the Derivative Works, if and
103
+ wherever such third-party notices normally appear. The contents of the NOTICE
104
+ file are for informational purposes only and do not modify the License. You may
105
+ add Your own attribution notices within Derivative Works that You distribute,
106
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
107
+ additional attribution notices cannot be construed as modifying the License.
108
+
109
+ You may add Your own copyright statement to Your modifications and may provide
110
+ additional or different license terms and conditions for use, reproduction, or
111
+ distribution of Your modifications, or for any such Derivative Works as a whole,
112
+ provided Your use, reproduction, and distribution of the Work otherwise complies
113
+ with the conditions stated in this License.
114
+
115
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
116
+ Contribution intentionally submitted for inclusion in the Work by You to the
117
+ Licensor shall be under the terms and conditions of this License, without any
118
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
119
+ supersede or modify the terms of any separate license agreement you may have
120
+ executed with Licensor regarding such Contributions.
121
+
122
+ 6. Trademarks. This License does not grant permission to use the trade names,
123
+ trademarks, service marks, or product names of the Licensor, except as required
124
+ for reasonable and customary use in describing the origin of the Work and
125
+ reproducing the content of the NOTICE file.
126
+
127
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
128
+ writing, Licensor provides the Work (and each Contributor provides its
129
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
130
+ KIND, either express or implied, including, without limitation, any warranties or
131
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
132
+ PARTICULAR PURPOSE. You are solely responsible for determining the
133
+ appropriateness of using or redistributing the Work and assume any risks
134
+ associated with Your exercise of permissions under this License.
135
+
136
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
137
+ tort (including negligence), contract, or otherwise, unless required by
138
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
139
+ writing, shall any Contributor be liable to You for damages, including any
140
+ direct, indirect, special, incidental, or consequential damages of any character
141
+ arising as a result of this License or out of the use or inability to use the
142
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
143
+ computer failure or malfunction, or any and all other commercial damages or
144
+ losses), even if such Contributor has been advised of the possibility of such
145
+ damages.
146
+
147
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
148
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
149
+ acceptance of support, warranty, indemnity, or other liability obligations
150
+ and/or rights consistent with this License. However, in accepting such
151
+ obligations, You may act only on Your own behalf and on Your sole
152
+ responsibility, not on behalf of any other Contributor, and only if You agree to
153
+ indemnify, defend, and hold each Contributor harmless for any liability incurred
154
+ by, or claims asserted against, such Contributor by reason of your accepting any
155
+ such warranty or additional liability.
156
+
157
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,83 @@
1
+ import type { ArtifactActionDefinition } from "@hunsu/protocol";
2
+ export type ArtifactActionRunStatus = "queued" | "running" | "succeeded" | "failed" | "stopped";
3
+ export type ArtifactActionRunSource = {
4
+ moveId?: string;
5
+ commit: string;
6
+ ref: string;
7
+ };
8
+ export type ArtifactActionAliasRecord = {
9
+ alias: string;
10
+ service?: string;
11
+ containerPort?: number;
12
+ healthPath?: string;
13
+ target?: string;
14
+ internalUrl?: string;
15
+ externalPath: string;
16
+ directUrl?: string;
17
+ };
18
+ export type ArtifactActionRunRecord = {
19
+ runId: string;
20
+ actionId: string;
21
+ roadmapId?: string;
22
+ action: ArtifactActionDefinition;
23
+ source: ArtifactActionRunSource;
24
+ status: ArtifactActionRunStatus;
25
+ sourceWorktree?: {
26
+ path: string;
27
+ commit: string;
28
+ createdAt: string;
29
+ removedAt?: string;
30
+ };
31
+ env: Record<string, string>;
32
+ aliases?: Record<string, ArtifactActionAliasRecord>;
33
+ exitCode?: number;
34
+ stdout?: string;
35
+ stderr?: string;
36
+ createdAt: string;
37
+ updatedAt: string;
38
+ stoppedAt?: string;
39
+ error?: string;
40
+ };
41
+ export type ArtifactActionRunInput = {
42
+ cwd?: string;
43
+ actionId: string;
44
+ moveId?: string;
45
+ commit?: string;
46
+ roadmapId?: string;
47
+ env?: Record<string, string>;
48
+ ambientEnv?: Record<string, string | undefined>;
49
+ processEnv?: Record<string, string | undefined>;
50
+ worktreeRoot?: string;
51
+ baseActionPath?: string;
52
+ now?: string;
53
+ };
54
+ export type ArtifactActionRunPlan = {
55
+ action: ArtifactActionDefinition;
56
+ run: ArtifactActionRunRecord;
57
+ commands: ArtifactActionCommand[];
58
+ };
59
+ export type ArtifactActionCommand = {
60
+ command: string;
61
+ args: string[];
62
+ cwd: string;
63
+ env: Record<string, string>;
64
+ };
65
+ export type ArtifactActionCommandRunner = (command: string, args: string[], options: {
66
+ cwd: string;
67
+ env: Record<string, string>;
68
+ }) => {
69
+ status: number;
70
+ stdout: string;
71
+ stderr: string;
72
+ };
73
+ export type ArtifactActionRunOptions = {
74
+ runner?: ArtifactActionCommandRunner;
75
+ store?: boolean;
76
+ processEnv?: Record<string, string | undefined>;
77
+ };
78
+ export declare function listArtifactActions(cwd?: string, moveId?: string): ArtifactActionDefinition[];
79
+ export declare function planArtifactActionRun(input: ArtifactActionRunInput): ArtifactActionRunPlan;
80
+ export declare function startArtifactActionRun(input: ArtifactActionRunInput, options?: ArtifactActionRunOptions): ArtifactActionRunRecord;
81
+ export declare function listArtifactActionRuns(cwd?: string): ArtifactActionRunRecord[];
82
+ export declare function readArtifactActionRun(cwd: string, runId: string): ArtifactActionRunRecord;
83
+ export declare function stopArtifactActionRun(cwd: string, runId: string, options?: ArtifactActionRunOptions): ArtifactActionRunRecord;
@@ -0,0 +1,415 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, join, resolve } from "node:path";
6
+ import { loadDomainStore } from "./domain-store.js";
7
+ import { ensureGitRepository, git } from "./git.js";
8
+ export function listArtifactActions(cwd = process.cwd(), moveId) {
9
+ const root = ensureGitRepository(cwd);
10
+ const store = loadDomainStore(root);
11
+ if (moveId) {
12
+ const move = store.board.moves.find(candidate => candidate.id === moveId);
13
+ if (!move) {
14
+ throw new Error(`No MOVE found for Artifact Action source: ${moveId}`);
15
+ }
16
+ const node = store.board.nodes.find(candidate => candidate.id === move.toNodeId);
17
+ return cloneActions(move.snapshot?.artifactActions ?? node?.artifactActions ?? []);
18
+ }
19
+ return cloneActions(store.board.artifactActions);
20
+ }
21
+ export function planArtifactActionRun(input) {
22
+ const root = ensureGitRepository(input.cwd ?? process.cwd());
23
+ const resolved = resolveActionSource(root, input);
24
+ const action = resolved.actions.find(candidate => candidate.id === input.actionId);
25
+ if (!action) {
26
+ throw new Error(`Unknown Artifact Action for selected source: ${input.actionId}`);
27
+ }
28
+ validateActionSourceScope(action, resolved.source);
29
+ const now = input.now ?? new Date().toISOString();
30
+ const runId = artifactActionRunId(action.id, resolved.source, now);
31
+ const externalBase = input.baseActionPath ?? actionRunBasePath(input.roadmapId, runId);
32
+ const aliases = action.kind === "host"
33
+ ? aliasesForAction(action, externalBase)
34
+ : undefined;
35
+ const env = resolveActionEnv(action, input.env, input.ambientEnv);
36
+ const run = {
37
+ runId,
38
+ actionId: action.id,
39
+ roadmapId: input.roadmapId,
40
+ action: cloneAction(action),
41
+ source: resolved.source,
42
+ status: "queued",
43
+ env: sanitizeEnvForStorage(action, env),
44
+ aliases,
45
+ createdAt: now,
46
+ updatedAt: now
47
+ };
48
+ return {
49
+ action: cloneAction(action),
50
+ run,
51
+ commands: actionCommands(root, action, run, env)
52
+ };
53
+ }
54
+ export function startArtifactActionRun(input, options = {}) {
55
+ const root = ensureGitRepository(input.cwd ?? process.cwd());
56
+ const plan = planArtifactActionRun(input);
57
+ const now = input.now ?? new Date().toISOString();
58
+ const sourceWorktree = createActionSourceWorktree(root, plan.run.runId, plan.run.source.commit, now, input.worktreeRoot);
59
+ const processEnv = input.processEnv ?? options.processEnv;
60
+ const runner = options.runner ?? ((command, args, commandOptions) => spawnCommand(command, args, { ...commandOptions, processEnv }));
61
+ let run = {
62
+ ...plan.run,
63
+ status: plan.action.kind === "host" ? "running" : "running",
64
+ sourceWorktree,
65
+ updatedAt: now
66
+ };
67
+ const resolvedEnv = resolveActionEnv(plan.action, input.env, input.ambientEnv);
68
+ const commands = actionCommands(root, plan.action, run, resolvedEnv);
69
+ try {
70
+ if (plan.action.runner.type === "docker_compose") {
71
+ runActionCommand(runner, commands[0]);
72
+ runActionCommand(runner, commands[1]);
73
+ run.aliases = attachDirectAliasUrls(root, run, runner, resolvedEnv);
74
+ run.status = "running";
75
+ }
76
+ else {
77
+ const result = runActionCommand(runner, commands[0]);
78
+ run.exitCode = result.status;
79
+ run.stdout = result.stdout;
80
+ run.stderr = result.stderr;
81
+ run.status = plan.action.kind === "host" ? "running" : "succeeded";
82
+ if (plan.action.kind === "check") {
83
+ const removed = removeActionSourceWorktree(root, sourceWorktree.path);
84
+ run.sourceWorktree = { ...sourceWorktree, removedAt: removed };
85
+ }
86
+ }
87
+ run.updatedAt = new Date().toISOString();
88
+ }
89
+ catch (error) {
90
+ run.status = "failed";
91
+ run.updatedAt = new Date().toISOString();
92
+ run.error = error instanceof Error ? error.message : String(error);
93
+ const removed = removeActionSourceWorktree(root, sourceWorktree.path);
94
+ run.sourceWorktree = { ...sourceWorktree, removedAt: removed };
95
+ }
96
+ if (options.store !== false) {
97
+ writeArtifactActionRun(root, run);
98
+ }
99
+ if (run.status === "failed") {
100
+ throw new Error(run.error ?? `Artifact Action ${run.runId} failed`);
101
+ }
102
+ return run;
103
+ }
104
+ export function listArtifactActionRuns(cwd = process.cwd()) {
105
+ const root = ensureGitRepository(cwd);
106
+ const dir = actionRunStoreDir(root);
107
+ if (!existsSync(dir)) {
108
+ return [];
109
+ }
110
+ return readdirSync(dir)
111
+ .filter(file => file.endsWith(".json"))
112
+ .map(file => readArtifactActionRun(root, file.slice(0, -".json".length)))
113
+ .sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
114
+ }
115
+ export function readArtifactActionRun(cwd, runId) {
116
+ const root = ensureGitRepository(cwd);
117
+ const path = actionRunRecordPath(root, runId);
118
+ if (!existsSync(path)) {
119
+ throw new Error(`Unknown Artifact Action Run: ${runId}`);
120
+ }
121
+ return JSON.parse(readFileSync(path, "utf8"));
122
+ }
123
+ export function stopArtifactActionRun(cwd, runId, options = {}) {
124
+ const root = ensureGitRepository(cwd);
125
+ const run = readArtifactActionRun(root, runId);
126
+ const runner = options.runner ?? ((command, args, commandOptions) => spawnCommand(command, args, { ...commandOptions, processEnv: options.processEnv }));
127
+ const env = resolveActionEnv(run.action, run.env, options.processEnv);
128
+ if (run.action.runner.type === "docker_compose") {
129
+ runActionCommand(runner, composeCommand(root, run, ["down"], env));
130
+ }
131
+ else if (run.action.runner.stopCommand) {
132
+ runActionCommand(runner, shellCommand(root, run, run.action.runner.stopCommand, env));
133
+ }
134
+ const removedAt = run.sourceWorktree?.path ? removeActionSourceWorktree(root, run.sourceWorktree.path) : undefined;
135
+ const stopped = {
136
+ ...run,
137
+ sourceWorktree: run.sourceWorktree ? { ...run.sourceWorktree, removedAt } : undefined,
138
+ status: "stopped",
139
+ stoppedAt: new Date().toISOString(),
140
+ updatedAt: new Date().toISOString()
141
+ };
142
+ if (options.store !== false) {
143
+ writeArtifactActionRun(root, stopped);
144
+ }
145
+ return stopped;
146
+ }
147
+ function resolveActionSource(root, input) {
148
+ if (input.moveId && input.commit) {
149
+ throw new Error("Artifact Action source accepts either moveId or commit, not both");
150
+ }
151
+ const store = loadDomainStore(root);
152
+ if (input.moveId) {
153
+ const move = store.board.moves.find(candidate => candidate.id === input.moveId);
154
+ if (!move) {
155
+ throw new Error(`No MOVE found for Artifact Action source: ${input.moveId}`);
156
+ }
157
+ const node = store.board.nodes.find(candidate => candidate.id === move.toNodeId);
158
+ return {
159
+ source: {
160
+ moveId: move.id,
161
+ commit: git(["rev-parse", "--verify", `${move.commit}^{commit}`], { cwd: root }).trim(),
162
+ ref: move.commit
163
+ },
164
+ actions: cloneActions(move.snapshot?.artifactActions ?? node?.artifactActions ?? [])
165
+ };
166
+ }
167
+ const ref = input.commit ?? "HEAD";
168
+ return {
169
+ source: {
170
+ commit: git(["rev-parse", "--verify", `${ref}^{commit}`], { cwd: root }).trim(),
171
+ ref
172
+ },
173
+ actions: cloneActions(store.board.artifactActions)
174
+ };
175
+ }
176
+ function validateActionSourceScope(action, source) {
177
+ if (action.sourceScope === "move" && !source.moveId) {
178
+ throw new Error(`Artifact Action ${action.id} can only run against a MOVE source`);
179
+ }
180
+ if (action.sourceScope === "commit" && source.moveId) {
181
+ throw new Error(`Artifact Action ${action.id} can only run against a commit source`);
182
+ }
183
+ }
184
+ function resolveActionEnv(action, overrides = {}, ambientEnv = {}) {
185
+ const env = {};
186
+ const declared = new Set();
187
+ for (const [name, spec] of Object.entries(action.env ?? {})) {
188
+ declared.add(name);
189
+ if ("default" in spec) {
190
+ env[name] = overrides[name] ?? String(spec.default);
191
+ }
192
+ else if ("value" in spec) {
193
+ env[name] = overrides[name] ?? String(spec.value);
194
+ }
195
+ else if ("alias" in spec) {
196
+ const alias = action.aliases?.[spec.alias];
197
+ if (!alias) {
198
+ throw new Error(`Artifact Action env ${name} references unknown alias: ${spec.alias}`);
199
+ }
200
+ env[name] = String(alias.containerPort ?? alias.target ?? "");
201
+ }
202
+ else if ("fromAliasUrl" in spec) {
203
+ const alias = action.aliases?.[spec.fromAliasUrl];
204
+ if (!alias) {
205
+ throw new Error(`Artifact Action env ${name} references unknown alias: ${spec.fromAliasUrl}`);
206
+ }
207
+ env[name] = alias.service && alias.containerPort ? `http://${alias.service}:${alias.containerPort}` : String(alias.target ?? "");
208
+ }
209
+ else if (spec.required) {
210
+ const value = overrides[name] ?? ambientEnv[name];
211
+ if (!value) {
212
+ throw new Error(`Artifact Action env ${name} is required but not set`);
213
+ }
214
+ env[name] = value;
215
+ }
216
+ }
217
+ for (const [name, value] of Object.entries(overrides)) {
218
+ if (!declared.has(name)) {
219
+ env[name] = value;
220
+ }
221
+ }
222
+ return env;
223
+ }
224
+ function sanitizeEnvForStorage(action, env) {
225
+ const sanitized = {};
226
+ for (const [name, value] of Object.entries(env)) {
227
+ const spec = action.env?.[name];
228
+ sanitized[name] = spec && "required" in spec && spec.secret ? "<secret>" : value;
229
+ }
230
+ return sanitized;
231
+ }
232
+ function actionCommands(root, action, run, env) {
233
+ if (action.runner.type === "docker_compose") {
234
+ return [
235
+ composeCommand(root, run, ["build"], env),
236
+ composeCommand(root, run, ["up", "-d"], env)
237
+ ];
238
+ }
239
+ return [shellCommand(root, run, action.runner.command, env)];
240
+ }
241
+ function composeCommand(root, run, args, env) {
242
+ if (run.action.runner.type !== "docker_compose") {
243
+ throw new Error(`Artifact Action ${run.actionId} does not use docker compose`);
244
+ }
245
+ const shortCommit = run.source.commit.slice(0, 12);
246
+ const projectName = sanitizeProjectName(expandTemplate(run.action.runner.projectName ?? `hunsu-${run.actionId}-${shortCommit}`, {
247
+ actionId: run.actionId,
248
+ runId: run.runId,
249
+ commit: run.source.commit,
250
+ shortCommit,
251
+ moveId: run.source.moveId ?? ""
252
+ }));
253
+ return {
254
+ command: "docker",
255
+ args: ["compose", "-f", resolve(run.sourceWorktree?.path ?? root, run.action.runner.file), "-p", projectName, ...args],
256
+ cwd: run.sourceWorktree?.path ?? root,
257
+ env
258
+ };
259
+ }
260
+ function shellCommand(root, run, command, env) {
261
+ return {
262
+ command: "sh",
263
+ args: ["-lc", command],
264
+ cwd: run.sourceWorktree?.path ?? root,
265
+ env
266
+ };
267
+ }
268
+ function runActionCommand(runner, command) {
269
+ const result = runner(command.command, command.args, { cwd: command.cwd, env: command.env });
270
+ if (result.status !== 0) {
271
+ throw new Error(`${command.command} ${command.args.join(" ")} failed\n${result.stderr || result.stdout}`);
272
+ }
273
+ return result;
274
+ }
275
+ function aliasesForAction(action, externalBase) {
276
+ if (!action.aliases) {
277
+ return undefined;
278
+ }
279
+ return Object.fromEntries(Object.entries(action.aliases).map(([alias, value]) => [
280
+ alias,
281
+ {
282
+ alias,
283
+ service: value.service,
284
+ containerPort: value.containerPort,
285
+ healthPath: value.healthPath,
286
+ target: value.target,
287
+ internalUrl: value.service && value.containerPort ? `http://${value.service}:${value.containerPort}` : value.target,
288
+ externalPath: `${externalBase}/${encodeURIComponent(alias)}/`
289
+ }
290
+ ]));
291
+ }
292
+ function attachDirectAliasUrls(root, run, runner, env) {
293
+ if (!run.aliases || run.action.runner.type !== "docker_compose") {
294
+ return run.aliases;
295
+ }
296
+ const runnerDefinition = run.action.runner;
297
+ return Object.fromEntries(Object.entries(run.aliases).map(([alias, value]) => {
298
+ if (!value.service || !value.containerPort) {
299
+ return [alias, value];
300
+ }
301
+ const result = runner("docker", ["compose", "-f", resolve(run.sourceWorktree?.path ?? root, runnerDefinition.file), "-p", sanitizeProjectName(expandTemplate(runnerDefinition.projectName ?? `hunsu-${run.actionId}-${run.source.commit.slice(0, 12)}`, {
302
+ actionId: run.actionId,
303
+ runId: run.runId,
304
+ commit: run.source.commit,
305
+ shortCommit: run.source.commit.slice(0, 12),
306
+ moveId: run.source.moveId ?? ""
307
+ })), "port", value.service, String(value.containerPort)], {
308
+ cwd: run.sourceWorktree?.path ?? root,
309
+ env
310
+ });
311
+ if (result.status !== 0 || !result.stdout.trim()) {
312
+ return [alias, value];
313
+ }
314
+ return [alias, { ...value, directUrl: formatDirectUrl(result.stdout.trim()) }];
315
+ }));
316
+ }
317
+ function createActionSourceWorktree(root, runId, commit, createdAt, requestedWorktreeRoot) {
318
+ const worktreeRoot = resolve(requestedWorktreeRoot ?? join(tmpdir(), "hunsu-action-runs", `${basename(root)}-${hashPath(root)}`));
319
+ const path = join(worktreeRoot, sanitizeRunId(runId));
320
+ mkdirSync(worktreeRoot, { recursive: true });
321
+ if (existsSync(path)) {
322
+ removeActionSourceWorktree(root, path);
323
+ rmSync(path, { recursive: true, force: true });
324
+ }
325
+ git(["worktree", "add", "--detach", path, commit], { cwd: root });
326
+ return { path, commit, createdAt };
327
+ }
328
+ function removeActionSourceWorktree(root, path) {
329
+ const removedAt = new Date().toISOString();
330
+ if (!existsSync(path)) {
331
+ return removedAt;
332
+ }
333
+ try {
334
+ git(["worktree", "remove", "--force", path], { cwd: root });
335
+ }
336
+ catch (_error) {
337
+ rmSync(path, { recursive: true, force: true });
338
+ git(["worktree", "prune"], { cwd: root });
339
+ }
340
+ return removedAt;
341
+ }
342
+ function writeArtifactActionRun(root, run) {
343
+ mkdirSync(actionRunStoreDir(root), { recursive: true });
344
+ writeFileSync(actionRunRecordPath(root, run.runId), `${JSON.stringify(run, null, 2)}\n`, "utf8");
345
+ }
346
+ function actionRunStoreDir(root) {
347
+ return join(root, ".hunsu", "action-runs");
348
+ }
349
+ function actionRunRecordPath(root, runId) {
350
+ return join(actionRunStoreDir(root), `${sanitizeRunId(runId)}.json`);
351
+ }
352
+ function actionRunBasePath(roadmapId, runId) {
353
+ return roadmapId
354
+ ? `/api/roadmaps/${encodeURIComponent(roadmapId)}/action-runs/${encodeURIComponent(runId)}/proxy`
355
+ : `/api/action-runs/${encodeURIComponent(runId)}/proxy`;
356
+ }
357
+ function artifactActionRunId(actionId, source, now) {
358
+ return sanitizeRunId(`${actionId}-${source.moveId ?? source.commit.slice(0, 12)}-${now.replace(/[^0-9A-Za-z]/g, "").slice(0, 14)}`);
359
+ }
360
+ function sanitizeRunId(value) {
361
+ return value.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "action-run";
362
+ }
363
+ function sanitizeProjectName(value) {
364
+ return value.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63) || "hunsu-action";
365
+ }
366
+ function expandTemplate(value, variables) {
367
+ return value.replace(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g, (_, key) => variables[key] ?? "");
368
+ }
369
+ function hashPath(path) {
370
+ return createHash("sha256").update(path).digest("hex").slice(0, 12);
371
+ }
372
+ function formatDirectUrl(output) {
373
+ const line = output.split(/\r?\n/).find(Boolean) ?? output;
374
+ const match = line.match(/(?:0\.0\.0\.0|127\.0\.0\.1|localhost|\[::\]|::):(\d+)$/);
375
+ if (match) {
376
+ return `http://127.0.0.1:${match[1]}`;
377
+ }
378
+ if (/^https?:\/\//.test(line)) {
379
+ return line;
380
+ }
381
+ return `http://${line}`;
382
+ }
383
+ function spawnCommand(command, args, options) {
384
+ const result = spawnSync(command, args, {
385
+ cwd: options.cwd,
386
+ env: { ...filterProcessEnv(options.processEnv), ...options.env },
387
+ encoding: "utf8",
388
+ maxBuffer: 16 * 1024 * 1024
389
+ });
390
+ return { status: result.status ?? 1, stdout: result.stdout, stderr: result.stderr };
391
+ }
392
+ function filterProcessEnv(env) {
393
+ if (env === undefined) {
394
+ return undefined;
395
+ }
396
+ const next = {};
397
+ for (const [key, value] of Object.entries(env)) {
398
+ if (value !== undefined) {
399
+ next[key] = value;
400
+ }
401
+ }
402
+ return next;
403
+ }
404
+ function cloneActions(actions) {
405
+ return actions.map(cloneAction).sort((left, right) => left.displayOrder - right.displayOrder || String(left.id).localeCompare(String(right.id)));
406
+ }
407
+ function cloneAction(action) {
408
+ return {
409
+ ...action,
410
+ env: action.env ? Object.fromEntries(Object.entries(action.env).map(([key, value]) => [key, { ...value }])) : undefined,
411
+ runner: { ...action.runner },
412
+ aliases: action.aliases ? Object.fromEntries(Object.entries(action.aliases).map(([key, value]) => [key, { ...value }])) : undefined,
413
+ evidence: action.evidence ? { ...action.evidence, paths: action.evidence.paths?.slice() } : undefined
414
+ };
415
+ }
@@ -0,0 +1,15 @@
1
+ import { type Result } from "@hunsu/protocol";
2
+ import type { Board, BoardEvent, CommitRecord, HunsuEventType, MoveEventStatus } from "./model.ts";
3
+ export type TrailerParseErrorCode = "invalid_trailer_block" | "missing_trailer" | "invalid_hunsu_event_type" | "invalid_move_number" | "invalid_move_status" | "invalid_trailer_value";
4
+ export type TrailerParseError = {
5
+ type: "TrailerParseError";
6
+ code: TrailerParseErrorCode;
7
+ commitSha: string;
8
+ trailer?: string;
9
+ value?: string;
10
+ message: string;
11
+ };
12
+ export declare function commitToBoardEvent(commit: CommitRecord): Result<BoardEvent | null, TrailerParseError>;
13
+ export declare function createBoardFromCommits(commits: CommitRecord[]): Board;
14
+ export declare function parseHunsuEventType(value: string | undefined, commitSha: string): HunsuEventType | undefined;
15
+ export declare function parseMoveEventStatus(value: string, commitSha: string): MoveEventStatus;