jioogen 0.2.4 → 0.2.6

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/index.js CHANGED
@@ -363,9 +363,9 @@ var require_utils = __commonJS({
363
363
  fpath.split(self.sep).forEach(function(name) {
364
364
  if (!name || name.substr(-1, 1) === ":") return;
365
365
  resolvedPath += self.sep + name;
366
- var stat3;
366
+ var stat5;
367
367
  try {
368
- stat3 = self.fs.statSync(resolvedPath);
368
+ stat5 = self.fs.statSync(resolvedPath);
369
369
  } catch (e) {
370
370
  if (e.message && e.message.startsWith("ENOENT")) {
371
371
  self.fs.mkdirSync(resolvedPath);
@@ -373,7 +373,7 @@ var require_utils = __commonJS({
373
373
  throw e;
374
374
  }
375
375
  }
376
- if (stat3 && stat3.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
376
+ if (stat5 && stat5.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
377
377
  });
378
378
  }
379
379
  mkdirSync(folder);
@@ -382,8 +382,8 @@ var require_utils = __commonJS({
382
382
  const self = this;
383
383
  if (self.fs.existsSync(path)) {
384
384
  if (!overwrite) return false;
385
- var stat3 = self.fs.statSync(path);
386
- if (stat3.isDirectory()) {
385
+ var stat5 = self.fs.statSync(path);
386
+ if (stat5.isDirectory()) {
387
387
  return false;
388
388
  }
389
389
  }
@@ -416,8 +416,8 @@ var require_utils = __commonJS({
416
416
  const self = this;
417
417
  self.fs.exists(path, function(exist) {
418
418
  if (exist && !overwrite) return callback(false);
419
- self.fs.stat(path, function(err, stat3) {
420
- if (exist && stat3 && stat3.isDirectory()) {
419
+ self.fs.stat(path, function(err, stat5) {
420
+ if (exist && stat5 && stat5.isDirectory()) {
421
421
  return callback(false);
422
422
  }
423
423
  var folder = pth.dirname(path);
@@ -469,13 +469,13 @@ var require_utils = __commonJS({
469
469
  for (const part of rel.split(pth.sep)) {
470
470
  if (!part || part === ".") continue;
471
471
  cur = pth.join(cur, part);
472
- let stat3;
472
+ let stat5;
473
473
  try {
474
- stat3 = self.fs.lstatSync(cur);
474
+ stat5 = self.fs.lstatSync(cur);
475
475
  } catch (e) {
476
476
  break;
477
477
  }
478
- if (stat3.isSymbolicLink()) throw Errors.FILE_IN_THE_WAY(`"${cur}"`);
478
+ if (stat5.isSymbolicLink()) throw Errors.FILE_IN_THE_WAY(`"${cur}"`);
479
479
  }
480
480
  };
481
481
  Utils.prototype.findFiles = function(path) {
@@ -502,11 +502,11 @@ var require_utils = __commonJS({
502
502
  self.fs.readdirSync(dir).forEach(function(file) {
503
503
  const path2 = pth.join(dir, file);
504
504
  if (escapesRoot(path2)) return;
505
- const stat3 = self.fs.statSync(path2);
505
+ const stat5 = self.fs.statSync(path2);
506
506
  if (!pattern || pattern.test(path2)) {
507
- files.push(pth.normalize(path2) + (stat3.isDirectory() ? self.sep : ""));
507
+ files.push(pth.normalize(path2) + (stat5.isDirectory() ? self.sep : ""));
508
508
  }
509
- if (stat3.isDirectory() && recursive) {
509
+ if (stat5.isDirectory() && recursive) {
510
510
  const realDir = self.fs.realpathSync(path2);
511
511
  if (!visited.has(realDir)) {
512
512
  visited.add(realDir);
@@ -553,14 +553,14 @@ var require_utils = __commonJS({
553
553
  if (!--pending) done();
554
554
  return;
555
555
  }
556
- self.fs.stat(file, function(err3, stat3) {
556
+ self.fs.stat(file, function(err3, stat5) {
557
557
  if (err3) return done(err3);
558
- if (!stat3) {
558
+ if (!stat5) {
559
559
  if (!--pending) done();
560
560
  return;
561
561
  }
562
- results.push(pth.normalize(file) + (stat3.isDirectory() ? self.sep : ""));
563
- if (!stat3.isDirectory()) {
562
+ results.push(pth.normalize(file) + (stat5.isDirectory() ? self.sep : ""));
563
+ if (!stat5.isDirectory()) {
564
564
  if (!--pending) done();
565
565
  return;
566
566
  }
@@ -2124,8 +2124,8 @@ var require_adm_zip = __commonJS({
2124
2124
  return null;
2125
2125
  }
2126
2126
  function fixPath(zipPath) {
2127
- const { join: join7, normalize, sep: sep2 } = pth.posix;
2128
- return join7(pth.isAbsolute(zipPath) ? "/" : ".", normalize(sep2 + zipPath.split("\\").join(sep2) + sep2));
2127
+ const { join: join9, normalize, sep: sep2 } = pth.posix;
2128
+ return join9(pth.isAbsolute(zipPath) ? "/" : ".", normalize(sep2 + zipPath.split("\\").join(sep2) + sep2));
2129
2129
  }
2130
2130
  function filenameFilter(filterfn) {
2131
2131
  if (filterfn instanceof RegExp) {
@@ -2521,10 +2521,10 @@ var require_adm_zip = __commonJS({
2521
2521
  * @param {function|string} [props.namefix] - optional function to help fix filename
2522
2522
  */
2523
2523
  addLocalFolderPromise: function(localPath, props) {
2524
- return new Promise((resolve5, reject) => {
2524
+ return new Promise((resolve6, reject) => {
2525
2525
  this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => {
2526
2526
  if (err) return reject(err);
2527
- if (done) resolve5(this);
2527
+ if (done) resolve6(this);
2528
2528
  });
2529
2529
  });
2530
2530
  },
@@ -2716,12 +2716,12 @@ var require_adm_zip = __commonJS({
2716
2716
  keepOriginalPermission = get_Bool(false, keepOriginalPermission);
2717
2717
  overwrite = get_Bool(false, overwrite);
2718
2718
  if (!callback) {
2719
- return new Promise((resolve5, reject) => {
2719
+ return new Promise((resolve6, reject) => {
2720
2720
  this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function(err) {
2721
2721
  if (err) {
2722
2722
  reject(err);
2723
2723
  } else {
2724
- resolve5(this);
2724
+ resolve6(this);
2725
2725
  }
2726
2726
  });
2727
2727
  });
@@ -2836,11 +2836,11 @@ var require_adm_zip = __commonJS({
2836
2836
  */
2837
2837
  writeZipPromise: function(targetFileName, props) {
2838
2838
  const { overwrite, perm } = Object.assign({ overwrite: true }, props);
2839
- return new Promise((resolve5, reject) => {
2839
+ return new Promise((resolve6, reject) => {
2840
2840
  if (!targetFileName && opts.filename) targetFileName = opts.filename;
2841
2841
  if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing");
2842
2842
  this.toBufferPromise().then((zipData) => {
2843
- const ret = (done) => done ? resolve5(done) : reject("ADM-ZIP: Wasn't able to write zip file");
2843
+ const ret = (done) => done ? resolve6(done) : reject("ADM-ZIP: Wasn't able to write zip file");
2844
2844
  filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);
2845
2845
  }, reject);
2846
2846
  });
@@ -2849,8 +2849,8 @@ var require_adm_zip = __commonJS({
2849
2849
  * @returns {Promise<Buffer>} A promise to the Buffer.
2850
2850
  */
2851
2851
  toBufferPromise: function() {
2852
- return new Promise((resolve5, reject) => {
2853
- _zip.toAsyncBuffer(resolve5, reject);
2852
+ return new Promise((resolve6, reject) => {
2853
+ _zip.toAsyncBuffer(resolve6, reject);
2854
2854
  });
2855
2855
  },
2856
2856
  /**
@@ -2978,8 +2978,8 @@ var ApiClient = class {
2978
2978
  };
2979
2979
 
2980
2980
  // src/commands.ts
2981
- import { readdir as readdir4, readFile as readFile6 } from "node:fs/promises";
2982
- import { join as join6, resolve as resolve4 } from "node:path";
2981
+ import { readdir as readdir5, readFile as readFile8 } from "node:fs/promises";
2982
+ import { join as join8, resolve as resolve5 } from "node:path";
2983
2983
 
2984
2984
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
2985
2985
  var external_exports = {};
@@ -3472,15 +3472,15 @@ var makeIssue = (params) => {
3472
3472
  message: issueData.message
3473
3473
  };
3474
3474
  }
3475
- let errorMessage = "";
3475
+ let errorMessage2 = "";
3476
3476
  const maps = errorMaps.filter((m) => !!m).slice().reverse();
3477
3477
  for (const map of maps) {
3478
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
3478
+ errorMessage2 = map(fullIssue, { data, defaultError: errorMessage2 }).message;
3479
3479
  }
3480
3480
  return {
3481
3481
  ...issueData,
3482
3482
  path: fullPath,
3483
- message: errorMessage
3483
+ message: errorMessage2
3484
3484
  };
3485
3485
  };
3486
3486
  var EMPTY_PATH = [];
@@ -8562,19 +8562,9 @@ function isMissingFile(error) {
8562
8562
  return isRecord(error) && error.code === "ENOENT";
8563
8563
  }
8564
8564
 
8565
- // src/errors.ts
8566
- var UsageError = class extends Error {
8567
- };
8568
-
8569
- // src/output.ts
8570
- function formatTable(headers, rows) {
8571
- const widths = headers.map(
8572
- (header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length))
8573
- );
8574
- const render = (cells) => cells.map((cell, index) => cell.padEnd(widths[index] ?? 0)).join(" ").trimEnd();
8575
- const divider = widths.map((width) => "-".repeat(width)).join(" ");
8576
- return [render(headers), divider, ...rows.map(render)].join("\n");
8577
- }
8565
+ // src/doctor.ts
8566
+ import { readdir as readdir3, readFile as readFile5, rm as rm4, stat as stat3 } from "node:fs/promises";
8567
+ import { join as join5 } from "node:path";
8578
8568
 
8579
8569
  // src/sidecar.ts
8580
8570
  import { randomUUID } from "node:crypto";
@@ -8762,7 +8752,7 @@ async function removeStaleLock(target) {
8762
8752
  }
8763
8753
  }
8764
8754
  function delay(ms) {
8765
- return new Promise((resolve5) => setTimeout(resolve5, ms));
8755
+ return new Promise((resolve6) => setTimeout(resolve6, ms));
8766
8756
  }
8767
8757
 
8768
8758
  // src/skills.ts
@@ -8837,8 +8827,11 @@ var JIOOGEN_AGENTS_MD = `${MARKER}
8837
8827
 
8838
8828
  ## 5. Checkpoint
8839
8829
  Berhenti dan minta konfirmasi user bila task berikutnya berpindah layer, nomor
8840
- \`phase\` naik, atau task bertanda \`checkpoint: true\`. Jangan lanjut sebelum user
8841
- mengetik "lanjut".
8830
+ \`phase\` naik, task bertanda \`checkpoint: true\`, atau task tergolong berisiko
8831
+ (migrasi/schema/auth/permission/payment/webhook/secret/deploy/infra). Jangan lanjut
8832
+ sebelum user memutuskan. Setelah user memutuskan, jalankan salah satu:
8833
+ \`npx jioogen review --approve\`, \`npx jioogen review --request-changes "<teks>"\`,
8834
+ atau \`npx jioogen review --stop\`, lalu \`npx jioogen sync\`.
8842
8835
 
8843
8836
  ## 6. Skill eksekusi
8844
8837
  Baca skill \`${EXECUTION_SKILL_NAME}\` di awal prompt
@@ -8916,10 +8909,13 @@ atas ide, refactor, perbaikan, atau fitur lain.
8916
8909
  Berhenti dan minta konfirmasi user bila:
8917
8910
  - task berikutnya berpindah \`layer\` (mis. \`frontend_mock\` \u2192 \`backend_api\`/\`database\`),
8918
8911
  - nomor \`phase\` naik,
8919
- - task bertanda \`checkpoint: true\`.
8912
+ - task bertanda \`checkpoint: true\`,
8913
+ - task tergolong berisiko (migrasi/schema/auth/permission/payment/webhook/secret/deploy/infra).
8920
8914
 
8921
- Jangan lanjut sebelum user mengetik "lanjut". Set \`current.awaitingCheckpoint = true\`
8922
- di sidecar saat berhenti.
8915
+ Jangan lanjut sebelum user memutuskan. Set \`current.awaitingCheckpoint = true\` di
8916
+ sidecar saat berhenti, lalu setelah user memutuskan jalankan
8917
+ \`npx jioogen review --approve\` / \`--request-changes "<teks>"\` / \`--stop\`,
8918
+ diikuti \`npx jioogen sync\`.
8923
8919
 
8924
8920
  ## 6. Larangan ringkas
8925
8921
 
@@ -9278,9 +9274,674 @@ function skillsDisabled(options) {
9278
9274
  return value === "1" || value === "true" || value === "yes";
9279
9275
  }
9280
9276
 
9277
+ // src/doctor.ts
9278
+ var REQUIRED_NODE_MAJOR = 22;
9279
+ var LOCK_STALE_MS2 = 1e4;
9280
+ var AGENTS_MARKER = "<!-- jioogen-execution-skill:";
9281
+ var BUNDLE_SCAFFOLD_CHECKS = /* @__PURE__ */ new Set(["agents", "execution-skill", "skill-packs"]);
9282
+ function makeCheck(id, status, detail, fixable) {
9283
+ return fixable === true ? { id, status, detail, fixable: true } : { id, status, detail };
9284
+ }
9285
+ function errorMessage(error) {
9286
+ return error instanceof Error ? error.message : String(error);
9287
+ }
9288
+ function isMissingFile4(error) {
9289
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
9290
+ }
9291
+ function resolveDeps(deps) {
9292
+ return {
9293
+ readCredentials: deps?.readCredentials ?? readCredentials,
9294
+ fetchMe: deps?.fetchMe ?? (async (apiUrl, cookie) => {
9295
+ const client = new ApiClient(apiUrl, cookie);
9296
+ return client.getJson(ENDPOINTS.me);
9297
+ }),
9298
+ fetchExecution: deps?.fetchExecution ?? (async (apiUrl, cookie, projectId) => {
9299
+ const client = new ApiClient(apiUrl, cookie);
9300
+ return client.getJson(projectPath(projectId, "/execution"));
9301
+ }),
9302
+ installSkills: deps?.installSkills ?? ((bundleDir) => installAgentSkills(bundleDir))
9303
+ };
9304
+ }
9305
+ function checkNode() {
9306
+ const raw = process.versions.node;
9307
+ const major = Number.parseInt(raw.split(".")[0] ?? "0", 10);
9308
+ if (Number.isFinite(major) && major >= REQUIRED_NODE_MAJOR) {
9309
+ return makeCheck("node", "pass", `Node.js v${raw} memenuhi syarat >=${REQUIRED_NODE_MAJOR}.`);
9310
+ }
9311
+ return makeCheck(
9312
+ "node",
9313
+ "fail",
9314
+ `Node.js v${raw} terlalu lama; butuh >=${REQUIRED_NODE_MAJOR}. Perbarui Node.js lalu ulangi.`
9315
+ );
9316
+ }
9317
+ function checkCredentials(credentials, error) {
9318
+ if (error !== null) {
9319
+ return makeCheck(
9320
+ "credentials",
9321
+ "fail",
9322
+ `Credential tidak bisa dibaca: ${error}. Periksa izin file credential.`
9323
+ );
9324
+ }
9325
+ if (credentials === null) {
9326
+ return makeCheck(
9327
+ "credentials",
9328
+ "fail",
9329
+ "Belum ada credential. Jalankan `jioogen login --email ... --password-stdin`."
9330
+ );
9331
+ }
9332
+ return makeCheck("credentials", "pass", `Credential tersimpan untuk ${credentials.apiUrl}.`);
9333
+ }
9334
+ function checkApi(credentials, email, error) {
9335
+ if (credentials === null) {
9336
+ return makeCheck(
9337
+ "api",
9338
+ "warn",
9339
+ "Dilewati: credential belum ada. Jalankan `jioogen login` lalu ulangi."
9340
+ );
9341
+ }
9342
+ if (error !== null) {
9343
+ const message = errorMessage(error);
9344
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
9345
+ return makeCheck(
9346
+ "api",
9347
+ "fail",
9348
+ `Sesi ditolak (${error.status}). Jalankan \`jioogen login\` lagi.`
9349
+ );
9350
+ }
9351
+ return makeCheck(
9352
+ "api",
9353
+ "warn",
9354
+ `Tidak dapat menghubungi ${credentials.apiUrl}: ${message}. Cek koneksi lalu ulangi.`
9355
+ );
9356
+ }
9357
+ return makeCheck(
9358
+ "api",
9359
+ "pass",
9360
+ `API ${credentials.apiUrl} terjangkau; login sebagai ${email ?? "-"}.`
9361
+ );
9362
+ }
9363
+ function checkBinding(requestedProjectId, link, error) {
9364
+ if (error !== null) {
9365
+ return makeCheck(
9366
+ "binding",
9367
+ "fail",
9368
+ `Link project tidak valid: ${error}. Perbaiki atau hapus .jioogen/project.json.`
9369
+ );
9370
+ }
9371
+ if (link === null) {
9372
+ return makeCheck(
9373
+ "binding",
9374
+ "fail",
9375
+ "Belum terikat ke project. Jalankan `jioogen pull <projectId>` di folder bundle."
9376
+ );
9377
+ }
9378
+ if (requestedProjectId !== void 0 && link.projectId !== requestedProjectId) {
9379
+ return makeCheck(
9380
+ "binding",
9381
+ "fail",
9382
+ `Bundle terikat ke project ${link.projectId}, bukan ${requestedProjectId}. Jalankan \`jioogen pull ${requestedProjectId}\`.`
9383
+ );
9384
+ }
9385
+ return makeCheck("binding", "pass", `Bundle terikat ke project ${link.projectId}.`);
9386
+ }
9387
+ async function checkProject(deps, credentials, projectId) {
9388
+ if (credentials === null) {
9389
+ return makeCheck("project", "warn", "Dilewati: credential belum ada.");
9390
+ }
9391
+ if (projectId === void 0 || projectId.length === 0) {
9392
+ return makeCheck(
9393
+ "project",
9394
+ "warn",
9395
+ "Dilewati: project belum diketahui. Jalankan `jioogen pull <projectId>`."
9396
+ );
9397
+ }
9398
+ try {
9399
+ await deps.fetchExecution(credentials.apiUrl, credentials.cookie, projectId);
9400
+ return makeCheck("project", "pass", `Project ${projectId} dapat diakses akun ini.`);
9401
+ } catch (error) {
9402
+ if (error instanceof ApiError) {
9403
+ if (error.status === 404) {
9404
+ return makeCheck(
9405
+ "project",
9406
+ "fail",
9407
+ `Project ${projectId} tidak ditemukan atau bukan milik akun ini.`
9408
+ );
9409
+ }
9410
+ if (error.status === 401 || error.status === 403) {
9411
+ return makeCheck(
9412
+ "project",
9413
+ "fail",
9414
+ `Akses project ditolak (${error.status}). Jalankan \`jioogen login\` lagi.`
9415
+ );
9416
+ }
9417
+ }
9418
+ return makeCheck(
9419
+ "project",
9420
+ "warn",
9421
+ `Gagal memeriksa project ${projectId}: ${errorMessage(error)}. Coba lagi saat API stabil.`
9422
+ );
9423
+ }
9424
+ }
9425
+ async function isFile2(path) {
9426
+ try {
9427
+ return (await stat3(path)).isFile();
9428
+ } catch {
9429
+ return false;
9430
+ }
9431
+ }
9432
+ async function isDirectory2(path) {
9433
+ try {
9434
+ return (await stat3(path)).isDirectory();
9435
+ } catch {
9436
+ return false;
9437
+ }
9438
+ }
9439
+ async function listMarkdownFiles(directory) {
9440
+ try {
9441
+ const entries = await readdir3(directory, { withFileTypes: true });
9442
+ return entries.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md")).map((entry) => entry.name);
9443
+ } catch {
9444
+ return [];
9445
+ }
9446
+ }
9447
+ async function checkBundle(bundleDir) {
9448
+ const missing = [];
9449
+ if (!await isFile2(join5(bundleDir, "PRD.md"))) missing.push("PRD.md");
9450
+ const specsDir = join5(bundleDir, "specs");
9451
+ if (!await isDirectory2(specsDir)) {
9452
+ missing.push("specs/");
9453
+ } else {
9454
+ const content = (await listMarkdownFiles(specsDir)).filter(
9455
+ (name) => name.toLowerCase() !== "readme.md"
9456
+ );
9457
+ if (content.length === 0) missing.push("specs/*.md (konten)");
9458
+ }
9459
+ const tasksDir = join5(bundleDir, "tasks");
9460
+ if (!await isDirectory2(tasksDir)) {
9461
+ missing.push("tasks/");
9462
+ } else {
9463
+ const content = (await listMarkdownFiles(tasksDir)).filter(
9464
+ (name) => name.toLowerCase() !== "readme.md"
9465
+ );
9466
+ if (content.length === 0) missing.push("tasks/*.md (task)");
9467
+ }
9468
+ if (missing.length > 0) {
9469
+ return makeCheck(
9470
+ "bundle",
9471
+ "fail",
9472
+ `Bundle tidak lengkap: ${missing.join(", ")}. Jalankan \`jioogen pull <projectId>\`.`
9473
+ );
9474
+ }
9475
+ try {
9476
+ const report = await inspectBundle(bundleDir);
9477
+ if (!report.ok) {
9478
+ const codes = Object.entries(report.issueCounts).map(([code, count]) => `${code}\xD7${count}`).join(", ");
9479
+ return makeCheck(
9480
+ "bundle",
9481
+ "fail",
9482
+ `Bundle gagal gate (${report.issueCount} isu: ${codes}). Perbaiki PRD/specs/tasks.`
9483
+ );
9484
+ }
9485
+ return makeCheck("bundle", "pass", `Bundle lengkap dan lulus gate (${report.files} file).`);
9486
+ } catch (error) {
9487
+ return makeCheck("bundle", "fail", `Gagal memeriksa bundle: ${errorMessage(error)}.`);
9488
+ }
9489
+ }
9490
+ async function checkSidecar(bundleDir) {
9491
+ try {
9492
+ const state = await readState(bundleDir);
9493
+ if (state === null) {
9494
+ return makeCheck("sidecar", "warn", "Sidecar belum ada. Jalankan `jioogen task next`.");
9495
+ }
9496
+ return makeCheck("sidecar", "pass", `Sidecar valid dengan ${state.tasks.length} task.`);
9497
+ } catch (error) {
9498
+ return makeCheck(
9499
+ "sidecar",
9500
+ "fail",
9501
+ `Sidecar tidak valid: ${errorMessage(error)}. Hapus tasks/.execution/state.json lalu jalankan \`jioogen task next\`.`
9502
+ );
9503
+ }
9504
+ }
9505
+ async function checkRecovery(bundleDir) {
9506
+ const path = join5(bundleDir, "tasks/.execution/recovery.json");
9507
+ let raw;
9508
+ try {
9509
+ raw = await readFile5(path, "utf8");
9510
+ } catch (error) {
9511
+ if (isMissingFile4(error)) {
9512
+ return makeCheck("recovery", "pass", "Belum ada recovery journal.");
9513
+ }
9514
+ return makeCheck("recovery", "warn", "Recovery journal tidak bisa dibaca.");
9515
+ }
9516
+ let payload;
9517
+ try {
9518
+ payload = JSON.parse(raw);
9519
+ } catch {
9520
+ return makeCheck("recovery", "warn", "Recovery journal bukan JSON valid.");
9521
+ }
9522
+ const tasks = typeof payload === "object" && payload !== null ? payload.tasks : void 0;
9523
+ if (tasks === void 0 || typeof tasks !== "object" || tasks === null) {
9524
+ return makeCheck("recovery", "warn", "Recovery journal tidak memuat tasks.");
9525
+ }
9526
+ const exhausted = Object.entries(tasks).filter(([, entry]) => entry?.exhausted === true).map(([ref]) => ref);
9527
+ if (exhausted.length > 0) {
9528
+ return makeCheck(
9529
+ "recovery",
9530
+ "warn",
9531
+ `Task RECOVERY_EXHAUSTED: ${exhausted.join(", ")}. Jalankan \`jioogen resume\`.`
9532
+ );
9533
+ }
9534
+ return makeCheck("recovery", "pass", "Recovery journal valid; tidak ada task exhausted.");
9535
+ }
9536
+ async function checkLock(bundleDir) {
9537
+ const target = lockPath(bundleDir);
9538
+ let info;
9539
+ try {
9540
+ info = await stat3(target);
9541
+ } catch (error) {
9542
+ if (isMissingFile4(error)) {
9543
+ return makeCheck("lock", "pass", "Tidak ada lock; sidecar bebas ditulis.");
9544
+ }
9545
+ return makeCheck("lock", "warn", `Tidak bisa memeriksa lock: ${errorMessage(error)}.`);
9546
+ }
9547
+ const ageMs = Date.now() - info.mtimeMs;
9548
+ const ageSeconds = Math.max(0, Math.round(ageMs / 1e3));
9549
+ if (ageMs > LOCK_STALE_MS2) {
9550
+ return makeCheck(
9551
+ "lock",
9552
+ "warn",
9553
+ `Lock basi (${ageSeconds} detik) tertinggal. Jalankan \`jioogen doctor --fix\` untuk menghapus.`,
9554
+ true
9555
+ );
9556
+ }
9557
+ return makeCheck(
9558
+ "lock",
9559
+ "warn",
9560
+ `Lock masih aktif (${ageSeconds} detik); proses lain mungkin menulis. Tunggu atau hapus bila proses sudah mati.`
9561
+ );
9562
+ }
9563
+ async function checkAgents(bundleDir) {
9564
+ let content;
9565
+ try {
9566
+ content = await readFile5(join5(bundleDir, "AGENTS.md"), "utf8");
9567
+ } catch (error) {
9568
+ if (isMissingFile4(error)) {
9569
+ return makeCheck(
9570
+ "agents",
9571
+ "fail",
9572
+ "AGENTS.md belum ada. Jalankan `jioogen doctor --fix` untuk memasang kontrak eksekusi.",
9573
+ true
9574
+ );
9575
+ }
9576
+ return makeCheck(
9577
+ "agents",
9578
+ "fail",
9579
+ `AGENTS.md tidak bisa dibaca: ${errorMessage(error)}.`,
9580
+ true
9581
+ );
9582
+ }
9583
+ if (!content.includes(AGENTS_MARKER)) {
9584
+ return makeCheck(
9585
+ "agents",
9586
+ "fail",
9587
+ "AGENTS.md ada tetapi tanpa marker JiooGen. Jalankan `jioogen doctor --fix` untuk memasang ulang.",
9588
+ true
9589
+ );
9590
+ }
9591
+ return makeCheck("agents", "pass", "AGENTS.md terpasang dengan marker eksekusi JiooGen.");
9592
+ }
9593
+ async function checkExecutionSkill(bundleDir) {
9594
+ const missing = [];
9595
+ for (const dir of AGENT_SKILL_DIRS) {
9596
+ const target = join5(bundleDir, dir, EXECUTION_SKILL_NAME, "SKILL.md");
9597
+ if (!await isFile2(target)) missing.push(dir);
9598
+ }
9599
+ if (missing.length > 0) {
9600
+ return makeCheck(
9601
+ "execution-skill",
9602
+ "fail",
9603
+ `Skill ${EXECUTION_SKILL_NAME} hilang di: ${missing.join(", ")}. Jalankan \`jioogen doctor --fix\`.`,
9604
+ true
9605
+ );
9606
+ }
9607
+ return makeCheck(
9608
+ "execution-skill",
9609
+ "pass",
9610
+ `Skill ${EXECUTION_SKILL_NAME} ada di ${AGENT_SKILL_DIRS.length} direktori harness.`
9611
+ );
9612
+ }
9613
+ async function checkSkillPacks(bundleDir) {
9614
+ let manifest;
9615
+ try {
9616
+ manifest = await readHarnessManifest(bundleDir);
9617
+ } catch (error) {
9618
+ return makeCheck(
9619
+ "skill-packs",
9620
+ "warn",
9621
+ `harness.json tidak bisa dibaca: ${errorMessage(error)}. Jalankan \`jioogen doctor --fix\`.`,
9622
+ true
9623
+ );
9624
+ }
9625
+ if (manifest === null) {
9626
+ return makeCheck(
9627
+ "skill-packs",
9628
+ "warn",
9629
+ ".jioogen/harness.json belum ada atau tidak valid. Jalankan `jioogen doctor --fix` untuk menulis ulang.",
9630
+ true
9631
+ );
9632
+ }
9633
+ if (manifest.packs.length === 0) {
9634
+ return makeCheck("skill-packs", "pass", "Tidak ada skill pack yang dikelola.");
9635
+ }
9636
+ const issues = [];
9637
+ for (const pack of manifest.packs) {
9638
+ for (const name of pack.missing) {
9639
+ issues.push(`${pack.name}: ${name} tidak tersedia saat instalasi`);
9640
+ }
9641
+ for (const skill of pack.skills) {
9642
+ let matched = false;
9643
+ for (const dir of AGENT_SKILL_DIRS) {
9644
+ const target = join5(bundleDir, dir, skill.name);
9645
+ if (!await isFile2(join5(target, "SKILL.md"))) continue;
9646
+ try {
9647
+ if (await hashSkillDirectory(target) === skill.sha256) {
9648
+ matched = true;
9649
+ break;
9650
+ }
9651
+ } catch {
9652
+ }
9653
+ }
9654
+ if (!matched) issues.push(`${pack.name}: ${skill.name} hilang atau hash tidak cocok`);
9655
+ }
9656
+ }
9657
+ if (issues.length > 0) {
9658
+ return makeCheck(
9659
+ "skill-packs",
9660
+ "warn",
9661
+ `Skill pack bermasalah: ${issues.join("; ")}. Jalankan \`jioogen doctor --fix\`.`,
9662
+ true
9663
+ );
9664
+ }
9665
+ return makeCheck(
9666
+ "skill-packs",
9667
+ "pass",
9668
+ `Semua skill pack cocok (${manifest.packs.length} pack).`
9669
+ );
9670
+ }
9671
+ async function checkDuplicates(bundleDir) {
9672
+ let manifest = null;
9673
+ try {
9674
+ manifest = await readHarnessManifest(bundleDir);
9675
+ } catch {
9676
+ }
9677
+ const managed = /* @__PURE__ */ new Set([EXECUTION_SKILL_NAME]);
9678
+ for (const pack of manifest?.packs ?? []) {
9679
+ for (const skill of pack.skills) managed.add(skill.name);
9680
+ }
9681
+ const dirsByName = /* @__PURE__ */ new Map();
9682
+ for (const dir of AGENT_SKILL_DIRS) {
9683
+ const root = join5(bundleDir, dir);
9684
+ if (!await isDirectory2(root)) continue;
9685
+ let entries;
9686
+ try {
9687
+ entries = await readdir3(root, { withFileTypes: true });
9688
+ } catch {
9689
+ continue;
9690
+ }
9691
+ for (const entry of entries) {
9692
+ if (!entry.isDirectory()) continue;
9693
+ if (managed.has(entry.name)) continue;
9694
+ if (!await isFile2(join5(root, entry.name, "SKILL.md"))) continue;
9695
+ const owners = dirsByName.get(entry.name) ?? [];
9696
+ owners.push(dir);
9697
+ dirsByName.set(entry.name, owners);
9698
+ }
9699
+ }
9700
+ const duplicates = [...dirsByName.entries()].filter(([, dirs]) => dirs.length > 1);
9701
+ if (duplicates.length === 0) {
9702
+ return makeCheck("duplicates", "pass", "Tidak ada skill duplikat antar-harness.");
9703
+ }
9704
+ const detail = duplicates.map(([name, dirs]) => `${name} (${dirs.join(", ")})`).join("; ");
9705
+ return makeCheck(
9706
+ "duplicates",
9707
+ "warn",
9708
+ `Skill yang sama ada di beberapa harness: ${detail}. Pastikan itu disengaja.`
9709
+ );
9710
+ }
9711
+ async function checkHarness(bundleDir) {
9712
+ const detected = [];
9713
+ for (const dir of AGENT_SKILL_DIRS) {
9714
+ if (await isDirectory2(join5(bundleDir, dir))) detected.push(dir);
9715
+ }
9716
+ if (detected.length === 0) {
9717
+ return makeCheck("harness", "pass", "Tidak ada direktori harness terdeteksi.");
9718
+ }
9719
+ return makeCheck("harness", "pass", `Harness terdeteksi: ${detected.join(", ")}.`);
9720
+ }
9721
+ async function runChecks(options, deps) {
9722
+ const checks = [checkNode()];
9723
+ let credentials = null;
9724
+ let credentialsError = null;
9725
+ try {
9726
+ credentials = await deps.readCredentials();
9727
+ } catch (error) {
9728
+ credentialsError = errorMessage(error);
9729
+ }
9730
+ checks.push(checkCredentials(credentials, credentialsError));
9731
+ let email = null;
9732
+ let apiError2 = null;
9733
+ if (credentials !== null) {
9734
+ try {
9735
+ email = (await deps.fetchMe(credentials.apiUrl, credentials.cookie)).email;
9736
+ } catch (error) {
9737
+ apiError2 = error;
9738
+ }
9739
+ }
9740
+ checks.push(checkApi(credentials, email, apiError2));
9741
+ let link = null;
9742
+ let linkError = null;
9743
+ try {
9744
+ link = await findProjectLink(options.bundleDir);
9745
+ } catch (error) {
9746
+ linkError = errorMessage(error);
9747
+ }
9748
+ checks.push(checkBinding(options.projectId, link, linkError));
9749
+ const effectiveProjectId = options.projectId ?? link?.projectId;
9750
+ checks.push(await checkProject(deps, credentials, effectiveProjectId));
9751
+ checks.push(await checkBundle(options.bundleDir));
9752
+ checks.push(await checkSidecar(options.bundleDir));
9753
+ checks.push(await checkLock(options.bundleDir));
9754
+ checks.push(await checkRecovery(options.bundleDir));
9755
+ checks.push(await checkAgents(options.bundleDir));
9756
+ checks.push(await checkExecutionSkill(options.bundleDir));
9757
+ checks.push(await checkSkillPacks(options.bundleDir));
9758
+ checks.push(await checkDuplicates(options.bundleDir));
9759
+ checks.push(await checkHarness(options.bundleDir));
9760
+ return checks;
9761
+ }
9762
+ async function applyFixes(options, deps, checks) {
9763
+ let changed = false;
9764
+ if (checks.some((check) => check.id === "lock" && check.fixable === true)) {
9765
+ try {
9766
+ await rm4(lockPath(options.bundleDir), { force: true });
9767
+ changed = true;
9768
+ } catch {
9769
+ }
9770
+ }
9771
+ const needsScaffold = checks.some(
9772
+ (check) => check.fixable === true && BUNDLE_SCAFFOLD_CHECKS.has(check.id)
9773
+ );
9774
+ if (needsScaffold) {
9775
+ try {
9776
+ await deps.installSkills(options.bundleDir);
9777
+ changed = true;
9778
+ } catch {
9779
+ }
9780
+ }
9781
+ return changed;
9782
+ }
9783
+ async function runDoctor(options) {
9784
+ const deps = resolveDeps(options.deps);
9785
+ let checks = await runChecks(options, deps);
9786
+ if (options.fix) {
9787
+ const changed = await applyFixes(options, deps, checks);
9788
+ if (changed) checks = await runChecks(options, deps);
9789
+ }
9790
+ return { ok: !checks.some((check) => check.status === "fail"), checks };
9791
+ }
9792
+
9793
+ // src/errors.ts
9794
+ var UsageError = class extends Error {
9795
+ };
9796
+
9797
+ // src/output.ts
9798
+ function formatTable(headers, rows) {
9799
+ const widths = headers.map(
9800
+ (header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length))
9801
+ );
9802
+ const render = (cells) => cells.map((cell, index) => cell.padEnd(widths[index] ?? 0)).join(" ").trimEnd();
9803
+ const divider = widths.map((width) => "-".repeat(width)).join(" ");
9804
+ return [render(headers), divider, ...rows.map(render)].join("\n");
9805
+ }
9806
+
9807
+ // src/recovery.ts
9808
+ import { randomUUID as randomUUID2 } from "node:crypto";
9809
+ import { mkdir as mkdir4, readFile as readFile6, rename as rename2, rm as rm5, writeFile as writeFile4 } from "node:fs/promises";
9810
+ import { dirname as dirname4, join as join6 } from "node:path";
9811
+ var RECOVERY_PATH = "tasks/.execution/recovery.json";
9812
+ var RECOVERY_BUDGET = { maxAttempts: 3 };
9813
+ function recoveryPath(bundleDir) {
9814
+ return join6(bundleDir, RECOVERY_PATH);
9815
+ }
9816
+ function emptyJournal() {
9817
+ return { schemaVersion: 1, tasks: {} };
9818
+ }
9819
+ function isJournal(value) {
9820
+ if (typeof value !== "object" || value === null) return false;
9821
+ const obj = value;
9822
+ if (obj.schemaVersion !== 1) return false;
9823
+ if (typeof obj.tasks !== "object" || obj.tasks === null) return false;
9824
+ return true;
9825
+ }
9826
+ async function readRecovery(bundleDir) {
9827
+ let raw;
9828
+ try {
9829
+ raw = await readFile6(recoveryPath(bundleDir), "utf8");
9830
+ } catch {
9831
+ return emptyJournal();
9832
+ }
9833
+ let payload;
9834
+ try {
9835
+ payload = JSON.parse(raw);
9836
+ } catch {
9837
+ return emptyJournal();
9838
+ }
9839
+ if (!isJournal(payload)) return emptyJournal();
9840
+ return payload;
9841
+ }
9842
+ function classifyFailure(input) {
9843
+ if (input.stalled === true || input.timedOut === true) return "transient";
9844
+ if (input.verificationFailed === true) return "semantic";
9845
+ const note = input.note ?? "";
9846
+ if (/^AUTHORIZATION:/i.test(note.trim())) return "authorization";
9847
+ if (/timeout|stall|econn|rate limit|\b429\b|\b5\d\d\b/i.test(note)) return "transient";
9848
+ const prior = input.prior ?? null;
9849
+ if (prior !== null && prior.attempts >= 1 && note === prior.lastNote) return "no_progress";
9850
+ return "semantic";
9851
+ }
9852
+ async function writeRecovery(bundleDir, journal) {
9853
+ const target = recoveryPath(bundleDir);
9854
+ await mkdir4(dirname4(target), { recursive: true });
9855
+ const temp = `${target}.${process.pid}.${randomUUID2()}.tmp`;
9856
+ try {
9857
+ await writeFile4(temp, `${JSON.stringify(journal, null, 2)}
9858
+ `, "utf8");
9859
+ await rename2(temp, target);
9860
+ } catch (error) {
9861
+ await rm5(temp, { force: true }).catch(() => {
9862
+ });
9863
+ throw error;
9864
+ }
9865
+ }
9866
+ async function recordFailure(bundleDir, ref, args) {
9867
+ return withStateLock(bundleDir, async () => {
9868
+ const journal = await readRecovery(bundleDir);
9869
+ const prior = journal.tasks[ref] ?? null;
9870
+ const klass = classifyFailure({ ...args, prior });
9871
+ const attempt = (prior?.attempts ?? 0) + 1;
9872
+ const exhausted = attempt >= RECOVERY_BUDGET.maxAttempts;
9873
+ const resumable = exhausted;
9874
+ const now = (/* @__PURE__ */ new Date()).toISOString();
9875
+ const note = args.note ?? "";
9876
+ const history = [...prior?.history ?? []];
9877
+ history.push({ attempt, class: klass, note, at: now });
9878
+ const capped = history.length > 20 ? history.slice(history.length - 20) : history;
9879
+ const entry = {
9880
+ ref,
9881
+ attempts: attempt,
9882
+ exhausted,
9883
+ resumable,
9884
+ lastClass: klass,
9885
+ lastNote: note === "" ? prior?.lastNote ?? "" : note,
9886
+ history: capped,
9887
+ updatedAt: now
9888
+ };
9889
+ journal.tasks[ref] = entry;
9890
+ await writeRecovery(bundleDir, journal);
9891
+ return { entry, exhausted, class: klass, attempt };
9892
+ });
9893
+ }
9894
+ async function recordSuccess(bundleDir, ref) {
9895
+ await withStateLock(bundleDir, async () => {
9896
+ const journal = await readRecovery(bundleDir);
9897
+ if (journal.tasks[ref] !== void 0) {
9898
+ delete journal.tasks[ref];
9899
+ await writeRecovery(bundleDir, journal);
9900
+ }
9901
+ });
9902
+ }
9903
+ async function rearmTask(bundleDir, ref) {
9904
+ await withStateLock(bundleDir, async () => {
9905
+ const journal = await readRecovery(bundleDir);
9906
+ const prior = journal.tasks[ref];
9907
+ const now = (/* @__PURE__ */ new Date()).toISOString();
9908
+ const entry = {
9909
+ ref,
9910
+ attempts: 0,
9911
+ exhausted: false,
9912
+ resumable: true,
9913
+ lastClass: prior?.lastClass ?? null,
9914
+ lastNote: prior?.lastNote ?? "",
9915
+ history: prior?.history ?? [],
9916
+ updatedAt: now
9917
+ };
9918
+ journal.tasks[ref] = entry;
9919
+ await writeRecovery(bundleDir, journal);
9920
+ });
9921
+ }
9922
+ function isExhausted(journal, ref) {
9923
+ return journal.tasks[ref]?.exhausted === true;
9924
+ }
9925
+ function describeRecovery(entry) {
9926
+ if (entry === void 0) {
9927
+ return "No recovery record. Run `jioogen resume`, then retry with a different approach.";
9928
+ }
9929
+ const lines = [];
9930
+ lines.push(
9931
+ `Task ${entry.ref}: ${entry.attempts}/${RECOVERY_BUDGET.maxAttempts} attempts, last=${entry.lastClass ?? "none"}.`
9932
+ );
9933
+ if (entry.lastNote.length > 0) lines.push(`Last note: ${entry.lastNote}`);
9934
+ lines.push("Run `jioogen resume`, then retry with a different approach.");
9935
+ return lines.join("\n");
9936
+ }
9937
+
9938
+ // src/session.ts
9939
+ import { rm as rm6, stat as stat4 } from "node:fs/promises";
9940
+ import { resolve as resolve3 } from "node:path";
9941
+
9281
9942
  // src/tasks.ts
9282
- import { readdir as readdir3, readFile as readFile5 } from "node:fs/promises";
9283
- import { join as join5 } from "node:path";
9943
+ import { readdir as readdir4, readFile as readFile7 } from "node:fs/promises";
9944
+ import { join as join7 } from "node:path";
9284
9945
  var TASK_ID_RE2 = /\b(?:TASK|T)-\d{3,}\b/i;
9285
9946
  var HEADING_RE = /^#{1,4}\s+(.+)$/m;
9286
9947
  var LAYER_RANK = {
@@ -9330,12 +9991,12 @@ var LAYER_CHECKLISTS = {
9330
9991
  ]
9331
9992
  };
9332
9993
  async function loadTasks(bundleDir) {
9333
- const tasksDir = join5(bundleDir, "tasks");
9994
+ const tasksDir = join7(bundleDir, "tasks");
9334
9995
  let entries;
9335
9996
  try {
9336
- entries = await readdir3(tasksDir, { withFileTypes: true });
9997
+ entries = await readdir4(tasksDir, { withFileTypes: true });
9337
9998
  } catch (error) {
9338
- if (isMissingFile4(error)) throw new Error(`Direktori tasks/ tidak ditemukan di ${bundleDir}`);
9999
+ if (isMissingFile5(error)) throw new Error(`Direktori tasks/ tidak ditemukan di ${bundleDir}`);
9339
10000
  throw error;
9340
10001
  }
9341
10002
  const names = entries.filter(
@@ -9344,16 +10005,16 @@ async function loadTasks(bundleDir) {
9344
10005
  const tasks = [];
9345
10006
  if (names.length > 0) {
9346
10007
  for (const name of names) {
9347
- const content = await readFile5(join5(tasksDir, name), "utf8");
10008
+ const content = await readFile7(join7(tasksDir, name), "utf8");
9348
10009
  tasks.push(parseSingleTask(name, content));
9349
10010
  }
9350
10011
  } else {
9351
- const singlePath = join5(tasksDir, "TASKS.md");
10012
+ const singlePath = join7(tasksDir, "TASKS.md");
9352
10013
  let content;
9353
10014
  try {
9354
- content = await readFile5(singlePath, "utf8");
10015
+ content = await readFile7(singlePath, "utf8");
9355
10016
  } catch (error) {
9356
- if (isMissingFile4(error)) throw new Error(`Tidak ada berkas task di ${tasksDir}`);
10017
+ if (isMissingFile5(error)) throw new Error(`Tidak ada berkas task di ${tasksDir}`);
9357
10018
  throw error;
9358
10019
  }
9359
10020
  tasks.push(...parseSingleFile(content));
@@ -9523,16 +10184,213 @@ function isBoundary(previous, next) {
9523
10184
  }
9524
10185
  return previous.phase !== void 0 && next.phase !== previous.phase;
9525
10186
  }
9526
- function isMissingFile4(error) {
10187
+ var RISKY_TASK_RE = /\b(migrat(?:e|ion|ions)?|migrasi|prisma|schema|rls|auth|permission|payment|checkout|webhook|secret|deploy|drop)\b/i;
10188
+ var TARGET_FILES_LABEL_RE = /^\s*(?:[-*]\s*)?\*{0,2}targetFiles\*{0,2}\s*:\s*(.*)$/i;
10189
+ function isRiskyTask(task) {
10190
+ const targetFiles = task.targetFiles ?? targetFilesFromContent(task.content);
10191
+ return RISKY_TASK_RE.test([task.id, task.title, ...targetFiles].join("\n"));
10192
+ }
10193
+ function targetFilesFromContent(content) {
10194
+ const lines = content.split(/\r?\n/);
10195
+ const index = lines.findIndex((line) => TARGET_FILES_LABEL_RE.test(line));
10196
+ if (index === -1) return [];
10197
+ const inline = (lines[index]?.match(TARGET_FILES_LABEL_RE)?.[1] ?? "").trim();
10198
+ if (inline.length > 0) return splitTargetFiles(inline);
10199
+ const items = [];
10200
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
10201
+ const line = lines[cursor] ?? "";
10202
+ if (line.trim().length === 0) continue;
10203
+ const item = /^\s*-\s+(.+?)\s*$/.exec(line);
10204
+ if (item === null) break;
10205
+ const cleaned = cleanTargetFile(item[1] ?? "");
10206
+ if (cleaned.length > 0) items.push(cleaned);
10207
+ }
10208
+ return items;
10209
+ }
10210
+ function splitTargetFiles(value) {
10211
+ return value.replace(/[[\]`]/g, "").split(",").map(cleanTargetFile).filter((part) => part.length > 0 && !/^(?:\(?none\)?|n\/a|-+)$/i.test(part));
10212
+ }
10213
+ function cleanTargetFile(value) {
10214
+ return value.replace(/^[-*\s]+/, "").trim();
10215
+ }
10216
+ function isMissingFile5(error) {
10217
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
10218
+ }
10219
+
10220
+ // src/session.ts
10221
+ var LOCK_STALE_MS3 = 1e4;
10222
+ var CHANGE_REQUEST_PREFIX = "Perubahan diminta:";
10223
+ async function resumeSession(options) {
10224
+ const context = await resolveBundleContext(options);
10225
+ await removeStaleLock2(context.bundleDir);
10226
+ const initial = await readState(context.bundleDir);
10227
+ if (initial === null) {
10228
+ return {
10229
+ projectId: context.projectId ?? "",
10230
+ bundleDir: context.bundleDir,
10231
+ hasState: false,
10232
+ current: null,
10233
+ nextRef: null,
10234
+ awaitingCheckpoint: false
10235
+ };
10236
+ }
10237
+ const definitions = await loadTasks(context.bundleDir);
10238
+ const written = await withStateLock(context.bundleDir, async () => {
10239
+ const state = await readState(context.bundleDir) ?? initial;
10240
+ const merged = mergeTasks(state, definitions);
10241
+ return writeState(context.bundleDir, merged);
10242
+ });
10243
+ const journal = await readRecovery(context.bundleDir);
10244
+ const exhausted = written.tasks.filter(
10245
+ (task) => isExhausted(journal, task.ref.toUpperCase()) || isExhausted(journal, task.ref)
10246
+ );
10247
+ if (exhausted.length > 0) {
10248
+ await withStateLock(context.bundleDir, async () => {
10249
+ const state = await readState(context.bundleDir) ?? written;
10250
+ let next2 = state;
10251
+ for (const task of exhausted) {
10252
+ next2 = withStatus(next2, task.ref, "todo", { awaitingCheckpoint: false });
10253
+ }
10254
+ await writeState(context.bundleDir, next2);
10255
+ });
10256
+ for (const task of exhausted) await rearmTask(context.bundleDir, task.ref.toUpperCase());
10257
+ }
10258
+ const finalState = await readState(context.bundleDir) ?? written;
10259
+ const current = finalState.current ?? null;
10260
+ const next = selectNext(definitions, finalState.tasks);
10261
+ return {
10262
+ projectId: finalState.projectId ?? context.projectId ?? "",
10263
+ bundleDir: context.bundleDir,
10264
+ hasState: true,
10265
+ current,
10266
+ nextRef: next?.task.id ?? null,
10267
+ awaitingCheckpoint: current?.awaitingCheckpoint === true
10268
+ };
10269
+ }
10270
+ async function reviewSession(options, review) {
10271
+ const context = await resolveBundleContext(options);
10272
+ return withStateLock(context.bundleDir, async () => {
10273
+ const state = await readState(context.bundleDir);
10274
+ if (state === null) return unchanged(review.action, null);
10275
+ const current = state.current ?? null;
10276
+ if (review.action === "stop") {
10277
+ return stopReview(context.bundleDir, state, current, review.note);
10278
+ }
10279
+ if (current === null || current.awaitingCheckpoint !== true) {
10280
+ return unchanged(review.action, current?.ref ?? null);
10281
+ }
10282
+ if (review.action === "approve") {
10283
+ const cleared = { ...current, awaitingCheckpoint: false };
10284
+ const written2 = await writeState(context.bundleDir, setCurrent(state, cleared));
10285
+ const ref2 = written2.current?.ref ?? current.ref ?? null;
10286
+ return { action: review.action, ref: ref2, clearedCheckpoint: true, nextRef: ref2 };
10287
+ }
10288
+ const ref = review.ref ?? latestDoneRef(state);
10289
+ if (ref === null) {
10290
+ return {
10291
+ action: review.action,
10292
+ ref: null,
10293
+ clearedCheckpoint: false,
10294
+ nextRef: current.ref ?? null
10295
+ };
10296
+ }
10297
+ const target = findTask(state, ref);
10298
+ if (target === void 0) {
10299
+ throw new Error(
10300
+ `Task ${ref} tidak ada di sidecar. Jalankan \`jioogen task next\` lebih dulu.`
10301
+ );
10302
+ }
10303
+ const note = `${CHANGE_REQUEST_PREFIX} ${review.note ?? ""}`.trim();
10304
+ const reopened = withStatus(state, target.ref, "in_progress", {
10305
+ note,
10306
+ awaitingCheckpoint: false
10307
+ });
10308
+ const reopenedTarget = findTask(reopened, target.ref);
10309
+ const nextCurrent = {
10310
+ ref: reopenedTarget?.ref ?? target.ref,
10311
+ ...reopenedTarget?.layer !== void 0 ? { layer: reopenedTarget.layer } : {},
10312
+ ...reopenedTarget?.phase !== void 0 ? { phase: reopenedTarget.phase } : {},
10313
+ awaitingCheckpoint: false
10314
+ };
10315
+ const written = await writeState(context.bundleDir, setCurrent(reopened, nextCurrent));
10316
+ const finalRef = written.current?.ref ?? nextCurrent.ref ?? null;
10317
+ return { action: review.action, ref: finalRef, clearedCheckpoint: true, nextRef: finalRef };
10318
+ });
10319
+ }
10320
+ async function stopReview(bundleDir, state, current, note) {
10321
+ const ref = current?.ref ?? null;
10322
+ if (note === void 0 || note.length === 0 || current?.ref === void 0) {
10323
+ return { action: "stop", ref, clearedCheckpoint: false, nextRef: ref };
10324
+ }
10325
+ const key = current.ref.toUpperCase();
10326
+ const now = (/* @__PURE__ */ new Date()).toISOString();
10327
+ const tasks = state.tasks.map(
10328
+ (task) => task.ref.toUpperCase() === key ? { ...task, note, updatedAt: now } : task
10329
+ );
10330
+ const written = await writeState(bundleDir, { ...state, tasks });
10331
+ return {
10332
+ action: "stop",
10333
+ ref,
10334
+ clearedCheckpoint: false,
10335
+ nextRef: written.current?.ref ?? ref
10336
+ };
10337
+ }
10338
+ function unchanged(action, ref) {
10339
+ return { action, ref, clearedCheckpoint: false, nextRef: ref };
10340
+ }
10341
+ function findTask(state, ref) {
10342
+ const key = ref.toUpperCase();
10343
+ return state.tasks.find((task) => task.ref.toUpperCase() === key);
10344
+ }
10345
+ function latestDoneRef(state) {
10346
+ let latest = null;
10347
+ for (const task of state.tasks) {
10348
+ if (task.status !== "done") continue;
10349
+ if (latest === null || updatedAtMs(task) >= updatedAtMs(latest)) latest = task;
10350
+ }
10351
+ return latest?.ref ?? null;
10352
+ }
10353
+ function updatedAtMs(task) {
10354
+ if (task.updatedAt === void 0) return Number.NEGATIVE_INFINITY;
10355
+ const value = Date.parse(task.updatedAt);
10356
+ return Number.isNaN(value) ? Number.NEGATIVE_INFINITY : value;
10357
+ }
10358
+ async function resolveBundleContext(options) {
10359
+ const link = await findProjectLink(options.dir ?? process.cwd());
10360
+ const projectId = options.project ?? envFirst("JIOOGEN_PROJECT", "JIOOCODE_PROJECT") ?? link?.projectId;
10361
+ return {
10362
+ projectId,
10363
+ bundleDir: resolve3(link?.bundleDir ?? options.dir ?? process.cwd())
10364
+ };
10365
+ }
10366
+ async function removeStaleLock2(bundleDir) {
10367
+ const target = lockPath(bundleDir);
10368
+ let info;
10369
+ try {
10370
+ info = await stat4(target);
10371
+ } catch (error) {
10372
+ if (isMissingFile6(error)) return;
10373
+ throw error;
10374
+ }
10375
+ if (Date.now() - info.mtimeMs <= LOCK_STALE_MS3) return;
10376
+ await rm6(target, { force: true });
10377
+ }
10378
+ function envFirst(primary, legacy) {
10379
+ const value = process.env[primary]?.trim();
10380
+ if (value !== void 0 && value.length > 0) return value;
10381
+ const fallback = process.env[legacy]?.trim();
10382
+ return fallback !== void 0 && fallback.length > 0 ? fallback : void 0;
10383
+ }
10384
+ function isMissingFile6(error) {
9527
10385
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
9528
10386
  }
9529
10387
 
9530
10388
  // src/zip.ts
9531
10389
  var import_adm_zip = __toESM(require_adm_zip(), 1);
9532
- import { mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
9533
- import { dirname as dirname4, resolve as resolve3, sep } from "node:path";
10390
+ import { mkdir as mkdir5, writeFile as writeFile5 } from "node:fs/promises";
10391
+ import { dirname as dirname5, resolve as resolve4, sep } from "node:path";
9534
10392
  async function extractBundle(bytes, targetDir) {
9535
- const root = resolve3(targetDir);
10393
+ const root = resolve4(targetDir);
9536
10394
  const zip = new import_adm_zip.default(Buffer.from(bytes));
9537
10395
  const written = [];
9538
10396
  for (const entry of zip.getEntries()) {
@@ -9542,12 +10400,12 @@ async function extractBundle(bytes, targetDir) {
9542
10400
  if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
9543
10401
  throw new Error(`Path bundle tidak aman: ${entry.entryName}`);
9544
10402
  }
9545
- const destination = resolve3(root, relative2);
10403
+ const destination = resolve4(root, relative2);
9546
10404
  if (!destination.startsWith(`${root}${sep}`)) {
9547
10405
  throw new Error(`Path bundle keluar dari direktori target: ${entry.entryName}`);
9548
10406
  }
9549
- await mkdir4(dirname4(destination), { recursive: true });
9550
- await writeFile4(destination, entry.getData());
10407
+ await mkdir5(dirname5(destination), { recursive: true });
10408
+ await writeFile5(destination, entry.getData());
9551
10409
  written.push(relative2);
9552
10410
  }
9553
10411
  return written;
@@ -9559,10 +10417,10 @@ function isValidProjectId(projectId) {
9559
10417
  return PROJECT_ID_RE.test(projectId.trim());
9560
10418
  }
9561
10419
  async function loginCommand(options) {
9562
- const token = options.token ?? envFirst("JIOOGEN_TOKEN", "JIOOCODE_TOKEN");
10420
+ const token = options.token ?? envFirst2("JIOOGEN_TOKEN", "JIOOCODE_TOKEN");
9563
10421
  if (token !== void 0 && token.length > 0) {
9564
10422
  const apiUrl = normalizeBaseUrl(
9565
- options.api ?? envFirst("JIOOGEN_API", "JIOOCODE_API") ?? DEFAULT_API_URL
10423
+ options.api ?? envFirst2("JIOOGEN_API", "JIOOCODE_API") ?? DEFAULT_API_URL
9566
10424
  );
9567
10425
  const client = new ApiClient(apiUrl, `${SESSION_COOKIE}=${token}`);
9568
10426
  const body = await client.getJson(ENDPOINTS.me);
@@ -9577,17 +10435,17 @@ async function loginCommand(options) {
9577
10435
  console.log(`Credential disimpan di ${credentialsPath()} (mode 0600).`);
9578
10436
  return;
9579
10437
  }
9580
- const email = options.email ?? envFirst("JIOOGEN_EMAIL", "JIOOCODE_EMAIL");
10438
+ const email = options.email ?? envFirst2("JIOOGEN_EMAIL", "JIOOCODE_EMAIL");
9581
10439
  if (email === void 0 || email.length === 0) {
9582
10440
  throw new Error("--email wajib diisi (atau set JIOOGEN_EMAIL).");
9583
10441
  }
9584
- let password = options.password ?? envFirst("JIOOGEN_PASSWORD", "JIOOCODE_PASSWORD");
10442
+ let password = options.password ?? envFirst2("JIOOGEN_PASSWORD", "JIOOCODE_PASSWORD");
9585
10443
  if (options.passwordStdin === true) password = (await readStdin()).trim();
9586
10444
  if (password === void 0 || password.length === 0) {
9587
10445
  throw new Error("--password atau --password-stdin wajib diisi.");
9588
10446
  }
9589
10447
  const result = await apiLogin(
9590
- options.api ?? envFirst("JIOOGEN_API", "JIOOCODE_API") ?? DEFAULT_API_URL,
10448
+ options.api ?? envFirst2("JIOOGEN_API", "JIOOCODE_API") ?? DEFAULT_API_URL,
9591
10449
  email,
9592
10450
  password
9593
10451
  );
@@ -9645,7 +10503,7 @@ async function pullCommand(projectId, options) {
9645
10503
  }
9646
10504
  await assertPullDefaultDir(process.cwd(), options.dir);
9647
10505
  const { apiUrl, client } = await resolveApi(options);
9648
- const target = resolve4(options.dir ?? projectId);
10506
+ const target = resolve5(options.dir ?? projectId);
9649
10507
  await assertPullTarget(target, projectId, options.force === true);
9650
10508
  const bytes = await client.getBytes(projectPath(projectId, "/bundle"));
9651
10509
  const written = await extractBundle(bytes, target);
@@ -9662,12 +10520,12 @@ async function pullCommand(projectId, options) {
9662
10520
  }
9663
10521
  async function linkCommand(projectId, options) {
9664
10522
  const { apiUrl, client } = await resolveApi(options);
9665
- const target = resolve4(options.dir ?? process.cwd());
10523
+ const target = resolve5(options.dir ?? process.cwd());
9666
10524
  await assertLinkTarget(target, projectId);
9667
10525
  await verifyProjectAccess(client, projectId);
9668
10526
  await writeProjectLink(target, { projectId, apiUrl });
9669
10527
  const skills = await installAgentSkills(target, { noSkills: skillsDisabled(options) });
9670
- const linkedFile = join6(target, ".jioogen", "project.json");
10528
+ const linkedFile = join8(target, ".jioogen", "project.json");
9671
10529
  if (options.json === true) {
9672
10530
  console.log(JSON.stringify({ projectId, target, apiUrl, linkedFile, skills }, null, 2));
9673
10531
  return;
@@ -9762,7 +10620,7 @@ async function skillsRemoveCommand(packArgument, options) {
9762
10620
  }
9763
10621
  async function resolveSkillsBundleDir(options) {
9764
10622
  const link = await findProjectLink(options.dir ?? process.cwd());
9765
- return resolve4(link?.bundleDir ?? options.dir ?? process.cwd());
10623
+ return resolve5(link?.bundleDir ?? options.dir ?? process.cwd());
9766
10624
  }
9767
10625
  function printSkillPacks(packs, missing) {
9768
10626
  if (packs.length === 0 && missing.length === 0) return;
@@ -9774,7 +10632,7 @@ function printSkillPacks(packs, missing) {
9774
10632
  }
9775
10633
  async function checkCommand(options) {
9776
10634
  const link = await findProjectLink(options.dir ?? process.cwd());
9777
- const bundleDir = resolve4(link?.bundleDir ?? options.dir ?? process.cwd());
10635
+ const bundleDir = resolve5(link?.bundleDir ?? options.dir ?? process.cwd());
9778
10636
  const result = await inspectBundle(bundleDir);
9779
10637
  if (options.json === true) {
9780
10638
  console.log(JSON.stringify(result, null, 2));
@@ -9783,6 +10641,90 @@ async function checkCommand(options) {
9783
10641
  }
9784
10642
  if (!result.ok) process.exitCode = 1;
9785
10643
  }
10644
+ async function doctorCommand(options) {
10645
+ const link = await findProjectLink(options.dir ?? process.cwd());
10646
+ const bundleDir = resolve5(link?.bundleDir ?? options.dir ?? process.cwd());
10647
+ const projectId = options.project ?? link?.projectId;
10648
+ const report = await runDoctor({
10649
+ bundleDir,
10650
+ ...projectId === void 0 ? {} : { projectId },
10651
+ fix: options.fix === true
10652
+ });
10653
+ if (options.json === true) {
10654
+ console.log(JSON.stringify(report, null, 2));
10655
+ } else {
10656
+ for (const check of report.checks) {
10657
+ console.log(`${check.status.toUpperCase().padEnd(4)} ${check.id} \u2014 ${check.detail}`);
10658
+ }
10659
+ const fails = report.checks.filter((check) => check.status === "fail").length;
10660
+ const warns = report.checks.filter((check) => check.status === "warn").length;
10661
+ console.log(
10662
+ `
10663
+ ${report.ok ? "Doctor OK" : "Doctor GAGAL"} (${fails} fail, ${warns} warn).` + (report.ok || options.fix === true ? "" : " Jalankan `jioogen doctor --fix` untuk perbaikan wiring.")
10664
+ );
10665
+ }
10666
+ if (!report.ok) process.exitCode = 1;
10667
+ }
10668
+ async function resumeCommand(options) {
10669
+ const result = await resumeSession(options);
10670
+ if (options.json === true) {
10671
+ console.log(JSON.stringify(result, null, 2));
10672
+ return;
10673
+ }
10674
+ if (!result.hasState) {
10675
+ console.log("Belum ada eksekusi tersimpan. Mulai dengan `jioogen task next`.");
10676
+ return;
10677
+ }
10678
+ const current = result.current?.ref ?? "-";
10679
+ console.log(`Resume project ${result.projectId} di ${result.bundleDir}.`);
10680
+ console.log(`Current: ${current}${result.awaitingCheckpoint ? " (checkpoint)" : ""}`);
10681
+ console.log(`Task berikutnya: ${result.nextRef ?? "selesai"}.`);
10682
+ if (result.awaitingCheckpoint) {
10683
+ console.log(
10684
+ 'Putuskan: `jioogen review --approve`, `--request-changes "<teks>"`, atau `--stop`.'
10685
+ );
10686
+ }
10687
+ }
10688
+ async function reviewCommand(options) {
10689
+ const actions = [
10690
+ options.approve === true ? "approve" : void 0,
10691
+ options.requestChanges !== void 0 ? "request-changes" : void 0,
10692
+ options.stop === true ? "stop" : void 0
10693
+ ].filter((action2) => action2 !== void 0);
10694
+ if (actions.length !== 1) {
10695
+ throw new UsageError(
10696
+ '`jioogen review` butuh tepat satu: --approve, --request-changes "<teks>", atau --stop.'
10697
+ );
10698
+ }
10699
+ const action = actions[0];
10700
+ if (action === void 0) {
10701
+ throw new UsageError("`jioogen review` butuh tepat satu aksi.");
10702
+ }
10703
+ const result = await reviewSession(options, {
10704
+ action,
10705
+ ...options.requestChanges === void 0 ? {} : { note: options.requestChanges },
10706
+ ...options.ref === void 0 ? {} : { ref: options.ref }
10707
+ });
10708
+ if (options.json === true) {
10709
+ console.log(JSON.stringify(result, null, 2));
10710
+ return;
10711
+ }
10712
+ if (action === "stop") {
10713
+ console.log("Review: stop. Checkpoint dipertahankan; lanjutkan kapan saja dengan `resume`.");
10714
+ return;
10715
+ }
10716
+ if (!result.clearedCheckpoint) {
10717
+ console.log("Tidak ada checkpoint aktif. Jalankan `jioogen resume` untuk status.");
10718
+ return;
10719
+ }
10720
+ if (action === "approve") {
10721
+ console.log("Review: disetujui. Checkpoint dibuka.");
10722
+ } else {
10723
+ console.log(`Review: perubahan diminta untuk ${result.ref ?? "task terakhir"}.`);
10724
+ }
10725
+ if (result.nextRef !== null) console.log(`Task berikutnya: ${result.nextRef}.`);
10726
+ console.log("Jalankan `jioogen sync` agar panel monitoring ikut diperbarui.");
10727
+ }
9786
10728
  async function handoffCommand(options) {
9787
10729
  const { client, projectId } = await resolveBundle(options);
9788
10730
  const payload = await client.postJson(
@@ -9828,6 +10770,21 @@ async function taskNextCommand(options) {
9828
10770
  return;
9829
10771
  }
9830
10772
  const awaitingCheckpoint = written.current?.awaitingCheckpoint === true;
10773
+ const journal = await readRecovery(bundleDir);
10774
+ if (isExhausted(journal, next.task.id)) {
10775
+ const entry = journal.tasks[next.task.id];
10776
+ const diagnosis = describeRecovery(entry);
10777
+ if (options.json === true) {
10778
+ console.log(
10779
+ JSON.stringify({ done: false, projectId, recoveryExhausted: true, diagnosis }, null, 2)
10780
+ );
10781
+ return;
10782
+ }
10783
+ console.log("## RECOVERY_EXHAUSTED \u2014 task ini butuh keputusan");
10784
+ console.log(diagnosis);
10785
+ console.log("\nLanjutkan dengan `npx jioogen resume`, lalu ulangi dengan pendekatan berbeda.");
10786
+ return;
10787
+ }
9831
10788
  const manifest = await readHarnessManifest(bundleDir);
9832
10789
  const context = manifest === null ? void 0 : {
9833
10790
  productKind: manifest.productKind,
@@ -9865,7 +10822,14 @@ Status: ${next.state.status} \u2014 silakan ulangi.`);
9865
10822
  Progress: ${written.counts?.done ?? 0}/${definitions.length} task selesai.`);
9866
10823
  }
9867
10824
  async function taskStartCommand(ref, options) {
10825
+ const key = ref.trim().toUpperCase();
9868
10826
  const task = await withLocalState(options, async (local) => {
10827
+ const journal = await readRecovery(local.bundleDir);
10828
+ if (isExhausted(journal, key) || isExhausted(journal, ref)) {
10829
+ throw new Error(
10830
+ `Task ${ref} berstatus RECOVERY_EXHAUSTED. Jalankan \`jioogen resume\` lalu ulangi dengan pendekatan berbeda.`
10831
+ );
10832
+ }
9869
10833
  assertStartDependencies(ref, local.definitions, local.state.tasks);
9870
10834
  const updated = withStatus(local.state, ref, "in_progress", {
9871
10835
  awaitingCheckpoint: false,
@@ -9877,49 +10841,84 @@ async function taskStartCommand(ref, options) {
9877
10841
  console.log(`Started ${task?.ref ?? ref} (attempt ${task?.attempt ?? 1}).`);
9878
10842
  }
9879
10843
  async function taskCompleteCommand(ref, options) {
9880
- const { completedTask, next, checkpoint } = await withLocalState(options, async (local) => {
9881
- assertCompleteDependencies(ref, local.definitions, local.state.tasks, options.force === true);
9882
- const completed = withStatus(local.state, ref, "done", {
9883
- note: options.note ?? "",
9884
- awaitingCheckpoint: false
9885
- });
9886
- const completedTask2 = completed.tasks.find(
9887
- (entry) => entry.ref.toUpperCase() === ref.toUpperCase()
9888
- );
9889
- const next2 = selectNext(local.definitions, completed.tasks);
9890
- if (completedTask2 !== void 0 && next2 !== null && isBoundary(completedTask2, next2.task)) {
9891
- const withCheckpoint = setCurrent(completed, {
9892
- ref: next2.task.id,
9893
- ...next2.task.layer !== void 0 ? { layer: next2.task.layer } : {},
9894
- phase: next2.task.phase,
9895
- awaitingCheckpoint: true
10844
+ const { completedTask, next, checkpoint, bundleDir } = await withLocalState(
10845
+ options,
10846
+ async (local) => {
10847
+ assertCompleteDependencies(ref, local.definitions, local.state.tasks, options.force === true);
10848
+ const completed = withStatus(local.state, ref, "done", {
10849
+ note: options.note ?? "",
10850
+ awaitingCheckpoint: false
9896
10851
  });
9897
- await writeState(local.bundleDir, withCheckpoint);
9898
- return { completedTask: completedTask2, next: next2, checkpoint: true };
10852
+ const completedTask2 = completed.tasks.find(
10853
+ (entry) => entry.ref.toUpperCase() === ref.toUpperCase()
10854
+ );
10855
+ const next2 = selectNext(local.definitions, completed.tasks);
10856
+ const definition = local.definitions.find(
10857
+ (entry) => entry.id.toUpperCase() === ref.toUpperCase()
10858
+ );
10859
+ const risky = definition !== void 0 && isRiskyTask(definition);
10860
+ const boundary = completedTask2 !== void 0 && (next2 !== null && isBoundary(completedTask2, next2.task) || risky);
10861
+ if (boundary && completedTask2 !== void 0) {
10862
+ const target = next2?.task;
10863
+ const withCheckpoint = setCurrent(completed, {
10864
+ ref: target?.id ?? completedTask2.ref,
10865
+ layer: target?.layer ?? completedTask2.layer,
10866
+ phase: target?.phase ?? completedTask2.phase ?? 1,
10867
+ awaitingCheckpoint: true
10868
+ });
10869
+ await writeState(local.bundleDir, withCheckpoint);
10870
+ return { completedTask: completedTask2, next: next2, checkpoint: true, bundleDir: local.bundleDir };
10871
+ }
10872
+ await writeState(local.bundleDir, completed);
10873
+ return { completedTask: completedTask2, next: next2, checkpoint: false, bundleDir: local.bundleDir };
9899
10874
  }
9900
- await writeState(local.bundleDir, completed);
9901
- return { completedTask: completedTask2, next: next2, checkpoint: false };
9902
- });
10875
+ );
10876
+ await recordSuccess(bundleDir, ref.trim().toUpperCase());
9903
10877
  console.log(`Done ${completedTask?.ref ?? ref}.`);
9904
- if (checkpoint && next !== null) {
10878
+ if (checkpoint) {
10879
+ if (next === null) {
10880
+ console.log("Semua task selesai; menunggu review terakhir.");
10881
+ } else {
10882
+ console.log(
10883
+ `Checkpoint berikutnya: ${next.task.id} (${next.task.layer ?? "-"} / phase ${next.task.phase}).`
10884
+ );
10885
+ }
9905
10886
  console.log(
9906
- `Checkpoint berikutnya: ${next.task.id} (${next.task.layer ?? "-"} / phase ${next.task.phase}).`
10887
+ 'Berhenti. Setelah user memutuskan: `jioogen review --approve`, `--request-changes "<teks>"`, atau `--stop`; lalu `jioogen sync`.'
9907
10888
  );
9908
- console.log("Berhenti dan minta konfirmasi user sebelum task start berikutnya.");
9909
10889
  return;
9910
10890
  }
9911
10891
  if (next !== null) console.log(`Berikutnya: ${next.task.id} \u2014 ${next.task.title}`);
9912
10892
  }
9913
10893
  async function taskFailCommand(ref, reasonParts, options) {
9914
10894
  const reason = reasonParts.join(" ").trim() || options.note || "";
9915
- await withLocalState(options, async (local) => {
10895
+ const key = ref.trim().toUpperCase();
10896
+ const bundleDir = await withLocalState(options, async (local) => {
9916
10897
  const updated = withStatus(local.state, ref, "failed", {
9917
10898
  note: reason,
9918
10899
  awaitingCheckpoint: false
9919
10900
  });
9920
10901
  await writeState(local.bundleDir, updated);
10902
+ return local.bundleDir;
9921
10903
  });
10904
+ const recovery = await recordFailure(bundleDir, key, { note: reason });
10905
+ if (recovery.exhausted) {
10906
+ await withLocalState(options, async (local) => {
10907
+ const blocked = withStatus(local.state, ref, "blocked", {
10908
+ note: `RECOVERY_EXHAUSTED: ${describeRecovery(recovery.entry)}`,
10909
+ awaitingCheckpoint: false
10910
+ });
10911
+ await writeState(local.bundleDir, blocked);
10912
+ });
10913
+ }
9922
10914
  console.log(`Failed ${ref}${reason.length > 0 ? `: ${reason}` : "."}`);
10915
+ console.log(
10916
+ `Recovery: attempt ${recovery.attempt}/${RECOVERY_BUDGET.maxAttempts}, kelas ${recovery.class}.`
10917
+ );
10918
+ if (recovery.exhausted) {
10919
+ console.log("Status: RECOVERY_EXHAUSTED (blocked). State tersimpan dan bisa dilanjutkan.");
10920
+ console.log(describeRecovery(recovery.entry));
10921
+ }
9923
10922
  }
9924
10923
  async function taskResetCommand(ref, reasonParts, options) {
9925
10924
  const reason = reasonParts.join(" ").trim() || options.note || "";
@@ -10007,7 +11006,7 @@ async function syncCommand(options) {
10007
11006
  assertBundleRelative(relative2);
10008
11007
  files.push({
10009
11008
  path: relative2,
10010
- content: await readFile6(join6(bundleDir, relative2), "utf8")
11009
+ content: await readFile8(join8(bundleDir, relative2), "utf8")
10011
11010
  });
10012
11011
  }
10013
11012
  }
@@ -10029,9 +11028,9 @@ async function syncCommand(options) {
10029
11028
  async function resolveApi(options) {
10030
11029
  const stored = await readCredentials();
10031
11030
  const apiUrl = normalizeBaseUrl(
10032
- options.api ?? envFirst("JIOOGEN_API", "JIOOCODE_API") ?? stored?.apiUrl ?? DEFAULT_API_URL
11031
+ options.api ?? envFirst2("JIOOGEN_API", "JIOOCODE_API") ?? stored?.apiUrl ?? DEFAULT_API_URL
10033
11032
  );
10034
- const explicitCookie = envFirst("JIOOGEN_COOKIE", "JIOOCODE_COOKIE");
11033
+ const explicitCookie = envFirst2("JIOOGEN_COOKIE", "JIOOCODE_COOKIE");
10035
11034
  const storedCookie = stored !== null && normalizeBaseUrl(stored.apiUrl) === apiUrl ? stored.cookie : void 0;
10036
11035
  const cookie = explicitCookie || storedCookie;
10037
11036
  if (cookie === void 0 || cookie.length === 0) {
@@ -10046,7 +11045,7 @@ async function resolveApi(options) {
10046
11045
  }
10047
11046
  async function resolveLocalBundle(options) {
10048
11047
  const link = await findProjectLink(options.dir ?? process.cwd());
10049
- const projectId = options.project ?? envFirst("JIOOGEN_PROJECT", "JIOOCODE_PROJECT") ?? link?.projectId;
11048
+ const projectId = options.project ?? envFirst2("JIOOGEN_PROJECT", "JIOOCODE_PROJECT") ?? link?.projectId;
10050
11049
  if (projectId === void 0 || projectId.length === 0) {
10051
11050
  throw new Error(
10052
11051
  "Project belum di-bind. Jalankan `jioogen pull <projectId>` atau pakai --project."
@@ -10054,7 +11053,7 @@ async function resolveLocalBundle(options) {
10054
11053
  }
10055
11054
  return {
10056
11055
  projectId,
10057
- bundleDir: resolve4(link?.bundleDir ?? options.dir ?? process.cwd()),
11056
+ bundleDir: resolve5(link?.bundleDir ?? options.dir ?? process.cwd()),
10058
11057
  linkedApiUrl: link?.apiUrl
10059
11058
  };
10060
11059
  }
@@ -10107,9 +11106,9 @@ async function assertPullDefaultDir(cwd, dirOption) {
10107
11106
  async function assertPullTarget(target, projectId, force = false) {
10108
11107
  let entries;
10109
11108
  try {
10110
- entries = await readdir4(target);
11109
+ entries = await readdir5(target);
10111
11110
  } catch (error) {
10112
- if (isMissingFile5(error)) return;
11111
+ if (isMissingFile7(error)) return;
10113
11112
  throw error;
10114
11113
  }
10115
11114
  if (entries.length === 0) return;
@@ -10141,19 +11140,19 @@ async function assertLinkTarget(target, projectId) {
10141
11140
  }
10142
11141
  async function hasBundleMarkers(target) {
10143
11142
  try {
10144
- await readFile6(join6(target, "PRD.md"));
11143
+ await readFile8(join8(target, "PRD.md"));
10145
11144
  return true;
10146
11145
  } catch (error) {
10147
- if (!isMissingFile5(error)) throw error;
11146
+ if (!isMissingFile7(error)) throw error;
10148
11147
  }
10149
- return hasTaskMarkdown(join6(target, "tasks"));
11148
+ return hasTaskMarkdown(join8(target, "tasks"));
10150
11149
  }
10151
11150
  async function hasTaskMarkdown(directory) {
10152
11151
  let names;
10153
11152
  try {
10154
- names = await readdir4(directory);
11153
+ names = await readdir5(directory);
10155
11154
  } catch (error) {
10156
- if (isMissingFile5(error)) return false;
11155
+ if (isMissingFile7(error)) return false;
10157
11156
  throw error;
10158
11157
  }
10159
11158
  return names.some((name) => name.toLowerCase().endsWith(".md"));
@@ -10209,18 +11208,18 @@ async function readStdin() {
10209
11208
  for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
10210
11209
  return Buffer.concat(chunks).toString("utf8");
10211
11210
  }
10212
- function envFirst(primary, legacy) {
11211
+ function envFirst2(primary, legacy) {
10213
11212
  const value = process.env[primary]?.trim();
10214
11213
  if (value !== void 0 && value.length > 0) return value;
10215
11214
  const fallback = process.env[legacy]?.trim();
10216
11215
  return fallback !== void 0 && fallback.length > 0 ? fallback : void 0;
10217
11216
  }
10218
- function isMissingFile5(error) {
11217
+ function isMissingFile7(error) {
10219
11218
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
10220
11219
  }
10221
11220
 
10222
11221
  // src/index.ts
10223
- var VERSION = "0.2.4";
11222
+ var VERSION = "0.2.6";
10224
11223
  var USAGE = `jioogen \u2014 CLI JiooGen (task selection lokal, server read-only)
10225
11224
 
10226
11225
  Usage:
@@ -10237,6 +11236,9 @@ Usage:
10237
11236
  jioogen skills update [--dir <dir>]
10238
11237
  jioogen skills remove <baseline|ui-quality|backend-rules> [--dir <dir>]
10239
11238
  jioogen check [--dir <dir>] [--json]
11239
+ jioogen doctor [--fix] [--dir <dir>] [--json]
11240
+ jioogen resume [--dir <dir>] [--json]
11241
+ jioogen review (--approve | --request-changes <teks> | --stop) [--ref <TASK-XXX>] [--json]
10240
11242
  jioogen handoff [--project <id>] [--json]
10241
11243
  jioogen task next [--json]
10242
11244
  jioogen task start <ref>
@@ -10277,6 +11279,11 @@ async function main() {
10277
11279
  "no-skills": { type: "boolean" },
10278
11280
  files: { type: "string" },
10279
11281
  note: { type: "string" },
11282
+ fix: { type: "boolean" },
11283
+ approve: { type: "boolean" },
11284
+ stop: { type: "boolean" },
11285
+ "request-changes": { type: "string" },
11286
+ ref: { type: "string" },
10280
11287
  json: { type: "boolean" },
10281
11288
  help: { type: "boolean", short: "h" },
10282
11289
  version: { type: "boolean", short: "v" }
@@ -10304,6 +11311,11 @@ async function main() {
10304
11311
  noSkills: flag(raw["no-skills"]),
10305
11312
  files: text(raw.files),
10306
11313
  note: text(raw.note),
11314
+ fix: flag(raw.fix),
11315
+ approve: flag(raw.approve),
11316
+ stop: flag(raw.stop),
11317
+ requestChanges: text(raw["request-changes"]),
11318
+ ref: text(raw.ref),
10307
11319
  json: flag(raw.json)
10308
11320
  };
10309
11321
  if (flag(raw.version)) {
@@ -10366,6 +11378,15 @@ async function dispatch(command, rest, options) {
10366
11378
  case "check":
10367
11379
  await checkCommand(options);
10368
11380
  return;
11381
+ case "doctor":
11382
+ await doctorCommand(options);
11383
+ return;
11384
+ case "resume":
11385
+ await resumeCommand(options);
11386
+ return;
11387
+ case "review":
11388
+ await reviewCommand(options);
11389
+ return;
10369
11390
  case "handoff":
10370
11391
  await handoffCommand(options);
10371
11392
  return;