@kody-ade/kody-engine 0.3.13 → 0.3.14

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/dist/bin/kody.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // package.json
4
4
  var package_default = {
5
5
  name: "@kody-ade/kody-engine",
6
- version: "0.3.13",
6
+ version: "0.3.14",
7
7
  description: "kody \u2014 autonomous development engine. Single-session Claude Code agent behind a generic executor + declarative executable profiles.",
8
8
  license: "MIT",
9
9
  type: "module",
@@ -2732,6 +2732,70 @@ function postPrReviewComment(prNumber, body, cwd) {
2732
2732
  }
2733
2733
  }
2734
2734
 
2735
+ // src/scripts/dispatchManagerTicks.ts
2736
+ var dispatchManagerTicks = async (ctx, _profile, args) => {
2737
+ ctx.skipAgent = true;
2738
+ const label = String(args?.label ?? "");
2739
+ const targetExecutable = String(args?.targetExecutable ?? "");
2740
+ if (!label) throw new Error("dispatchManagerTicks: `with.label` is required");
2741
+ if (!targetExecutable) throw new Error("dispatchManagerTicks: `with.targetExecutable` is required");
2742
+ const issueArg = String(args?.issueArg ?? "issue");
2743
+ const issues = listIssuesByLabel(label, ctx.cwd);
2744
+ ctx.data.managerIssueCount = issues.length;
2745
+ if (issues.length === 0) {
2746
+ process.stdout.write(`[manager] no open issues with label "${label}"
2747
+ `);
2748
+ return;
2749
+ }
2750
+ process.stdout.write(`[manager] ticking ${issues.length} issue(s) via ${targetExecutable}
2751
+ `);
2752
+ const results = [];
2753
+ for (const issue of issues) {
2754
+ process.stdout.write(`[manager] \u2192 tick #${issue.number}: ${issue.title}
2755
+ `);
2756
+ try {
2757
+ const out = await runExecutable(targetExecutable, {
2758
+ cliArgs: { [issueArg]: issue.number },
2759
+ cwd: ctx.cwd,
2760
+ config: ctx.config,
2761
+ verbose: ctx.verbose,
2762
+ quiet: ctx.quiet
2763
+ });
2764
+ results.push({ issue: issue.number, exitCode: out.exitCode, reason: out.reason });
2765
+ if (out.exitCode !== 0) {
2766
+ process.stderr.write(`[manager] tick #${issue.number} failed (exit ${out.exitCode}): ${out.reason ?? ""}
2767
+ `);
2768
+ }
2769
+ } catch (err) {
2770
+ const msg = err instanceof Error ? err.message : String(err);
2771
+ process.stderr.write(`[manager] tick #${issue.number} crashed: ${msg}
2772
+ `);
2773
+ results.push({ issue: issue.number, exitCode: 99, reason: msg });
2774
+ }
2775
+ }
2776
+ ctx.data.managerTickResults = results;
2777
+ ctx.output.exitCode = 0;
2778
+ };
2779
+ function listIssuesByLabel(label, cwd) {
2780
+ let raw = "";
2781
+ try {
2782
+ raw = gh2(
2783
+ ["issue", "list", "--state", "open", "--label", label, "--limit", "100", "--json", "number,title"],
2784
+ { cwd }
2785
+ );
2786
+ } catch {
2787
+ return [];
2788
+ }
2789
+ let list;
2790
+ try {
2791
+ list = JSON.parse(raw);
2792
+ } catch {
2793
+ return [];
2794
+ }
2795
+ if (!Array.isArray(list)) return [];
2796
+ return list.filter((x) => typeof x.number === "number" && typeof x.title === "string").map((x) => ({ number: x.number, title: x.title }));
2797
+ }
2798
+
2735
2799
  // src/pr.ts
2736
2800
  var TITLE_MAX = 72;
2737
2801
  function stripTitlePrefixes(raw) {
@@ -3744,6 +3808,112 @@ var loadIssueContext = async (ctx) => {
3744
3808
  ctx.data.commentTargetNumber = issueNumber;
3745
3809
  };
3746
3810
 
3811
+ // src/scripts/issueStateComment.ts
3812
+ function isStateEnvelope(x) {
3813
+ if (x === null || typeof x !== "object") return false;
3814
+ const o = x;
3815
+ return o.version === 1 && typeof o.rev === "number" && Number.isInteger(o.rev) && o.rev >= 0 && typeof o.cursor === "string" && typeof o.done === "boolean" && o.data !== null && typeof o.data === "object" && !Array.isArray(o.data);
3816
+ }
3817
+ function formatStateCommentBody(marker, state) {
3818
+ return `<!-- ${marker} -->
3819
+
3820
+ \`\`\`json
3821
+ ${JSON.stringify(state, null, 2)}
3822
+ \`\`\`
3823
+ `;
3824
+ }
3825
+ function parseStateCommentBody(marker, body) {
3826
+ const markerLine = `<!-- ${marker} -->`;
3827
+ if (!body.trimStart().startsWith(markerLine)) return null;
3828
+ const fenceOpen = body.indexOf("```json");
3829
+ if (fenceOpen === -1) return null;
3830
+ const after = body.slice(fenceOpen + "```json".length);
3831
+ const fenceClose = after.indexOf("```");
3832
+ if (fenceClose === -1) return null;
3833
+ const jsonText = after.slice(0, fenceClose).trim();
3834
+ let parsed;
3835
+ try {
3836
+ parsed = JSON.parse(jsonText);
3837
+ } catch {
3838
+ return null;
3839
+ }
3840
+ return isStateEnvelope(parsed) ? parsed : null;
3841
+ }
3842
+ function listIssueComments(owner, repo, issueNumber, cwd) {
3843
+ const raw = gh2(["api", "--paginate", `repos/${owner}/${repo}/issues/${issueNumber}/comments`], { cwd });
3844
+ let parsed;
3845
+ try {
3846
+ parsed = JSON.parse(raw);
3847
+ } catch {
3848
+ return [];
3849
+ }
3850
+ if (!Array.isArray(parsed)) return [];
3851
+ return parsed.filter((c) => typeof c.id === "number" && typeof c.node_id === "string" && typeof c.body === "string").map((c) => ({ id: c.id, node_id: c.node_id, body: c.body }));
3852
+ }
3853
+ function findStateComment2(owner, repo, issueNumber, marker, cwd) {
3854
+ const comments = listIssueComments(owner, repo, issueNumber, cwd);
3855
+ for (const c of comments) {
3856
+ const state = parseStateCommentBody(marker, c.body);
3857
+ if (!state) continue;
3858
+ return { commentId: c.id, commentNodeId: c.node_id, state };
3859
+ }
3860
+ return null;
3861
+ }
3862
+ function createStateComment(owner, repo, issueNumber, marker, state, cwd) {
3863
+ const body = formatStateCommentBody(marker, state);
3864
+ const raw = gh2(
3865
+ ["api", "--method", "POST", `repos/${owner}/${repo}/issues/${issueNumber}/comments`, "--input", "-"],
3866
+ { cwd, input: JSON.stringify({ body }) }
3867
+ );
3868
+ const parsed = JSON.parse(raw);
3869
+ try {
3870
+ minimizeComment(parsed.node_id, cwd);
3871
+ } catch {
3872
+ }
3873
+ return { commentId: parsed.id, commentNodeId: parsed.node_id, state };
3874
+ }
3875
+ function updateStateComment(owner, repo, commentId, commentNodeId, marker, state, cwd) {
3876
+ const body = formatStateCommentBody(marker, state);
3877
+ gh2(
3878
+ ["api", "--method", "PATCH", `repos/${owner}/${repo}/issues/comments/${commentId}`, "--input", "-"],
3879
+ { cwd, input: JSON.stringify({ body }) }
3880
+ );
3881
+ try {
3882
+ minimizeComment(commentNodeId, cwd);
3883
+ } catch {
3884
+ }
3885
+ }
3886
+ function minimizeComment(nodeId, cwd) {
3887
+ const mutation = "mutation($id: ID!) { minimizeComment(input: { classifier: OUTDATED, subjectId: $id }) { minimizedComment { isMinimized } } }";
3888
+ gh2(["api", "graphql", "-f", `query=${mutation}`, "-f", `id=${nodeId}`], { cwd });
3889
+ }
3890
+
3891
+ // src/scripts/loadIssueStateComment.ts
3892
+ var loadIssueStateComment = async (ctx, _profile, args) => {
3893
+ const marker = String(args?.marker ?? "");
3894
+ if (!marker) {
3895
+ throw new Error("loadIssueStateComment: `with.marker` is required");
3896
+ }
3897
+ const issueArg = String(args?.issueArg ?? "issue");
3898
+ const issueNumber = Number(ctx.args[issueArg]);
3899
+ if (!Number.isFinite(issueNumber) || issueNumber <= 0) {
3900
+ throw new Error(`loadIssueStateComment: ctx.args.${issueArg} must be a positive integer`);
3901
+ }
3902
+ const owner = ctx.config.github.owner;
3903
+ const repo = ctx.config.github.repo;
3904
+ if (!owner || !repo) {
3905
+ throw new Error("loadIssueStateComment: ctx.config.github.owner/repo must be set");
3906
+ }
3907
+ const issue = getIssue(issueNumber, ctx.cwd);
3908
+ const loaded = findStateComment2(owner, repo, issueNumber, marker, ctx.cwd);
3909
+ ctx.data.stateMarker = marker;
3910
+ ctx.data.issueIntent = issue.body;
3911
+ ctx.data.issueTitle = issue.title;
3912
+ ctx.data.issueNumber = String(issueNumber);
3913
+ ctx.data.issueStateComment = loaded;
3914
+ ctx.data.issueStateJson = loaded ? JSON.stringify(loaded.state, null, 2) : "null";
3915
+ };
3916
+
3747
3917
  // src/scripts/loadPriorArt.ts
3748
3918
  var PER_PR_DIFF_MAX_BYTES = 8e3;
3749
3919
  var TOTAL_MAX_BYTES = 3e4;
@@ -3911,6 +4081,53 @@ function makeAction(type, payload) {
3911
4081
  return { type, payload, timestamp: (/* @__PURE__ */ new Date()).toISOString() };
3912
4082
  }
3913
4083
 
4084
+ // src/scripts/parseIssueStateFromAgentResult.ts
4085
+ function isPartialEnvelope(x) {
4086
+ if (x === null || typeof x !== "object") return false;
4087
+ const o = x;
4088
+ return typeof o.cursor === "string" && o.cursor.length > 0 && typeof o.done === "boolean" && o.data !== null && typeof o.data === "object" && !Array.isArray(o.data);
4089
+ }
4090
+ var parseIssueStateFromAgentResult = async (ctx, _profile, agentResult, args) => {
4091
+ const fenceLabel = String(args?.fenceLabel ?? "");
4092
+ if (!fenceLabel) {
4093
+ throw new Error("parseIssueStateFromAgentResult: `with.fenceLabel` is required");
4094
+ }
4095
+ if (!agentResult) {
4096
+ ctx.data.nextStateParseError = "agent did not run";
4097
+ return;
4098
+ }
4099
+ const fenceRegex = new RegExp("```" + escapeRegex(fenceLabel) + "\\s*\\n([\\s\\S]*?)\\n```", "m");
4100
+ const match = fenceRegex.exec(agentResult.finalText);
4101
+ if (!match) {
4102
+ ctx.data.nextStateParseError = `agent did not emit a \`${fenceLabel}\` fenced block`;
4103
+ return;
4104
+ }
4105
+ let parsed;
4106
+ try {
4107
+ parsed = JSON.parse(match[1].trim());
4108
+ } catch (err) {
4109
+ ctx.data.nextStateParseError = `state JSON parse error: ${err instanceof Error ? err.message : String(err)}`;
4110
+ return;
4111
+ }
4112
+ if (!isPartialEnvelope(parsed)) {
4113
+ ctx.data.nextStateParseError = "state must be an object with string `cursor`, object `data`, and boolean `done`";
4114
+ return;
4115
+ }
4116
+ const loaded = ctx.data.issueStateComment;
4117
+ const prevRev = loaded?.state.rev ?? 0;
4118
+ const next = {
4119
+ version: 1,
4120
+ rev: prevRev + 1,
4121
+ cursor: parsed.cursor,
4122
+ data: parsed.data,
4123
+ done: parsed.done
4124
+ };
4125
+ ctx.data.nextIssueState = next;
4126
+ };
4127
+ function escapeRegex(s) {
4128
+ return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
4129
+ }
4130
+
3914
4131
  // src/scripts/persistArtifacts.ts
3915
4132
  var persistArtifacts = async (ctx, profile) => {
3916
4133
  if (profile.outputArtifacts.length === 0) return;
@@ -5232,6 +5449,42 @@ var watchStalePrsFlow = async (ctx) => {
5232
5449
  ctx.data.staleCount = stale.length;
5233
5450
  };
5234
5451
 
5452
+ // src/scripts/writeIssueStateComment.ts
5453
+ var writeIssueStateComment = async (ctx, _profile, _agentResult, args) => {
5454
+ const marker = String(args?.marker ?? "");
5455
+ if (!marker) {
5456
+ throw new Error("writeIssueStateComment: `with.marker` is required");
5457
+ }
5458
+ const issueArg = String(args?.issueArg ?? "issue");
5459
+ const issueNumber = Number(ctx.args[issueArg]);
5460
+ if (!Number.isFinite(issueNumber) || issueNumber <= 0) {
5461
+ throw new Error(`writeIssueStateComment: ctx.args.${issueArg} must be a positive integer`);
5462
+ }
5463
+ const parseError = ctx.data.nextStateParseError;
5464
+ if (parseError) {
5465
+ process.stderr.write(`[kody] state write skipped: ${parseError}
5466
+ `);
5467
+ if (ctx.output.exitCode === 0) ctx.output.exitCode = 1;
5468
+ if (!ctx.output.reason) ctx.output.reason = `next-state parse failed: ${parseError}`;
5469
+ return;
5470
+ }
5471
+ const next = ctx.data.nextIssueState;
5472
+ if (!next) {
5473
+ return;
5474
+ }
5475
+ const owner = ctx.config.github.owner;
5476
+ const repo = ctx.config.github.repo;
5477
+ if (!owner || !repo) {
5478
+ throw new Error("writeIssueStateComment: ctx.config.github.owner/repo must be set");
5479
+ }
5480
+ const loaded = ctx.data.issueStateComment;
5481
+ if (loaded) {
5482
+ updateStateComment(owner, repo, loaded.commentId, loaded.commentNodeId, marker, next, ctx.cwd);
5483
+ } else {
5484
+ createStateComment(owner, repo, issueNumber, marker, next, ctx.cwd);
5485
+ }
5486
+ };
5487
+
5235
5488
  // src/scripts/writeRunSummary.ts
5236
5489
  import * as fs20 from "fs";
5237
5490
  var writeRunSummary = async (ctx, profile) => {
@@ -5274,6 +5527,7 @@ var preflightScripts = {
5274
5527
  watchStalePrsFlow,
5275
5528
  loadTaskState,
5276
5529
  loadIssueContext,
5530
+ loadIssueStateComment,
5277
5531
  loadConventions,
5278
5532
  loadCoverageRules,
5279
5533
  loadPriorArt,
@@ -5286,10 +5540,13 @@ var preflightScripts = {
5286
5540
  setLifecycleLabel,
5287
5541
  skipAgent,
5288
5542
  classifyByLabel,
5289
- diagMcp
5543
+ diagMcp,
5544
+ dispatchManagerTicks
5290
5545
  };
5291
5546
  var postflightScripts = {
5292
5547
  parseAgentResult: parseAgentResult2,
5548
+ parseIssueStateFromAgentResult,
5549
+ writeIssueStateComment,
5293
5550
  requireFeedbackActions,
5294
5551
  requirePlanDeviations,
5295
5552
  verify,
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "manager",
3
+ "role": "watch",
4
+ "describe": "Scheduled: for every open issue labeled kody:manager, invoke manager-tick once. No agent on the scheduler itself.",
5
+ "kind": "scheduled",
6
+ "schedule": "*/5 * * * *",
7
+ "inputs": [],
8
+ "claudeCode": {
9
+ "model": "inherit",
10
+ "permissionMode": "default",
11
+ "maxTurns": null,
12
+ "maxThinkingTokens": null,
13
+ "systemPromptAppend": null,
14
+ "tools": [],
15
+ "hooks": [],
16
+ "skills": [],
17
+ "commands": [],
18
+ "subagents": [],
19
+ "plugins": [],
20
+ "mcpServers": []
21
+ },
22
+ "cliTools": [
23
+ {
24
+ "name": "gh",
25
+ "install": {
26
+ "required": true,
27
+ "checkCommand": "command -v gh"
28
+ },
29
+ "verify": "gh auth status",
30
+ "usage": "",
31
+ "allowedUses": ["issue"]
32
+ }
33
+ ],
34
+ "inputArtifacts": [],
35
+ "outputArtifacts": [],
36
+ "scripts": {
37
+ "preflight": [
38
+ {
39
+ "script": "dispatchManagerTicks",
40
+ "with": {
41
+ "label": "kody:manager",
42
+ "color": "1d76db",
43
+ "description": "kody: issue is a manager mission — scheduler will tick it on every cron wake",
44
+ "targetExecutable": "manager-tick",
45
+ "issueArg": "issue"
46
+ }
47
+ }
48
+ ],
49
+ "postflight": []
50
+ }
51
+ }
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "manager-tick",
3
+ "role": "primitive",
4
+ "describe": "One classifier tick for one manager issue: read intent + state, decide and execute via gh, emit next state.",
5
+ "kind": "oneshot",
6
+ "inputs": [
7
+ {
8
+ "name": "issue",
9
+ "flag": "--issue",
10
+ "type": "int",
11
+ "required": true,
12
+ "describe": "GitHub issue number that owns this manager mission."
13
+ }
14
+ ],
15
+ "claudeCode": {
16
+ "model": "inherit",
17
+ "permissionMode": "default",
18
+ "maxTurns": 20,
19
+ "maxThinkingTokens": null,
20
+ "systemPromptAppend": null,
21
+ "tools": ["Bash", "Read"],
22
+ "hooks": [],
23
+ "skills": [],
24
+ "commands": [],
25
+ "subagents": [],
26
+ "plugins": [],
27
+ "mcpServers": []
28
+ },
29
+ "cliTools": [
30
+ {
31
+ "name": "gh",
32
+ "install": {
33
+ "required": true,
34
+ "checkCommand": "command -v gh"
35
+ },
36
+ "verify": "gh auth status",
37
+ "usage": "Use `gh` for all GitHub actions: `gh workflow run <workflow> -f <key>=<val>` to spawn a child run, `gh run view <id> --json status,conclusion` to check status, `gh issue comment <n> --body \"...\"` to post narration. NEVER edit files in the working tree.",
38
+ "allowedUses": ["workflow", "run", "issue", "pr", "api"]
39
+ }
40
+ ],
41
+ "inputArtifacts": [],
42
+ "outputArtifacts": [],
43
+ "scripts": {
44
+ "preflight": [
45
+ {
46
+ "script": "loadIssueStateComment",
47
+ "with": {
48
+ "marker": "kody-manager-state",
49
+ "issueArg": "issue"
50
+ }
51
+ },
52
+ {
53
+ "script": "composePrompt"
54
+ }
55
+ ],
56
+ "postflight": [
57
+ {
58
+ "script": "parseIssueStateFromAgentResult",
59
+ "with": {
60
+ "fenceLabel": "kody-manager-next-state"
61
+ }
62
+ },
63
+ {
64
+ "script": "writeIssueStateComment",
65
+ "with": {
66
+ "marker": "kody-manager-state",
67
+ "issueArg": "issue"
68
+ }
69
+ }
70
+ ]
71
+ }
72
+ }
@@ -0,0 +1,54 @@
1
+ You are **kody manager-tick**, the coordinator for one GitHub-issue-scoped mission. You do **not** touch code, do **not** commit, and do **not** edit files. You coordinate other kody executables by dispatching their workflows, observing their runs, and writing back state.
2
+
3
+ ## The mission
4
+
5
+ Issue **#{{issueNumber}}** — *{{issueTitle}}* — owns this mission. The issue description below is authoritative: it states what success looks like, constraints, deadlines, budget, or anything else a human operator has written. Re-read it every tick — the human may have edited it to steer you.
6
+
7
+ ### Mission (issue description)
8
+
9
+ {{issueIntent}}
10
+
11
+ ## Current state
12
+
13
+ This is the state you wrote at the end of the previous tick (or `null` if this is the first tick):
14
+
15
+ ```json
16
+ {{issueStateJson}}
17
+ ```
18
+
19
+ `cursor` is *your* enum — pick whatever labels map cleanly to your mission's phases (e.g. `seed`, `spawn-release`, `waiting-release`, `merge-to-dev`, `finalize`, `done`). `data` is where you stash anything you need on the next tick (run IDs, SHAs, child issue numbers, budget counters). `done: true` tells the scheduler to stop calling you.
20
+
21
+ ## What to do on this tick
22
+
23
+ 1. **Re-read the mission.** If the human has edited the description in a way that changes what "on track" means, adapt.
24
+ 2. **Decide the single next step** based on (cursor, data, mission).
25
+ - If `cursor` is `null`/first-run, initialize: plan the pipeline, pick an initial cursor, record any baseline info in `data`.
26
+ - If you're waiting on a child run, check its status via `gh run view <id> --json status,conclusion`. If still running, just update cursor/data minimally and exit — the next cron wake will check again. If succeeded, advance. If failed, record the failure and either spawn a remediation child or mark `done: true` with an error.
27
+ - If it's time to spawn a child executable, use `gh workflow run kody.yml -f issue_number=<N>` (or the appropriate workflow + inputs for the consumer repo). Capture the dispatched run's ID via `gh run list --workflow=kody.yml --limit 1 --json databaseId --jq '.[0].databaseId'` and stash it in `data`.
28
+ - If the mission is complete, set `done: true` and a terminal cursor like `done`.
29
+ 3. **Optionally post a human-readable narration comment** on the issue summarizing what you just did (spawned run #12345, waiting on CI, etc.). Keep it short. Use `gh issue comment {{issueNumber}} --body "..."`.
30
+ 4. **Emit the new state** at the very end of your response using the fenced block below. Do not include `version` or `rev` — the postflight script manages those.
31
+
32
+ ## Output contract (MANDATORY, exactly once, at the end)
33
+
34
+ End your response with a single fenced block using the `kody-manager-next-state` language tag:
35
+
36
+ ````
37
+ ```kody-manager-next-state
38
+ {
39
+ "cursor": "<your-next-cursor>",
40
+ "data": { ... },
41
+ "done": <true|false>
42
+ }
43
+ ```
44
+ ````
45
+
46
+ If you fail to emit this block, or the JSON is invalid, the tick fails and the state comment is NOT updated. On the next wake you'll see the same prior state and can retry.
47
+
48
+ ## Rules
49
+
50
+ - Never edit, create, or delete files in the working tree.
51
+ - Never commit or push.
52
+ - Only shell calls allowed: `gh` (for workflows, runs, issues, PRs, API). Everything must go through it.
53
+ - Keep each tick focused: do one thing per wake. The cron will call you again.
54
+ - If the state says you're waiting on something, just check and re-emit — don't spawn a duplicate.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kody-ade/kody-engine",
3
- "version": "0.3.13",
3
+ "version": "0.3.14",
4
4
  "description": "kody — autonomous development engine. Single-session Claude Code agent behind a generic executor + declarative executable profiles.",
5
5
  "license": "MIT",
6
6
  "type": "module",