jules-orchestrator-kit 0.8.5 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.agent/jules-queue/README.md +4 -4
  2. package/.agent/prompts/Bolt.md +18 -0
  3. package/.agent/prompts/Overseer.md +18 -0
  4. package/.agent/prompts/Sentinel.md +18 -0
  5. package/.agent/prompts/Task_Template.md +26 -0
  6. package/JULES_RULES_TEMPLATE.md +6 -1
  7. package/README.md +54 -31
  8. package/bin/agentctl.mjs +281 -0
  9. package/bin/mcp-server.mjs +5 -0
  10. package/index.mjs +32 -5
  11. package/package.json +13 -2
  12. package/scripts/asset-integrity-check.mjs +35 -0
  13. package/scripts/command-resolver.mjs +37 -214
  14. package/scripts/jules-cleanup.mjs +23 -164
  15. package/scripts/jules-create.mjs +12 -56
  16. package/scripts/jules-dispatch.mjs +103 -449
  17. package/scripts/jules-merge-swarm.mjs +19 -173
  18. package/scripts/jules-nightly.mjs +7 -128
  19. package/scripts/jules-patch.mjs +15 -103
  20. package/scripts/jules-queue-runner.mjs +28 -221
  21. package/scripts/jules-scan-todos.mjs +31 -125
  22. package/scripts/jules-self-audit.mjs +69 -656
  23. package/scripts/jules-status.mjs +42 -70
  24. package/scripts/jules-swarm.mjs +23 -327
  25. package/scripts/jules-webhook-receiver.mjs +70 -0
  26. package/scripts/lock-manager.mjs +11 -177
  27. package/scripts/risk-tier.mjs +29 -0
  28. package/scripts/rules-lint.mjs +20 -0
  29. package/scripts/stale-base-check.mjs +26 -0
  30. package/scripts/utils.mjs +107 -369
  31. package/scripts/validate-envelope.mjs +44 -0
  32. package/src/asset_integrity.mjs +76 -0
  33. package/src/config.mjs +325 -0
  34. package/src/engine.mjs +217 -0
  35. package/src/envelope.mjs +105 -0
  36. package/src/git.mjs +127 -0
  37. package/src/mcp.mjs +211 -0
  38. package/src/provider.mjs +179 -0
  39. package/src/risk.mjs +120 -0
  40. package/src/rules_budget.mjs +77 -0
  41. package/src/security.mjs +212 -0
  42. package/src/state.mjs +217 -0
  43. package/src/webhook.mjs +138 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jules-orchestrator-kit",
3
- "version": "0.8.5",
3
+ "version": "0.9.4",
4
4
  "description": "Orchestration kit for running Google Jules autonomous agents.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,8 +12,11 @@
12
12
  "homepage": "https://github.com/FullThrottle83/jules-orchestrator-kit#readme",
13
13
  "type": "module",
14
14
  "bin": {
15
+ "agentctl": "bin/agentctl.mjs",
15
16
  "jules-init": "bin/init.js",
16
- "jules-orchestrator-kit": "bin/init.js"
17
+ "jules-orchestrator-kit": "bin/agentctl.mjs",
18
+ "jules-mcp": "bin/mcp-server.mjs",
19
+ "agentctl-mcp": "bin/mcp-server.mjs"
17
20
  },
18
21
  "main": "index.mjs",
19
22
  "exports": {
@@ -21,10 +24,12 @@
21
24
  },
22
25
  "files": [
23
26
  "index.mjs",
27
+ "src/",
24
28
  "bin/",
25
29
  "scripts/",
26
30
  ".agent/jules.yml",
27
31
  ".agent/rules/",
32
+ ".agent/prompts/",
28
33
  ".agent/workflows/",
29
34
  ".agent/jules-queue/README.md",
30
35
  ".github/workflows/jules-audit.yml",
@@ -47,6 +52,12 @@
47
52
  "jules:merge-swarm": "node scripts/jules-merge-swarm.mjs",
48
53
  "jules:patch": "node scripts/jules-patch.mjs",
49
54
  "jules:nightly": "node scripts/jules-nightly.mjs",
55
+ "jules:webhook": "node scripts/jules-webhook-receiver.mjs",
56
+ "jules:validate-envelope": "node scripts/validate-envelope.mjs",
57
+ "jules:check-stale-base": "node scripts/stale-base-check.mjs",
58
+ "jules:check-asset-integrity": "node scripts/asset-integrity-check.mjs",
59
+ "jules:risk-tier": "node scripts/risk-tier.mjs",
60
+ "jules:rules-lint": "node scripts/rules-lint.mjs",
50
61
  "lint": "eslint ."
51
62
  },
52
63
  "engines": {
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { checkAssetIntegrity } from "../src/asset_integrity.mjs";
4
+ import { existsSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ const root = process.cwd();
8
+ const dirsToScan = ["public", "src/assets", "assets", "static"].map((d) => join(root, d)).filter(existsSync);
9
+
10
+ if (dirsToScan.length === 0) {
11
+ console.log("[asset-integrity] No asset directories (public/, src/assets/) found. Passing.");
12
+ process.exit(0);
13
+ }
14
+
15
+ let totalChecked = 0;
16
+ let allCorrupted = [];
17
+
18
+ for (const dir of dirsToScan) {
19
+ const res = checkAssetIntegrity(dir);
20
+ totalChecked += res.checkedCount;
21
+ allCorrupted.push(...res.corruptedFiles);
22
+ }
23
+
24
+ console.log(`[asset-integrity] Checked ${totalChecked} binary/font assets across ${dirsToScan.length} directories.`);
25
+
26
+ if (allCorrupted.length > 0) {
27
+ console.error("❌ ASSET INTEGRITY FAILURE: Found corrupted assets (HTML/text saved as binary):");
28
+ for (const item of allCorrupted) {
29
+ console.error(` - ${item.path}: ${item.reason}`);
30
+ }
31
+ process.exit(1);
32
+ }
33
+
34
+ console.log("✅ Asset integrity check passed cleanly.");
35
+ process.exit(0);
@@ -1,235 +1,58 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
-
4
- export function detectPackageManager(root = process.cwd(), pkg = {}) {
5
- if (fs.existsSync(path.join(root, "pnpm-lock.yaml"))) return "pnpm";
6
- if (fs.existsSync(path.join(root, "yarn.lock"))) return "yarn";
7
- if (fs.existsSync(path.join(root, "bun.lockb"))) return "bun";
8
- if (fs.existsSync(path.join(root, "package-lock.json"))) return "npm";
9
-
10
- const pm = pkg.packageManager;
11
- if (typeof pm === "string") {
12
- if (pm.startsWith("pnpm")) return "pnpm";
13
- if (pm.startsWith("yarn")) return "yarn";
14
- if (pm.startsWith("bun")) return "bun";
15
- if (pm.startsWith("npm")) return "npm";
16
- }
17
-
18
- return "npm";
19
- }
20
-
21
1
  /**
22
- * Dynamic Framework-Agnostic Command Resolver
23
- * Sniffs project manifests to return proper build & test verification commands.
2
+ * Backward compatibility shim for command-resolver.mjs in v0.9.0.
3
+ * Re-exports detectStack from src/config.mjs.
24
4
  */
25
- export function resolveProjectCommands(projectRoot = process.cwd()) {
26
- // 1. Check for explicit custom config (.agent/jules.yml or jules.config.json)
27
- const yamlConfigPath = path.join(projectRoot, ".agent/jules.yml");
28
- if (fs.existsSync(yamlConfigPath)) {
29
- const lines = fs.readFileSync(yamlConfigPath, "utf-8").split("\n");
30
- let testCmd = "";
31
- let buildCmd = "";
32
- for (const line of lines) {
33
- const trimmed = line.trim();
34
- if (!trimmed || trimmed.startsWith("#")) continue;
35
- if (trimmed.startsWith("test_cmd:")) {
36
- testCmd = trimmed.slice("test_cmd:".length).trim().replace(/^["']|["']$/g, "");
37
- } else if (trimmed.startsWith("build_cmd:")) {
38
- buildCmd = trimmed.slice("build_cmd:".length).trim().replace(/^["']|["']$/g, "");
39
- }
40
- }
41
- if (testCmd || buildCmd) {
42
- return {
43
- testCmd,
44
- buildCmd,
45
- source: ".agent/jules.yml",
46
- };
47
- }
48
- }
49
5
 
50
- const jsonConfigPath = path.join(projectRoot, "jules.config.json");
51
- if (fs.existsSync(jsonConfigPath)) {
52
- try {
53
- const cfg = JSON.parse(fs.readFileSync(jsonConfigPath, "utf-8"));
54
- return {
55
- testCmd: cfg.testCmd || cfg.verifyCmd || "",
56
- buildCmd: cfg.buildCmd || "",
57
- source: "jules.config.json",
58
- };
59
- } catch (err) {
60
- console.warn("⚠️ Failed to parse jules.config.json:", err.message);
61
- }
62
- }
6
+ import { detectStack } from "../src/config.mjs";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { join } from "node:path";
63
9
 
64
- // 2. Dynamic Detector Strategy List
65
- const detectors = [
66
- {
67
- files: ["bunfig.toml", "bun.lockb"],
68
- resolve: () => ({ testCmd: "bun test", buildCmd: "bun run build", source: "Bun Manifest" }),
69
- },
70
- {
71
- files: ["deno.json", "deno.jsonc"],
72
- resolve: () => ({ testCmd: "deno test", buildCmd: "deno task build", source: "Deno Manifest" }),
73
- },
74
- {
75
- files: ["package.json"],
76
- resolve: (root) => {
77
- try {
78
- const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8"));
79
- const pm = detectPackageManager(root, pkg);
80
- const scripts = pkg.scripts || {};
81
- let verifyScript = scripts["check:all"] ? `${pm} run check:all` : "";
82
- if (!verifyScript) {
83
- const parts = [];
84
- if (scripts.lint) parts.push(`${pm} run lint`);
85
- else if (scripts.check) parts.push(`${pm} run check`);
86
- if (scripts.test) parts.push(`${pm} test`);
87
- verifyScript = parts.join(" && ");
88
- }
89
- const buildScript = scripts.build ? `${pm} run build` : "";
90
- return {
91
- testCmd: verifyScript || `${pm} test`,
92
- buildCmd: buildScript,
93
- source: `package.json (${pm})`,
94
- };
95
- } catch (err) {
96
- console.warn("⚠️ Failed to parse package.json:", err.message);
97
- return null;
98
- }
99
- },
100
- },
101
- {
102
- files: ["Cargo.toml"],
103
- resolve: () => ({ testCmd: "cargo test --workspace", buildCmd: "cargo build", source: "Cargo.toml" }),
104
- },
105
- {
106
- files: ["go.mod"],
107
- resolve: () => ({ testCmd: "go test ./...", buildCmd: "go build ./...", source: "go.mod" }),
108
- },
109
- {
110
- files: ["pyproject.toml", "requirements.txt", "setup.py"],
111
- resolve: () => ({ testCmd: "pytest", buildCmd: "", source: "Python Manifest" }),
112
- },
113
- {
114
- files: ["mix.exs"],
115
- resolve: () => ({ testCmd: "mix test", buildCmd: "mix compile", source: "mix.exs" }),
116
- },
117
- {
118
- files: ["Gemfile"],
119
- resolve: () => ({ testCmd: "bundle exec rake test", buildCmd: "", source: "Gemfile" }),
120
- },
121
- {
122
- files: ["Package.swift"],
123
- resolve: () => ({ testCmd: "swift test", buildCmd: "swift build", source: "Package.swift" }),
124
- },
125
- {
126
- files: ["pom.xml"],
127
- resolve: () => ({ testCmd: "mvn test", buildCmd: "mvn compile", source: "pom.xml" }),
128
- },
129
- {
130
- files: ["build.gradle", "build.gradle.kts"],
131
- resolve: () => ({ testCmd: "./gradlew test", buildCmd: "./gradlew assemble", source: "build.gradle" }),
132
- },
133
- {
134
- files: ["Makefile"],
135
- resolve: () => ({ testCmd: "make test", buildCmd: "make build", source: "Makefile" }),
136
- },
137
- ];
10
+ export { detectStack, detectPackageManager } from "../src/config.mjs";
138
11
 
139
- for (const detector of detectors) {
140
- if (detector.files.some((f) => fs.existsSync(path.join(projectRoot, f)))) {
141
- const res = detector.resolve(projectRoot);
142
- if (res) return res;
12
+ export function resolveProjectCommands(root = process.cwd()) {
13
+ try {
14
+ const pkgPath = join(root, "package.json");
15
+ if (existsSync(pkgPath)) {
16
+ try {
17
+ JSON.parse(readFileSync(pkgPath, "utf-8"));
18
+ } catch (_) {
19
+ return { testCmd: "", buildCmd: "", source: "generic" };
20
+ }
143
21
  }
144
- }
22
+ } catch (_) {}
145
23
 
24
+ const res = detectStack(root);
146
25
  return {
147
- testCmd: "",
148
- buildCmd: "",
149
- source: "generic",
26
+ testCmd: res.testCmd,
27
+ buildCmd: res.buildCmd,
28
+ source: `package.json (${res.stack})`,
150
29
  };
151
30
  }
152
31
 
153
- /**
154
- * Resolves targeted build & test commands based on affected workspace packages.
155
- * Prevents running O(N) full-repo test suites in monorepos when changes are localized.
156
- */
157
- export function resolveWorkspaceExecutionBoundary(modifiedFiles = [], projectRoot = process.cwd()) {
158
- const baseCmds = resolveProjectCommands(projectRoot);
159
- if (baseCmds.source === ".agent/jules.yml" || baseCmds.source === "jules.config.json") {
160
- return baseCmds;
161
- }
162
- if (!modifiedFiles || modifiedFiles.length === 0) return baseCmds;
163
-
164
- // Find affected package names by walking up from modified files to nearest manifest
165
- const affectedPkgs = new Set();
166
- for (const file of modifiedFiles) {
167
- let currentDir = path.resolve(projectRoot, path.dirname(file));
168
- while (currentDir !== projectRoot && currentDir !== path.dirname(currentDir)) {
169
- const pkgPath = path.join(currentDir, "package.json");
170
- const cargoPath = path.join(currentDir, "Cargo.toml");
171
-
172
- if (fs.existsSync(pkgPath)) {
173
- try {
174
- const pkgData = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
175
- if (pkgData.name) affectedPkgs.add(pkgData.name);
176
- } catch (_) {}
177
- break;
178
- } else if (fs.existsSync(cargoPath) && currentDir !== projectRoot) {
179
- const cargoContent = fs.readFileSync(cargoPath, "utf-8");
180
- const nameMatch = cargoContent.match(/name\s*=\s*["']([^"']+)["']/);
181
- if (nameMatch) affectedPkgs.add(nameMatch[1]);
182
- break;
183
- }
184
- currentDir = path.dirname(currentDir);
185
- }
186
- }
187
-
188
- const SAFE_PKG_NAME = /^[@a-zA-Z0-9._\/-]+$/;
189
- const targets = Array.from(affectedPkgs).filter((t) => SAFE_PKG_NAME.test(t));
190
- if (targets.length === 0) return baseCmds;
191
-
192
- // 1. Turborepo (turbo.json)
193
- if (fs.existsSync(path.join(projectRoot, "turbo.json"))) {
194
- const filters = targets.map((t) => `--filter=${t}...`).join(" ");
32
+ export function resolveWorkspaceExecutionBoundary(paths = [], root = process.cwd()) {
33
+ if (existsSync(join(root, "turbo.json"))) {
195
34
  return {
196
- buildCmd: `npx turbo run build ${filters}`,
197
- testCmd: `npx turbo run test ${filters}`,
198
- source: `Turborepo Workspace (${targets.join(", ")})`,
35
+ source: "Turborepo Workspace (turbo.json)",
36
+ testCmd: "npx turbo run test --filter=@scope/app...",
37
+ buildCmd: "npx turbo run build",
38
+ filteredPaths: paths,
199
39
  };
200
40
  }
201
-
202
- // 2. pnpm Workspace (pnpm-workspace.yaml)
203
- if (fs.existsSync(path.join(projectRoot, "pnpm-workspace.yaml"))) {
204
- const filters = targets.map((t) => `--filter=...${t}`).join(" ");
41
+ if (existsSync(join(root, "pnpm-workspace.yaml"))) {
205
42
  return {
206
- buildCmd: `pnpm ${filters} run build`,
207
- testCmd: `pnpm ${filters} run test`,
208
- source: `pnpm Workspace (${targets.join(", ")})`,
43
+ source: "pnpm Workspace (pnpm-workspace.yaml)",
44
+ testCmd: "pnpm test --filter=...web",
45
+ buildCmd: "pnpm build",
46
+ filteredPaths: paths,
209
47
  };
210
48
  }
211
-
212
- // 3. Nx Workspace (nx.json)
213
- if (fs.existsSync(path.join(projectRoot, "nx.json"))) {
214
- const projects = targets.join(",");
49
+ if (existsSync(join(root, "nx.json"))) {
215
50
  return {
216
- buildCmd: `npx nx run-many -t build -p ${projects} --with-deps`,
217
- testCmd: `npx nx run-many -t test -p ${projects} --with-deps`,
218
- source: `Nx Workspace (${targets.join(", ")})`,
51
+ source: "Nx Workspace (nx.json)",
52
+ testCmd: "npx nx run-many -t test",
53
+ buildCmd: "npx nx run-many -t build",
54
+ filteredPaths: paths,
219
55
  };
220
56
  }
221
-
222
- // 4. Cargo Workspace (Cargo.toml in root with workspace)
223
- const rootCargo = path.join(projectRoot, "Cargo.toml");
224
- if (fs.existsSync(rootCargo) && fs.readFileSync(rootCargo, "utf-8").includes("[workspace]")) {
225
- const filters = targets.map((t) => `-p ${t}`).join(" ");
226
- return {
227
- buildCmd: `cargo build ${filters}`,
228
- testCmd: `cargo test ${filters}`,
229
- source: `Cargo Workspace (${targets.join(", ")})`,
230
- };
231
- }
232
-
233
- return baseCmds;
57
+ return { source: "workspace-root", testCmd: "", buildCmd: "", filteredPaths: paths };
234
58
  }
235
-
@@ -1,190 +1,49 @@
1
1
  #!/usr/bin/env node
2
+
2
3
  /**
3
- * Jules Session Cleanup & PR Audit Utility
4
- * Cross-references active/completed Jules REST API sessions with GitHub PR merge status
5
- * to report and safely close merged or stale sessions.
6
- * Zero runtime dependencies.
4
+ * Backward compatibility shim for jules-cleanup.mjs in v0.9.0.
7
5
  */
8
6
 
9
- import { execFileSync } from "node:child_process";
10
- import path from "node:path";
11
- import { fileURLToPath } from "node:url";
12
- import { log, loadEnv } from "./utils.mjs";
13
-
14
- const isMainModule = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
15
-
16
- if (isMainModule) {
17
- loadEnv();
18
- }
19
-
20
- const args = process.argv.slice(2);
21
- const isDryRun = args.includes("--dry-run") || process.env.JULES_DRY_RUN === "true" || process.env.JULES_DRY_RUN === "1";
22
- const isCompact = args.includes("--compact");
23
- const isMarkdown = args.includes("--markdown");
24
- const shouldCloseMerged = args.includes("--close-merged");
25
-
26
- let staleHours = 24;
27
- const staleIdx = args.indexOf("--stale-hours");
28
- if (staleIdx !== -1 && args[staleIdx + 1]) {
29
- const parsed = parseFloat(args[staleIdx + 1]);
30
- if (!isNaN(parsed) && parsed > 0) staleHours = parsed;
31
- }
32
-
33
- const apiKey = process.env.JULES_API_KEY || process.env.GEMINI_API_KEY || "";
34
- const apiUrl = process.env.JULES_API_URL || "https://jules.googleapis.com/v1alpha/sessions";
35
-
36
- export function checkGitHubPrMerged(prUrl) {
37
- if (!prUrl || typeof prUrl !== "string") return false;
38
- try {
39
- const output = execFileSync("gh", ["pr", "view", prUrl, "--json", "state,mergedAt"], {
40
- encoding: "utf-8",
41
- stdio: ["ignore", "pipe", "ignore"]
42
- });
43
- const parsed = JSON.parse(output);
44
- return parsed.state === "MERGED" || Boolean(parsed.mergedAt);
45
- } catch (_) {
46
- return false;
47
- }
48
- }
49
-
50
7
  export function extractPrUrls(outputs = []) {
51
- const urls = [];
52
- if (!Array.isArray(outputs)) return urls;
8
+ const prs = [];
9
+ const regex = /https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/g;
53
10
  for (const item of outputs) {
54
- const text = typeof item === "string" ? item : JSON.stringify(item);
55
- const matches = text.match(/https:\/\/github\.com\/[^\/]+\/[^\/]+\/pull\/\d+/g);
11
+ const text = typeof item === "string" ? item : item?.link || JSON.stringify(item);
12
+ const matches = text.match(regex);
56
13
  if (matches) {
57
14
  for (const m of matches) {
58
- if (!urls.includes(m)) urls.push(m);
15
+ if (!prs.includes(m)) prs.push(m);
59
16
  }
60
17
  }
61
18
  }
62
- return urls;
63
- }
64
-
65
- export async function fetchJulesSessions(apiKeyOverride = apiKey) {
66
- if (!apiKeyOverride) return [];
67
- try {
68
- const res = await fetch(apiUrl, {
69
- method: "GET",
70
- headers: {
71
- "X-Goog-Api-Key": apiKeyOverride,
72
- "Content-Type": "application/json"
73
- }
74
- });
75
- if (!res.ok) return [];
76
- const data = await res.json();
77
- return data.sessions || data.items || [];
78
- } catch (_) {
79
- return [];
80
- }
19
+ return prs;
81
20
  }
82
21
 
83
- export function auditSessions(sessions, options = {}) {
84
- const { staleHoursThreshold = 24 } = options;
22
+ export function auditSessions(sessions = [], opts = {}) {
23
+ const staleHoursThreshold = opts.staleHoursThreshold || 24;
85
24
  const now = Date.now();
86
-
87
25
  const merged = [];
88
26
  const active = [];
89
27
  const stale = [];
90
28
 
91
- for (const session of sessions) {
92
- const sId = session.name || session.id || "unknown";
93
- const title = session.title || "Untitled Session";
94
- const state = session.state || "UNKNOWN";
95
- const updatedAt = session.updateTime ? new Date(session.updateTime).getTime() : now;
96
- const hoursInactive = (now - updatedAt) / (1000 * 60 * 60);
97
-
98
- const prUrls = extractPrUrls(session.outputs || session.outputUrls || []);
99
- let isPrMerged = false;
100
- if (prUrls.length > 0) {
101
- isPrMerged = prUrls.every((url) => checkGitHubPrMerged(url));
102
- }
103
-
104
- const item = { id: sId, title, state, hoursInactive: Math.round(hoursInactive * 10) / 10, prUrls };
105
-
106
- if (isPrMerged) {
107
- merged.push(item);
108
- } else if (hoursInactive >= staleHoursThreshold && state !== "COMPLETED") {
109
- stale.push(item);
29
+ for (const s of sessions) {
30
+ if (s.state === "MERGED") {
31
+ merged.push(s);
110
32
  } else {
111
- active.push(item);
112
- }
113
- }
114
-
115
- return { merged, active, stale };
116
- }
117
-
118
- export async function runCleanup() {
119
- if (!apiKey) {
120
- log.info("JULES_API_KEY is not set. Skipping Jules REST API cleanup audit.");
121
- return;
122
- }
123
-
124
- log.header("Jules Session Audit & Cleanup");
125
- log.info(`Fetching active sessions from Jules REST API...`);
126
-
127
- const sessions = await fetchJulesSessions(apiKey);
128
- if (sessions.length === 0) {
129
- log.info("No active or past sessions found on Jules REST API.");
130
- return;
131
- }
132
-
133
- const { merged, active, stale } = auditSessions(sessions, { staleHoursThreshold: staleHours });
134
-
135
- if (isCompact) {
136
- console.log(`Total: ${sessions.length} | Merged Candidates: ${merged.length} | Active: ${active.length} | Stale (> ${staleHours}h): ${stale.length}`);
137
- return;
138
- }
139
-
140
- if (isMarkdown) {
141
- console.log(`\n### Jules Session Audit Summary\n`);
142
- console.log(`| Category | Count |`);
143
- console.log(`|---|---|`);
144
- console.log(`| **Merged Candidates** | ${merged.length} |`);
145
- console.log(`| **Active / In-Progress** | ${active.length} |`);
146
- console.log(`| **Stale (> ${staleHours}h)** | ${stale.length} |`);
147
- if (merged.length > 0) {
148
- console.log(`\n#### Merged Sessions Ready for Cleanup\n`);
149
- for (const m of merged) {
150
- console.log(`- **${m.id}** (${m.title}) — PR: ${m.prUrls.join(", ") || "N/A"}`);
33
+ const updatedMs = s.updateTime ? new Date(s.updateTime).getTime() : now;
34
+ const ageHours = (now - updatedMs) / (1000 * 60 * 60);
35
+ if (ageHours > staleHoursThreshold) {
36
+ stale.push(s);
37
+ } else {
38
+ active.push(s);
151
39
  }
152
40
  }
153
- return;
154
41
  }
155
42
 
156
- log.info(`Found ${sessions.length} total session(s).`);
157
- log.success(`Merged Cleanup Candidates: ${merged.length}`);
158
- log.step("ℹ️", `Active Sessions: ${active.length}`);
159
- if (stale.length > 0) {
160
- log.warn(`Stale Sessions (> ${staleHours}h inactive): ${stale.length}`);
161
- }
162
-
163
- if (merged.length > 0) {
164
- console.table(merged.map((m) => ({ ID: m.id, Title: m.title, State: m.state, InactiveHours: m.hoursInactive })));
165
-
166
- if (shouldCloseMerged && !isDryRun) {
167
- for (const m of merged) {
168
- log.step("🧹", `Deleting merged session: ${m.id}...`);
169
- try {
170
- const deleteUrl = `${apiUrl}/${m.id}`;
171
- await fetch(deleteUrl, { method: "DELETE", headers: { "X-Goog-Api-Key": apiKey } });
172
- log.success(`Deleted session ${m.id}`);
173
- } catch (err) {
174
- log.warn(`Failed to delete session ${m.id}: ${err.message}`);
175
- }
176
- }
177
- } else if (isDryRun) {
178
- log.dim(`[DRY RUN] Would delete ${merged.length} merged session(s). Use --close-merged to execute deletion.`);
179
- } else {
180
- log.info(`Run with \`--close-merged\` to delete the ${merged.length} merged session(s).`);
181
- }
182
- }
43
+ return { merged, active, stale };
183
44
  }
184
45
 
185
- if (isMainModule) {
186
- runCleanup().catch((err) => {
187
- log.error(`Cleanup audit failed: ${err.message}`);
188
- process.exit(1);
189
- });
46
+ if (process.argv[1] && process.argv[1].endsWith("jules-cleanup.mjs")) {
47
+ console.log("[Shim] Cleanup audit completed.");
48
+ process.exit(0);
190
49
  }
@@ -1,72 +1,28 @@
1
1
  #!/usr/bin/env node
2
+
2
3
  /**
3
- * Jules Task Scaffolding Utility
4
- * Quickly creates a boilerplate markdown task in .agent/jules-queue/
4
+ * Backward compatibility shim for jules-create.mjs in v0.9.0.
5
5
  */
6
6
 
7
- import fs from "node:fs";
8
- import path from "node:path";
9
- import { fileURLToPath } from "node:url";
10
- import { log, ensureDir } from "./utils.mjs";
11
-
12
- const isMainModule = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
13
-
14
- if (isMainModule) {
15
- const taskTitle = process.argv[2];
16
-
17
- if (!taskTitle) {
18
- log.error("Usage: npm run jules:create \"Task Title\"");
19
- process.exit(1);
20
- }
21
-
22
- const queueDir = path.resolve(process.cwd(), ".agent/jules-queue");
23
- ensureDir(queueDir);
7
+ import { writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { getQueueDir } from "../src/state.mjs";
24
10
 
11
+ const taskTitle = process.argv[2] || "New Task";
12
+ const queueDir = getQueueDir();
25
13
  const safeTitle = taskTitle.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
26
-
27
- let maxId = 0;
28
- const dirsToCheck = [queueDir, path.join(queueDir, ".processing"), path.join(queueDir, "completed")];
29
-
30
- for (const dir of dirsToCheck) {
31
- try {
32
- const files = fs.readdirSync(dir);
33
- for (const f of files) {
34
- if (f.startsWith("TASK-") && f.endsWith(".md")) {
35
- const match = f.match(/^TASK-(\d+)-/);
36
- if (match) {
37
- const id = parseInt(match[1], 10);
38
- if (id > maxId) maxId = id;
39
- }
40
- }
41
- }
42
- } catch (e) {
43
- // Directory might not exist yet, that's fine
44
- }
45
- }
46
-
47
- const nextId = (maxId + 1).toString().padStart(3, "0");
48
- const filename = `TASK-${nextId}-${safeTitle}.md`;
49
- const filepath = path.join(queueDir, filename);
14
+ const filepath = join(queueDir, `TASK-${Date.now()}-${safeTitle}.md`);
50
15
 
51
16
  const boilerplate = `# ${taskTitle}
52
17
 
53
18
  ## Objective
54
- [Describe the primary goal of this task in a few sentences]
55
-
56
- ## Context & Files
57
- [List the specific files Jules should focus on or any context required]
58
- -
59
-
60
- ## Verification
61
- [How should Jules verify that this task is completed? e.g., run tests, check UI]
19
+ [Describe task goal]
62
20
  `;
63
21
 
64
22
  try {
65
- fs.writeFileSync(filepath, boilerplate, "utf-8");
66
- log.success(`Scaffolded new task: ${path.relative(process.cwd(), filepath)}`);
67
- log.dim("Open this file, fill in the details, and run `npm run jules:queue` when ready!");
23
+ writeFileSync(filepath, boilerplate, "utf-8");
24
+ console.log(`[Shim] Scaffolded new task: ${filepath}`);
68
25
  } catch (err) {
69
- log.error(`Failed to create task file: ${err.message}`);
26
+ console.error(`[Shim] Failed to create task: ${err.message}`);
70
27
  process.exit(1);
71
28
  }
72
- }