dtu-github-actions 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,110 @@
1
+ # Functional Source License, Version 1.1, MIT Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-MIT
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 RedwoodJS Inc
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the MIT license that is effective on the second anniversary of the date we make
91
+ the Software available. On or after that date, you may use the Software under
92
+ the MIT license, in which case the following will apply:
93
+
94
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
95
+ this software and associated documentation files (the "Software"), to deal in
96
+ the Software without restriction, including without limitation the rights to
97
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
98
+ of the Software, and to permit persons to whom the Software is furnished to do
99
+ so, subject to the following conditions:
100
+
101
+ The above copyright notice and this permission notice shall be included in all
102
+ copies or substantial portions of the Software.
103
+
104
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
105
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
106
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
107
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
108
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
109
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
110
+ SOFTWARE.
@@ -430,8 +430,39 @@ export function registerActionRoutes(app) {
430
430
  ...(req.query?.includeRecords ? { records } : {}),
431
431
  }));
432
432
  });
433
- // 18. Generic Step Outputs Handler
433
+ // 18. Step Outputs Handler — capture outputs sent by the runner
434
434
  app.post("/_apis/distributedtask/hubs/:hub/plans/:planId/outputs", (req, res) => {
435
+ const planId = req.params.planId;
436
+ const payload = req.body || {};
437
+ // The runner posts step outputs as { stepId: { <name>: { value: <val> } } }
438
+ // Persist to the runner's log directory as outputs.json
439
+ const logDir = state.planToLogDir.get(planId);
440
+ if (logDir && payload && typeof payload === "object") {
441
+ try {
442
+ const outputsPath = path.join(logDir, "outputs.json");
443
+ // Merge with existing outputs
444
+ let existing = {};
445
+ try {
446
+ existing = JSON.parse(fs.readFileSync(outputsPath, "utf-8"));
447
+ }
448
+ catch {
449
+ /* no existing file */
450
+ }
451
+ // Flatten step outputs: { stepId: { name: { value: v } } } → { "stepId.name": v }
452
+ for (const [stepId, outputs] of Object.entries(payload)) {
453
+ if (outputs && typeof outputs === "object") {
454
+ for (const [name, meta] of Object.entries(outputs)) {
455
+ const value = meta?.value ?? (typeof meta === "string" ? meta : "");
456
+ existing[`${stepId}.${name}`] = value;
457
+ }
458
+ }
459
+ }
460
+ fs.writeFileSync(outputsPath, JSON.stringify(existing, null, 2));
461
+ }
462
+ catch {
463
+ /* best-effort */
464
+ }
465
+ }
435
466
  res.writeHead(200);
436
467
  res.end(JSON.stringify({ value: {} }));
437
468
  });
@@ -495,6 +526,8 @@ export function registerActionRoutes(app) {
495
526
  }
496
527
  const RUNNER_INTERNAL_RE = /^\[(?:RUNNER|WORKER) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}Z (?:INFO|WARN|ERR)\s/;
497
528
  let content = "";
529
+ // Collect agent-ci-output lines for cross-job output passing
530
+ const outputEntries = [];
498
531
  for (const rawLine of lines) {
499
532
  const line = rawLine.trimEnd();
500
533
  if (!line) {
@@ -505,6 +538,15 @@ export function registerActionRoutes(app) {
505
538
  const stripped = line
506
539
  .replace(/^\uFEFF?\d{4}-\d{2}-\d{2}T[\d:.]+Z\s*/, "")
507
540
  .replace(/^\uFEFF/, "");
541
+ // Parse agent-ci-output lines: ::agent-ci-output::key=value
542
+ if (stripped.startsWith("::agent-ci-output::")) {
543
+ const kv = stripped.slice("::agent-ci-output::".length);
544
+ const eqIdx = kv.indexOf("=");
545
+ if (eqIdx > 0) {
546
+ outputEntries.push([kv.slice(0, eqIdx), kv.slice(eqIdx + 1)]);
547
+ }
548
+ continue; // Don't include in regular step logs
549
+ }
508
550
  if (!stripped ||
509
551
  stripped.startsWith("##[") ||
510
552
  stripped.startsWith("[command]") ||
@@ -513,6 +555,26 @@ export function registerActionRoutes(app) {
513
555
  }
514
556
  content += stripped + "\n";
515
557
  }
558
+ // Persist captured outputs to outputs.json
559
+ if (outputEntries.length > 0) {
560
+ try {
561
+ const outputsPath = path.join(logDir, "outputs.json");
562
+ let existing = {};
563
+ try {
564
+ existing = JSON.parse(fs.readFileSync(outputsPath, "utf-8"));
565
+ }
566
+ catch {
567
+ /* no existing file */
568
+ }
569
+ for (const [key, value] of outputEntries) {
570
+ existing[key] = value;
571
+ }
572
+ fs.writeFileSync(outputsPath, JSON.stringify(existing, null, 2));
573
+ }
574
+ catch {
575
+ /* best-effort */
576
+ }
577
+ }
516
578
  if (content) {
517
579
  try {
518
580
  let stepName = state.recordToStepName.get(recordId);
@@ -23,13 +23,16 @@ export function registerDtuRoutes(app) {
23
23
  Id: crypto.randomUUID(),
24
24
  }));
25
25
  const jobPayload = { ...payload, steps: mappedSteps };
26
- // Store job both in the generic map AND keyed by runner name for per-runner dispatch.
27
- // The runnerName is passed in the body (from local-job.ts which spreads the Job object).
26
+ // Store the job for dispatch. Runner-targeted jobs go ONLY into runnerJobs
27
+ // to prevent other runners from stealing them via the generic pool fallback.
28
+ // Jobs without a runnerName go into the generic pool for any runner to pick up.
28
29
  const runnerName = payload.runnerName;
29
- state.jobs.set(jobId, jobPayload);
30
30
  if (runnerName) {
31
31
  state.runnerJobs.set(runnerName, jobPayload);
32
32
  }
33
+ else {
34
+ state.jobs.set(jobId, jobPayload);
35
+ }
33
36
  console.log(`[DTU] Seeded job: ${jobId}${runnerName ? ` for runner ${runnerName}` : ""}`);
34
37
  // Notify only the pending poll that belongs to this runner (if any already waiting).
35
38
  const baseUrl = getBaseUrl(req);
@@ -136,6 +136,139 @@ describe("DTU Server", () => {
136
136
  const body = JSON.parse(pollRes.body.Body);
137
137
  expect(body.JobDisplayName).toBe("poll-job");
138
138
  });
139
+ it("should dispatch a job seeded AFTER polling begins (issue #47 race condition)", async () => {
140
+ const runnerName = "agent-ci-race-test";
141
+ // 1. Register the runner with the DTU (so sessionToRunner mapping exists)
142
+ await request("POST", "/_dtu/start-runner", {
143
+ runnerName,
144
+ logDir: "/tmp/agent-ci-race-test-logs",
145
+ timelineDir: "/tmp/agent-ci-race-test-logs",
146
+ });
147
+ // 2. Create a session as this runner
148
+ const sessionRes = await request("POST", "/_apis/distributedtask/pools/1/sessions", {
149
+ agent: { name: runnerName },
150
+ });
151
+ const sessionId = sessionRes.body.sessionId;
152
+ expect(sessionRes.status).toBe(200);
153
+ // 3. Start the long-poll — this will block for up to 20s waiting for a job.
154
+ // The runner arrives BEFORE the job is seeded, exactly reproducing the race.
155
+ const pollPromise = request("GET", `/_apis/distributedtask/pools/1/messages?sessionId=${sessionId}`);
156
+ // 4. Give the event loop a tick so the poll handler registers in pendingPolls
157
+ await new Promise((r) => setTimeout(r, 50));
158
+ // 5. Now seed a job targeted at this runner — the seed handler should
159
+ // find the pending poll and dispatch immediately.
160
+ const seedRes = await request("POST", "/_dtu/seed", {
161
+ id: 999,
162
+ name: "race-test-job",
163
+ runnerName,
164
+ });
165
+ expect(seedRes.status).toBe(201);
166
+ // 6. The poll should resolve almost instantly with the job (200),
167
+ // NOT after the 20s timeout (204).
168
+ const pollRes = await pollPromise;
169
+ expect(pollRes.status).toBe(200);
170
+ expect(pollRes.body.MessageType).toBe("PipelineAgentJobRequest");
171
+ const body = JSON.parse(pollRes.body.Body);
172
+ expect(body.JobDisplayName).toBe("race-test-job");
173
+ }, 10_000);
174
+ it("should dispatch jobs to 8 concurrent runners seeded after polling (--all mode stress)", async () => {
175
+ const RUNNER_COUNT = 8;
176
+ const runners = [];
177
+ // 1. Register and create sessions for all runners
178
+ for (let i = 0; i < RUNNER_COUNT; i++) {
179
+ const name = `agent-ci-stress-${i + 1}`;
180
+ await request("POST", "/_dtu/start-runner", {
181
+ runnerName: name,
182
+ logDir: `/tmp/agent-ci-stress-${i + 1}-logs`,
183
+ timelineDir: `/tmp/agent-ci-stress-${i + 1}-logs`,
184
+ });
185
+ const sessionRes = await request("POST", "/_apis/distributedtask/pools/1/sessions", {
186
+ agent: { name },
187
+ });
188
+ runners.push({ name, sessionId: sessionRes.body.sessionId });
189
+ }
190
+ // 2. Start all polls concurrently — all runners are waiting before any job is seeded
191
+ const pollPromises = runners.map((r) => request("GET", `/_apis/distributedtask/pools/1/messages?sessionId=${r.sessionId}`));
192
+ // 3. Let the polls register in pendingPolls
193
+ await new Promise((r) => setTimeout(r, 100));
194
+ // 4. Seed all jobs with staggered timing (simulating concurrent executeLocalJob calls)
195
+ for (let i = 0; i < RUNNER_COUNT; i++) {
196
+ await request("POST", "/_dtu/seed", {
197
+ id: 2000 + i,
198
+ name: `stress-job-${i + 1}`,
199
+ runnerName: runners[i].name,
200
+ });
201
+ // Small stagger like real concurrent CLI calls
202
+ if (i < RUNNER_COUNT - 1) {
203
+ await new Promise((r) => setTimeout(r, 5));
204
+ }
205
+ }
206
+ // 5. ALL polls should resolve with 200 (their specific job), not 204
207
+ const pollResults = await Promise.all(pollPromises);
208
+ for (let i = 0; i < RUNNER_COUNT; i++) {
209
+ expect(pollResults[i].status).toBe(200);
210
+ expect(pollResults[i].body.MessageType).toBe("PipelineAgentJobRequest");
211
+ const body = JSON.parse(pollResults[i].body.Body);
212
+ expect(body.JobDisplayName).toBe(`stress-job-${i + 1}`);
213
+ }
214
+ }, 15_000);
215
+ it("should NOT let runner B steal runner A's job from the generic pool (issue #47)", async () => {
216
+ // This reproduces the core race in --all mode:
217
+ // 1. Job for runner A is seeded
218
+ // 2. Runner B creates a session and polls BEFORE its own job is seeded
219
+ // 3. BUG: Runner B falls through to the generic state.jobs pool and steals A's job
220
+ // 4. Runner B's actual job arrives later, but A's real runner never gets its job
221
+ const runnerA = "agent-ci-runner-A";
222
+ const runnerB = "agent-ci-runner-B";
223
+ // Register both runners
224
+ await request("POST", "/_dtu/start-runner", {
225
+ runnerName: runnerA,
226
+ logDir: "/tmp/agent-ci-A-logs",
227
+ timelineDir: "/tmp/agent-ci-A-logs",
228
+ });
229
+ await request("POST", "/_dtu/start-runner", {
230
+ runnerName: runnerB,
231
+ logDir: "/tmp/agent-ci-B-logs",
232
+ timelineDir: "/tmp/agent-ci-B-logs",
233
+ });
234
+ // Seed runner A's job
235
+ await request("POST", "/_dtu/seed", {
236
+ id: 3001,
237
+ name: "job-for-A",
238
+ runnerName: runnerA,
239
+ });
240
+ // Runner B creates a session and polls — its job hasn't been seeded yet.
241
+ const sessionB = await request("POST", "/_apis/distributedtask/pools/1/sessions", {
242
+ agent: { name: runnerB },
243
+ });
244
+ const pollBPromise = request("GET", `/_apis/distributedtask/pools/1/messages?sessionId=${sessionB.body.sessionId}`);
245
+ // Wait 200ms — if B stole A's job, the poll would have resolved instantly.
246
+ let pollBResolved = false;
247
+ pollBPromise.then(() => {
248
+ pollBResolved = true;
249
+ });
250
+ await new Promise((r) => setTimeout(r, 200));
251
+ expect(pollBResolved).toBe(false); // B should still be long-polling, NOT holding A's job
252
+ // Now seed runner B's actual job — this unblocks B's long-poll via notify-on-seed
253
+ await request("POST", "/_dtu/seed", {
254
+ id: 3002,
255
+ name: "job-for-B",
256
+ runnerName: runnerB,
257
+ });
258
+ // B should now receive its own job
259
+ const pollB = await pollBPromise;
260
+ expect(pollB.status).toBe(200);
261
+ const bodyB = JSON.parse(pollB.body.Body);
262
+ expect(bodyB.JobDisplayName).toBe("job-for-B");
263
+ // Runner A should still get its own job (not stolen)
264
+ const sessionA = await request("POST", "/_apis/distributedtask/pools/1/sessions", {
265
+ agent: { name: runnerA },
266
+ });
267
+ const pollA = await request("GET", `/_apis/distributedtask/pools/1/messages?sessionId=${sessionA.body.sessionId}`);
268
+ expect(pollA.status).toBe(200);
269
+ const bodyA = JSON.parse(pollA.body.Body);
270
+ expect(bodyA.JobDisplayName).toBe("job-for-A");
271
+ }, 10_000);
139
272
  it("should log unhandled requests to 404.log", async () => {
140
273
  const logDir = path.dirname(getDtuLogPath());
141
274
  const logFile = path.join(logDir, "404.log");
package/package.json CHANGED
@@ -1,10 +1,15 @@
1
1
  {
2
2
  "name": "dtu-github-actions",
3
- "version": "0.1.0",
3
+ "version": "0.3.1",
4
4
  "description": "Digital Twin Universe - GitHub Actions Mock and Simulation",
5
5
  "keywords": [],
6
6
  "license": "FSL-1.1-MIT",
7
7
  "author": "",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/redwoodjs/agent-ci.git",
11
+ "directory": "packages/dtu-github-actions"
12
+ },
8
13
  "files": [
9
14
  "dist",
10
15
  "README.md"
@@ -18,13 +23,6 @@
18
23
  "publishConfig": {
19
24
  "access": "public"
20
25
  },
21
- "scripts": {
22
- "dev": "(pnpm dlx kill-port 8910 || true) && tsx src/server/start.ts",
23
- "simulate": "tsx src/simulate.ts",
24
- "build": "tsgo",
25
- "typecheck": "tsgo",
26
- "test": "vitest run"
27
- },
28
26
  "dependencies": {
29
27
  "body-parser": "^2.2.2",
30
28
  "jsonc-parser": "^3.3.1",
@@ -39,5 +37,15 @@
39
37
  "execa": "^9.6.1",
40
38
  "tsx": "^4.19.2",
41
39
  "vitest": "^4.0.18"
40
+ },
41
+ "engines": {
42
+ "node": ">=22"
43
+ },
44
+ "scripts": {
45
+ "dev": "(pnpm dlx kill-port 8910 || true) && tsx src/server/start.ts",
46
+ "simulate": "tsx src/simulate.ts",
47
+ "build": "tsgo",
48
+ "typecheck": "tsgo",
49
+ "test": "vitest run"
42
50
  }
43
- }
51
+ }