jioogen 0.2.10 → 0.2.12

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 stat6;
366
+ var stat8;
367
367
  try {
368
- stat6 = self.fs.statSync(resolvedPath);
368
+ stat8 = 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 (stat6 && stat6.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
376
+ if (stat8 && stat8.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 stat6 = self.fs.statSync(path);
386
- if (stat6.isDirectory()) {
385
+ var stat8 = self.fs.statSync(path);
386
+ if (stat8.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, stat6) {
420
- if (exist && stat6 && stat6.isDirectory()) {
419
+ self.fs.stat(path, function(err, stat8) {
420
+ if (exist && stat8 && stat8.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 stat6;
472
+ let stat8;
473
473
  try {
474
- stat6 = self.fs.lstatSync(cur);
474
+ stat8 = self.fs.lstatSync(cur);
475
475
  } catch (e) {
476
476
  break;
477
477
  }
478
- if (stat6.isSymbolicLink()) throw Errors.FILE_IN_THE_WAY(`"${cur}"`);
478
+ if (stat8.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 stat6 = self.fs.statSync(path2);
505
+ const stat8 = self.fs.statSync(path2);
506
506
  if (!pattern || pattern.test(path2)) {
507
- files.push(pth.normalize(path2) + (stat6.isDirectory() ? self.sep : ""));
507
+ files.push(pth.normalize(path2) + (stat8.isDirectory() ? self.sep : ""));
508
508
  }
509
- if (stat6.isDirectory() && recursive) {
509
+ if (stat8.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, stat6) {
556
+ self.fs.stat(file, function(err3, stat8) {
557
557
  if (err3) return done(err3);
558
- if (!stat6) {
558
+ if (!stat8) {
559
559
  if (!--pending) done();
560
560
  return;
561
561
  }
562
- results.push(pth.normalize(file) + (stat6.isDirectory() ? self.sep : ""));
563
- if (!stat6.isDirectory()) {
562
+ results.push(pth.normalize(file) + (stat8.isDirectory() ? self.sep : ""));
563
+ if (!stat8.isDirectory()) {
564
564
  if (!--pending) done();
565
565
  return;
566
566
  }
@@ -9426,6 +9426,193 @@ ${specText}`, id.toLowerCase(), [], LEDGER_ESCAPE);
9426
9426
  );
9427
9427
  }
9428
9428
  }
9429
+ const functionalSpec = specs.find((file) => /functional/i.test(file.path));
9430
+ const functionalText = functionalSpec?.content ?? "";
9431
+ const permTableMatch = functionalText.match(
9432
+ /\|[^\n]*Resource[^\n]*\|[^\n]*Action[^\n]*\|[^\n]*Role[^\n]*\|[\s\S]*?(?=\n\n|\n#{1,3}\s|$)/i
9433
+ );
9434
+ const permRows = [];
9435
+ if (permTableMatch) {
9436
+ const lines = permTableMatch[0].split(/\r?\n/).map((l) => l.trim()).filter((l) => l.startsWith("|"));
9437
+ lines.shift();
9438
+ for (const line of lines) {
9439
+ if (/^\|:?-{2,}/.test(line)) continue;
9440
+ const cells = line.replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
9441
+ if (cells.every((c) => c.length === 0)) continue;
9442
+ permRows.push(cells);
9443
+ }
9444
+ }
9445
+ if (privilegedActors.length > 0 && permRows.length === 0) {
9446
+ issues.push(
9447
+ issue(
9448
+ "PRIVILEGED_ACTOR_WITHOUT_PERMISSION",
9449
+ "conformance",
9450
+ "specs/functional.md",
9451
+ `Aktor pengelola terdeteksi (${privilegedActors.slice(0, 3).join(", ")}) tetapi tidak ada permission matrix (Resource/Action/Role/Scope/Workflow/AC).`,
9452
+ "specs"
9453
+ )
9454
+ );
9455
+ }
9456
+ let incompleteRows = 0;
9457
+ for (const row of permRows) {
9458
+ const filled = row.filter((c) => c.length > 0 && !/^:?-{2,}:?$/.test(c));
9459
+ if (filled.length < 6) incompleteRows += 1;
9460
+ }
9461
+ if (incompleteRows > 0) {
9462
+ issues.push(
9463
+ issue(
9464
+ "PERMISSION_ROW_INCOMPLETE",
9465
+ "conformance",
9466
+ "specs/functional.md",
9467
+ `${incompleteRows} baris permission matrix tidak lengkap (butuh Resource/Action/Role/Scope/Workflow/AC).`,
9468
+ "specs"
9469
+ )
9470
+ );
9471
+ }
9472
+ if (permRows.length > 0 && privilegedActors.length > 0) {
9473
+ const roleCells = permRows.map((r) => (r[2] ?? "").toLowerCase()).join(" ");
9474
+ const missingActor = privilegedActors.filter(
9475
+ (actor) => !roleCells.includes(actor.toLowerCase().split(" ")[0] ?? "")
9476
+ );
9477
+ if (missingActor.length > 0) {
9478
+ issues.push(
9479
+ issue(
9480
+ "PRIVILEGED_ACTOR_WITHOUT_PERMISSION",
9481
+ "conformance",
9482
+ "specs/functional.md",
9483
+ `Aktor pengelola tidak muncul di kolom Role permission matrix: ${missingActor.slice(0, 5).join(", ")}.`,
9484
+ "specs"
9485
+ )
9486
+ );
9487
+ }
9488
+ }
9489
+ const taskAcceptanceText = tasks.map((t) => `${t.content}
9490
+ ${taskTargets(t)}`).join("\n");
9491
+ const taskFlowRefs = `${tasks.map((t) => taskLayer(t)).join(" ")} ${taskAcceptanceText}`;
9492
+ let permWithoutTask = 0;
9493
+ let permWithoutWorkflow = 0;
9494
+ for (const row of permRows) {
9495
+ const ac = row[5] ?? "";
9496
+ const acIds = ac.match(/AC-?\d+/gi) ?? [];
9497
+ if (acIds.length > 0) {
9498
+ const covered = acIds.some((id) => taskAcceptanceText.includes(id));
9499
+ if (!covered) permWithoutTask += 1;
9500
+ }
9501
+ const workflow = row[4] ?? "";
9502
+ const flowIds = workflow.match(/FLOW-?\d+/gi) ?? [];
9503
+ if (flowIds.length > 0) {
9504
+ const covered = flowIds.some((id) => taskFlowRefs.includes(id));
9505
+ if (!covered) permWithoutWorkflow += 1;
9506
+ }
9507
+ }
9508
+ if (permWithoutTask > 0) {
9509
+ issues.push(
9510
+ issue(
9511
+ "PERMISSION_WITHOUT_TASK",
9512
+ "conformance",
9513
+ "tasks/",
9514
+ `${permWithoutTask} permission row tidak ditelusuri ke task (AC tidak muncul di tasks).`,
9515
+ "tasks"
9516
+ )
9517
+ );
9518
+ }
9519
+ if (permWithoutWorkflow > 0) {
9520
+ issues.push(
9521
+ issue(
9522
+ "PERMISSION_WITHOUT_WORKFLOW",
9523
+ "conformance",
9524
+ "specs/functional.md",
9525
+ `${permWithoutWorkflow} permission row tidak ditelusuri ke workflow (FLOW ID tidak muncul di tasks/specs).`,
9526
+ "specs"
9527
+ )
9528
+ );
9529
+ }
9530
+ if (permRows.length > 0) {
9531
+ const hasAuthzTest = tasks.some(
9532
+ (t) => /authz|authorization|izin|permission test|akses ditolak|403|forbidden/i.test(
9533
+ `${t.content}
9534
+ ${taskTargets(t)}`
9535
+ )
9536
+ );
9537
+ if (!hasAuthzTest) {
9538
+ issues.push(
9539
+ issue(
9540
+ "AUTHZ_TEST_COVERAGE_MISSING",
9541
+ "advisory",
9542
+ "tasks/",
9543
+ "Permission matrix ada, tetapi tidak ada task yang merujuk pengujian authorization (403/izin).",
9544
+ "tasks"
9545
+ )
9546
+ );
9547
+ }
9548
+ }
9549
+ const prdText = prd ?? "";
9550
+ const subfeatureIds = [...new Set(prdText.match(/SUBFEATURE-\d+/gi) ?? [])].map(
9551
+ (s) => s.toUpperCase()
9552
+ );
9553
+ const taskSubfeatures = (task) => {
9554
+ const ctx = parseTaskContext(task.content, task.path);
9555
+ const declared = ctx.subfeatureIds ?? ctx.subfeatures;
9556
+ if (Array.isArray(declared) && declared.length > 0) {
9557
+ return declared.map((s) => s.toUpperCase());
9558
+ }
9559
+ return subfeatureIds.filter((sf) => new RegExp(sf.replace("-", "\\-"), "i").test(task.content));
9560
+ };
9561
+ const backendImplies = /payment|pembayaran|stock|stok|order|pesanan|auth|login|database|data|mutasi|transaksi/i;
9562
+ for (const sf of subfeatureIds) {
9563
+ const owners = tasks.filter((t) => taskSubfeatures(t).includes(sf));
9564
+ if (owners.length === 0) {
9565
+ issues.push(
9566
+ issue(
9567
+ "FEATURE_TASK_MISSING",
9568
+ "blocker",
9569
+ "tasks/",
9570
+ `Subfeature ${sf} tidak memiliki task yang menelusurinya (subfeatureIds atau content match).`,
9571
+ "tasks"
9572
+ )
9573
+ );
9574
+ continue;
9575
+ }
9576
+ const allMock = owners.every((t) => taskLayer(t) === "frontend_mock");
9577
+ const sfDescMatch = prdText.match(new RegExp(`${sf}[sS]{0,200}`, "i"));
9578
+ const sfDesc = sfDescMatch ? sfDescMatch[0] : sf;
9579
+ if (allMock && backendImplies.test(sfDesc)) {
9580
+ issues.push(
9581
+ issue(
9582
+ "FEATURE_MOCK_ONLY",
9583
+ "advisory",
9584
+ "tasks/",
9585
+ `Subfeature ${sf} hanya memiliki task layer frontend_mock, padahal implikasi backend terdeteksi.`,
9586
+ "tasks"
9587
+ )
9588
+ );
9589
+ }
9590
+ }
9591
+ if (input.runtime !== "client-only") {
9592
+ const dataSpec = specs.find((file) => /data/i.test(file.path));
9593
+ const dataText = dataSpec?.content ?? "";
9594
+ const entityNames = [
9595
+ ...new Set(
9596
+ (dataText.match(/^###\s+(.+)$/gm) ?? []).map((l) => l.replace(/^###\s+/, "").trim())
9597
+ )
9598
+ ];
9599
+ if (entityNames.length > 0) {
9600
+ const hasDbTask = tasks.some(
9601
+ (t) => taskLayer(t) === "database" || taskLayer(t) === "backend_api"
9602
+ );
9603
+ if (!hasDbTask) {
9604
+ issues.push(
9605
+ issue(
9606
+ "DB_REQUIREMENT_COVERAGE_MISSING",
9607
+ "advisory",
9608
+ "tasks/",
9609
+ "specs/data.md mendefinisikan entitas, tetapi tidak ada task dengan layer database.",
9610
+ "tasks"
9611
+ )
9612
+ );
9613
+ }
9614
+ }
9615
+ }
9429
9616
  return {
9430
9617
  ok: issues.every((finding) => finding.severity !== "blocker"),
9431
9618
  issues
@@ -9579,7 +9766,7 @@ Urutan otoritas: keamanan/a11y inti > PRD/specs > file di sini > default generik
9579
9766
  var EXECUTION_SIDECAR_PATH = "tasks/.execution/state.json";
9580
9767
  var EXECUTION_SIDECAR_VERSION = 1;
9581
9768
  var EXECUTION_SIDECAR_VERSION_V2 = 2;
9582
- var HANDOFF_PROMPT_VERSION = 21;
9769
+ var HANDOFF_PROMPT_VERSION = 27;
9583
9770
  var HANDOFF_AGENT_TOKEN_TTL_SECONDS = 30 * 24 * 3600;
9584
9771
  var HandoffPayloadSchema = external_exports.object({
9585
9772
  promptVersion: external_exports.literal(HANDOFF_PROMPT_VERSION),
@@ -9655,7 +9842,12 @@ var ExecutionTaskStateSchema = external_exports.object({
9655
9842
  blockedReason: external_exports.string().optional(),
9656
9843
  reqRefs: external_exports.array(external_exports.string()).optional(),
9657
9844
  acRefs: external_exports.array(external_exports.string()).optional(),
9658
- verification: external_exports.object({ command: external_exports.string().optional(), exitCode: external_exports.number().int().optional() }).optional()
9845
+ verification: external_exports.object({ command: external_exports.string().optional(), exitCode: external_exports.number().int().optional() }).optional(),
9846
+ /** v2 feature-scope roots for the completion rollup (all optional, v1-compat). */
9847
+ featureId: external_exports.string().optional(),
9848
+ subfeatures: external_exports.array(external_exports.string()).optional(),
9849
+ moduleId: external_exports.string().optional(),
9850
+ cap: external_exports.string().optional()
9659
9851
  }).passthrough();
9660
9852
  var TASK_MODES = ["authoring", "seed", "executor"];
9661
9853
  var TaskModeSchema = external_exports.enum(TASK_MODES);
@@ -9696,6 +9888,66 @@ function summarizeExecutionCounts(tasks) {
9696
9888
  }
9697
9889
  return base;
9698
9890
  }
9891
+ function computeCompletion(tasks, definitions) {
9892
+ const defById = new Map(
9893
+ (definitions ?? []).map((definition) => [definition.id.toUpperCase(), definition])
9894
+ );
9895
+ const units = /* @__PURE__ */ new Map();
9896
+ const tally = (key, done) => {
9897
+ if (key === void 0) return;
9898
+ const cleaned = key.trim();
9899
+ if (cleaned.length === 0 || /^N\/A\b/i.test(cleaned)) return;
9900
+ const entry = units.get(cleaned) ?? { done: 0, total: 0 };
9901
+ entry.total += 1;
9902
+ if (done) entry.done += 1;
9903
+ units.set(cleaned, entry);
9904
+ };
9905
+ const tallyDefinition = (definition, done) => {
9906
+ tally(definition.featureId, done);
9907
+ tally(definition.moduleId, done);
9908
+ for (const subfeature of definition.subfeatures ?? []) tally(subfeature, done);
9909
+ };
9910
+ let tasksDone = 0;
9911
+ const seenIds = /* @__PURE__ */ new Set();
9912
+ const doneRefs = /* @__PURE__ */ new Set();
9913
+ for (const task of tasks) {
9914
+ const done = task.status === "done";
9915
+ if (done) {
9916
+ tasksDone += 1;
9917
+ doneRefs.add(task.ref.toUpperCase());
9918
+ }
9919
+ seenIds.add(task.ref.toUpperCase());
9920
+ const definition = defById.get(task.ref.toUpperCase());
9921
+ tally(definition?.featureId ?? task.featureId, done);
9922
+ tally(definition?.moduleId ?? task.moduleId, done);
9923
+ const subfeatures = definition?.subfeatures ?? task.subfeatures ?? [];
9924
+ for (const subfeature of subfeatures) tally(subfeature, done);
9925
+ }
9926
+ for (const definition of definitions ?? []) {
9927
+ if (definition !== void 0 && !seenIds.has(definition.id.toUpperCase())) {
9928
+ tallyDefinition(definition, false);
9929
+ }
9930
+ }
9931
+ const features = {};
9932
+ for (const [id, entry] of units) {
9933
+ const status = entry.done === 0 ? "missing" : entry.done < entry.total ? "incomplete" : "complete";
9934
+ features[id] = { status, doneTasks: entry.done, totalTasks: entry.total };
9935
+ }
9936
+ const allTasksDone = tasks.every((task) => task.status === "done");
9937
+ const unitIds = Object.keys(features);
9938
+ const allUnitsComplete = unitIds.length > 0 && unitIds.every((id) => features[id]?.status === "complete");
9939
+ let allIntegrationDone = true;
9940
+ for (const task of tasks) {
9941
+ if (task.layer === "integration" && task.status !== "done") allIntegrationDone = false;
9942
+ }
9943
+ for (const definition of definitions ?? []) {
9944
+ if (definition.layer === "integration" && !doneRefs.has(definition.id.toUpperCase())) {
9945
+ allIntegrationDone = false;
9946
+ }
9947
+ }
9948
+ const projectComplete = allTasksDone && allUnitsComplete && allIntegrationDone;
9949
+ return { tasksDone, totalTasks: tasks.length, features, projectComplete };
9950
+ }
9699
9951
 
9700
9952
  // src/api.ts
9701
9953
  var DEFAULT_API_URL = "https://gen.jioo.site";
@@ -9763,6 +10015,8 @@ async function apiLogin(apiUrl, email, password) {
9763
10015
  var ApiClient = class {
9764
10016
  baseUrl;
9765
10017
  cookie;
10018
+ /** Set when the server re-signed a rotated token during a request. */
10019
+ renewedCookie = null;
9766
10020
  constructor(apiUrl, cookie) {
9767
10021
  this.baseUrl = normalizeBaseUrl(apiUrl);
9768
10022
  this.cookie = cookie;
@@ -9793,13 +10047,15 @@ var ApiClient = class {
9793
10047
  }
9794
10048
  const response = await fetch(`${this.baseUrl}${path}`, requestInit);
9795
10049
  if (!response.ok) throw await apiError(response);
10050
+ const renewed = sessionCookieFrom(response);
10051
+ if (renewed !== null) this.renewedCookie = renewed;
9796
10052
  return response;
9797
10053
  }
9798
10054
  };
9799
10055
 
9800
10056
  // src/commands.ts
9801
10057
  import { spawn } from "node:child_process";
9802
- import { mkdir as mkdir8, readdir as readdir7, readFile as readFile10, writeFile as writeFile8 } from "node:fs/promises";
10058
+ import { mkdir as mkdir8, readdir as readdir7, readFile as readFile10, stat as stat7, writeFile as writeFile8 } from "node:fs/promises";
9803
10059
  import { join as join10, resolve as resolve6 } from "node:path";
9804
10060
 
9805
10061
  // src/authoring.ts
@@ -10118,6 +10374,12 @@ function formatBundleCheck(check) {
10118
10374
  import { chmod, mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
10119
10375
  import { homedir } from "node:os";
10120
10376
  import { dirname as dirname2, join as join3, resolve as resolve2 } from "node:path";
10377
+
10378
+ // src/types.ts
10379
+ var UI_QUALITY_MODES = ["auto", "on", "off"];
10380
+
10381
+ // src/config.ts
10382
+ var DEFAULT_UI_QUALITY = "auto";
10121
10383
  var CONFIG_DIR_ENV = "JIOOGEN_CONFIG_DIR";
10122
10384
  var LEGACY_CONFIG_DIR_ENV = "JIOOCODE_CONFIG_DIR";
10123
10385
  var CREDENTIALS_FILE = "credentials.json";
@@ -10209,7 +10471,46 @@ function parseProjectLink(value, bundleDir) {
10209
10471
  const { projectId, apiUrl } = value;
10210
10472
  if (typeof projectId !== "string" || projectId.length === 0) return null;
10211
10473
  if (typeof apiUrl !== "string" || apiUrl.length === 0) return null;
10212
- return { projectId, apiUrl, bundleDir, taskMode: parseTaskMode(value.taskMode) };
10474
+ const execution = isRecord(value.execution) ? value.execution : {};
10475
+ return {
10476
+ projectId,
10477
+ apiUrl,
10478
+ bundleDir,
10479
+ taskMode: parseTaskMode(value.taskMode),
10480
+ execution: {
10481
+ // Legacy links may store the flag at the top level; prefer the nested form.
10482
+ uiQuality: parseUiQuality(execution.uiQuality ?? value.uiQuality),
10483
+ autoMode: parseAutoMode(execution.autoMode ?? value.autoMode)
10484
+ }
10485
+ };
10486
+ }
10487
+ function parseUiQuality(value) {
10488
+ if (value === void 0) return DEFAULT_UI_QUALITY;
10489
+ if (typeof value === "string" && UI_QUALITY_MODES.includes(value)) {
10490
+ return value;
10491
+ }
10492
+ throw new Error(`Project link execution.uiQuality tidak valid: ${String(value)}`);
10493
+ }
10494
+ function parseAutoMode(value) {
10495
+ if (value === void 0 || value === null) return false;
10496
+ if (typeof value === "boolean") return value;
10497
+ if (value === "true" || value === "1" || value === "yes") return true;
10498
+ if (value === "false" || value === "0" || value === "no") return false;
10499
+ throw new Error(`Project link execution.autoMode tidak valid: ${String(value)}`);
10500
+ }
10501
+ async function readAutoMode(bundleDir) {
10502
+ const link = await readProjectLink(resolve2(bundleDir));
10503
+ return link?.execution.autoMode ?? false;
10504
+ }
10505
+ async function writeAutoMode(bundleDir, enabled) {
10506
+ const link = await readProjectLink(resolve2(bundleDir));
10507
+ if (link === null) throw new Error("Belum ada project link. Jalankan `jioogen link` dulu.");
10508
+ await writeProjectLink(resolve2(bundleDir), {
10509
+ projectId: link.projectId,
10510
+ apiUrl: link.apiUrl,
10511
+ taskMode: link.taskMode,
10512
+ execution: { uiQuality: link.execution.uiQuality, autoMode: enabled }
10513
+ });
10213
10514
  }
10214
10515
  function parseTaskMode(value) {
10215
10516
  if (value === void 0) return DEFAULT_TASK_MODE;
@@ -10260,7 +10561,11 @@ async function writeProjectLink(bundleDir, link) {
10260
10561
  {
10261
10562
  projectId: link.projectId,
10262
10563
  apiUrl: link.apiUrl,
10263
- taskMode: link.taskMode ?? DEFAULT_TASK_MODE
10564
+ taskMode: link.taskMode ?? DEFAULT_TASK_MODE,
10565
+ execution: {
10566
+ uiQuality: link.execution?.uiQuality ?? DEFAULT_UI_QUALITY,
10567
+ autoMode: link.execution?.autoMode ?? false
10568
+ }
10264
10569
  },
10265
10570
  null,
10266
10571
  2
@@ -10269,6 +10574,23 @@ async function writeProjectLink(bundleDir, link) {
10269
10574
  "utf8"
10270
10575
  );
10271
10576
  }
10577
+ async function removeProjectLink(bundleDir) {
10578
+ let removedKey = false;
10579
+ for (const directoryName of [PROJECT_DIR, LEGACY_PROJECT_DIR]) {
10580
+ const candidate = join3(resolve2(bundleDir), directoryName, PROJECT_FILE);
10581
+ try {
10582
+ await rm2(candidate);
10583
+ removedKey = true;
10584
+ } catch (error) {
10585
+ if (!isMissingFile(error)) throw error;
10586
+ }
10587
+ }
10588
+ return removedKey;
10589
+ }
10590
+ async function readUiQuality(bundleDir) {
10591
+ const link = await readProjectLink(resolve2(bundleDir));
10592
+ return link?.execution.uiQuality ?? DEFAULT_UI_QUALITY;
10593
+ }
10272
10594
  async function readTaskMode(bundleDir) {
10273
10595
  const link = await readProjectLink(resolve2(bundleDir));
10274
10596
  return link?.taskMode ?? DEFAULT_TASK_MODE;
@@ -10278,992 +10600,1230 @@ function isMissingFile(error) {
10278
10600
  }
10279
10601
 
10280
10602
  // src/doctor.ts
10281
- import { readdir as readdir6, readFile as readFile8, rm as rm6, stat as stat4 } from "node:fs/promises";
10603
+ import { readdir as readdir6, readFile as readFile8, rm as rm6, stat as stat5 } from "node:fs/promises";
10282
10604
  import { join as join8 } from "node:path";
10283
10605
 
10284
10606
  // src/drift.ts
10285
10607
  import { createHash } from "node:crypto";
10286
- import { mkdir as mkdir3, readdir as readdir4, readFile as readFile5, rm as rm3, stat, writeFile as writeFile3 } from "node:fs/promises";
10287
- import { dirname as dirname3, isAbsolute, join as join5 } from "node:path";
10608
+ import { mkdir as mkdir4, readdir as readdir4, readFile as readFile6, rm as rm4, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
10609
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6 } from "node:path";
10288
10610
 
10289
10611
  // src/tasks.ts
10290
- import { readdir as readdir3, readFile as readFile4 } from "node:fs/promises";
10291
- import { join as join4 } from "node:path";
10292
- var TASK_ID_RE2 = /\b(?:TASK|T)-\d{3,}\b/i;
10293
- var HEADING_RE = /^#{1,4}\s+(.+)$/m;
10294
- var LAYER_RANK = {
10295
- frontend_mock: 0,
10296
- database: 1,
10297
- backend_api: 2,
10298
- integration: 3,
10299
- verification: 4
10300
- };
10301
- var IN_PROGRESS = ["in_progress", "verifying"];
10302
- var QUALITY_HEADING = "## KUALITAS WAJIB (ringkas; detail di skill bila tersedia)";
10303
- var BREAKDOWN_HEADING = "## BREAKDOWN WAJIB \u2014 SEBELUM CODING";
10304
- var MAX_CHECKLIST_LINES = 12;
10305
- var BREAKDOWN_RULES = [
10306
- "Breakdown ini mengikat: tulis/centang setiap item sebelum mulai edit, dan jangan `task complete` selama ada item tanpa bukti.",
10307
- "Ini checklist kerja, bukan task baru; task baru hanya diizinkan pada `--mode seed`.",
10308
- "Pratinjau ulang: `npx jioogen task expand <ref>`."
10309
- ];
10310
- var UI_SKILLS = ["ui-ux-pro-max", "impeccable"];
10311
- var LAYER_CHECKLISTS = {
10312
- frontend_mock: [
10313
- "- Reuse token desain yang ada; jangan hardcode warna/spacing bila token tersedia.",
10314
- "- Tangani semua state UI: loading, empty, error, success.",
10315
- "- Responsive untuk mobile dan desktop.",
10316
- "- Aksesibilitas dasar: label, aria, focus, keyboard.",
10317
- "- Microcopy jelas dan konsisten dengan konteks.",
10318
- "- Tanpa komponen/abstraksi baru untuk satu pemakaian; reuse yang ada."
10319
- ],
10320
- database: [
10321
- "- Migrasi eksplisit dan aman (reversible, tanpa mengubah migrasi lama).",
10322
- "- Constraint dan index sesuai pola query.",
10323
- "- Relasi dan isolation sesuai specs (tenant/owner).",
10324
- "- Seed idempotent (bisa dijalankan ulang tanpa duplikasi).",
10325
- "- Tanpa query lintas pemilik.",
10326
- "- Tanpa tabel/kolom spekulatif; hanya yang dipakai requirement."
10327
- ],
10328
- backend_api: [
10329
- "- Validasi input di boundary.",
10330
- "- Error contract konsisten (status + bentuk response).",
10331
- "- Auth/permission dicek sebelum mutasi.",
10332
- "- Idempotensi untuk operasi tulis/retry.",
10333
- "- Logging tanpa secret/PII.",
10334
- "- Tanpa helper/duplikasi untuk satu pemakaian; ekstrak hanya bila berulang."
10335
- ],
10336
- integration: [
10337
- "- Mock dihapus dari jalur utama.",
10338
- "- Kontrak CONTRACT-XXX sama dengan implementasi.",
10339
- "- E2E memakai data nyata.",
10340
- "- Error path diuji.",
10341
- "- Tanpa layer/abstraksi tambahan; hubungkan langsung ke kontrak."
10342
- ],
10343
- verification: [
10344
- "- Jalankan semua verificationCommand sampai exit 0.",
10345
- "- Smoke route/navigasi utama.",
10346
- "- UI states dan responsive dicek.",
10347
- "- Bukti Acceptance Criteria \xA711.",
10348
- "- Jangan menambah kode produksi baru hanya untuk verifikasi."
10349
- ]
10350
- };
10351
- async function loadTasks(bundleDir) {
10352
- const tasksDir = join4(bundleDir, "tasks");
10353
- let entries;
10354
- try {
10355
- entries = await readdir3(tasksDir, { withFileTypes: true });
10356
- } catch (error) {
10357
- if (isMissingFile2(error)) throw new Error(`Direktori tasks/ tidak ditemukan di ${bundleDir}`);
10358
- throw error;
10359
- }
10360
- const names = entries.filter(
10361
- (entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md") && entry.name.toUpperCase() !== "TASKS.MD"
10362
- ).map((entry) => entry.name).sort();
10363
- const tasks = [];
10364
- if (names.length > 0) {
10365
- for (const name of names) {
10366
- const content = await readFile4(join4(tasksDir, name), "utf8");
10367
- tasks.push(parseSingleTask(name, content));
10368
- }
10369
- } else {
10370
- const singlePath = join4(tasksDir, "TASKS.md");
10371
- let content;
10612
+ import { readdirSync, readFileSync } from "node:fs";
10613
+ import { readdir as readdir3, readFile as readFile5, stat as stat2 } from "node:fs/promises";
10614
+ import { isAbsolute, join as join5 } from "node:path";
10615
+
10616
+ // src/sidecar.ts
10617
+ import { randomUUID } from "node:crypto";
10618
+ import { mkdir as mkdir3, open, readFile as readFile4, rename, rm as rm3, stat, writeFile as writeFile3 } from "node:fs/promises";
10619
+ import { dirname as dirname3, join as join4 } from "node:path";
10620
+ var LOCK_RETRY_MS = 25;
10621
+ var LOCK_TIMEOUT_MS = 3e3;
10622
+ var LOCK_STALE_MS = 1e4;
10623
+ function sidecarPath(bundleDir) {
10624
+ return join4(bundleDir, EXECUTION_SIDECAR_PATH);
10625
+ }
10626
+ function lockPath(bundleDir) {
10627
+ return `${sidecarPath(bundleDir)}.lock`;
10628
+ }
10629
+ async function withStateLock(bundleDir, fn) {
10630
+ const target = lockPath(bundleDir);
10631
+ await mkdir3(dirname3(target), { recursive: true });
10632
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
10633
+ let handle = null;
10634
+ let staleRemoved = false;
10635
+ while (handle === null) {
10372
10636
  try {
10373
- content = await readFile4(singlePath, "utf8");
10637
+ handle = await open(target, "wx");
10374
10638
  } catch (error) {
10375
- if (isMissingFile2(error)) throw new Error(`Tidak ada berkas task di ${tasksDir}`);
10376
- throw error;
10639
+ if (!isLockBusy(error)) throw error;
10640
+ if (!staleRemoved && await removeStaleLock(target)) {
10641
+ staleRemoved = true;
10642
+ continue;
10643
+ }
10644
+ if (Date.now() >= deadline) {
10645
+ throw new Error(
10646
+ `Gagal mengambil lock sidecar setelah ${LOCK_TIMEOUT_MS / 1e3} detik: ${target}. Kemungkinan proses lain masih menulis; hapus file lock itu bila proses tersebut sudah mati.`
10647
+ );
10648
+ }
10649
+ await delay(LOCK_RETRY_MS);
10377
10650
  }
10378
- tasks.push(...parseSingleFile(content));
10379
10651
  }
10380
- if (tasks.length === 0) throw new Error(`Tidak ada task yang bisa dibaca di ${tasksDir}`);
10381
- assertUniqueIds(tasks);
10382
- return tasks;
10383
- }
10384
- function parseSingleTask(file, content) {
10385
- const heading = firstHeading(content);
10386
- const explicit = TASK_ID_RE2.exec(file)?.[0] ?? explicitIdFromContent(content);
10387
- const id = explicit ?? file.replace(/\.md$/i, "");
10388
- if (id.length === 0) {
10389
- throw new Error(`Berkas task tanpa ID: ${file}`);
10652
+ try {
10653
+ await handle.writeFile(`${process.pid}
10654
+ `, "utf8");
10655
+ return await fn();
10656
+ } finally {
10657
+ await handle.close().catch(() => {
10658
+ });
10659
+ await rm3(target, { force: true }).catch(() => {
10660
+ });
10390
10661
  }
10391
- return buildTask(id, heading, file, content);
10392
- }
10393
- function explicitIdFromContent(content) {
10394
- const heading = firstHeading(content);
10395
- const fromHeading = heading !== null ? TASK_ID_RE2.exec(heading)?.[0] : void 0;
10396
- if (fromHeading !== void 0) return fromHeading;
10397
- return /(?:\*\*)?ID(?:\*\*)?\s*[:=]\s*`?((?:TASK|T)-\d{3,})/i.exec(content)?.[1];
10398
10662
  }
10399
- function parseSingleFile(content) {
10400
- const blocks = content.split(/\n(?=#{1,4}\s+(?:TASK|T)-\d{3,}\b)/i);
10401
- const tasks = [];
10402
- for (const block of blocks) {
10403
- const heading = firstHeading(block);
10404
- const id = heading !== null ? TASK_ID_RE2.exec(heading)?.[0] : void 0;
10405
- if (id === void 0) continue;
10406
- tasks.push(buildTask(id, heading, "TASKS.md", block));
10663
+ async function readState(bundleDir) {
10664
+ let raw;
10665
+ try {
10666
+ raw = await readFile4(sidecarPath(bundleDir), "utf8");
10667
+ } catch (error) {
10668
+ if (isMissingFile2(error)) return null;
10669
+ throw error;
10407
10670
  }
10408
- return tasks;
10409
- }
10410
- function buildTask(id, heading, file, content) {
10411
- const context = parseTaskContext(content, id);
10412
- const layer = resolveLayer(context.layer);
10413
- if (context.layer !== void 0 && layer === void 0) {
10414
- throw new Error(`Task ${context.taskId} punya layer tidak dikenal: ${context.layer.trim()}`);
10671
+ let payload;
10672
+ try {
10673
+ payload = JSON.parse(raw);
10674
+ } catch {
10675
+ throw new Error(`Sidecar bukan JSON yang valid: ${sidecarPath(bundleDir)}`);
10415
10676
  }
10416
- return {
10417
- // Prefer the declared `id:` so `T-001-x.md` + `dependsOn: [TASK-001]` agree.
10418
- id: context.taskId,
10419
- title: titleFromGoal(content) ?? titleFromHeading(heading) ?? context.taskId,
10420
- file,
10421
- content: content.trim(),
10422
- layer,
10423
- phase: context.phase ?? 1,
10424
- checkpoint: context.checkpoint === true,
10425
- dependsOn: context.dependsOn
10426
- };
10427
- }
10428
- function renderActiveTask(task, context) {
10429
- const lines = [
10430
- "## TASK AKTIF \u2014 PRIORITASKAN INI (satu task per giliran)",
10431
- `ref: ${task.id}`,
10432
- `title: ${task.title}`,
10433
- `layer: ${task.layer ?? "-"} | phase: ${task.phase} | checkpoint: ${task.checkpoint}`,
10434
- `file: tasks/${task.file}`
10435
- ];
10436
- if (task.dependsOn.length > 0) lines.push(`dependsOn: ${task.dependsOn.join(", ")}`);
10437
- lines.push(
10438
- "",
10439
- "Aturan mengikat:",
10440
- "- Kerjakan HANYA task ini sampai semua Acceptance Criteria terpenuhi dan verificationCommand exit 0.",
10441
- "- Jangan pindah task, jangan mengerjakan task lain, jangan melebar ke file di luar targetFiles (file/direktori/glob).",
10442
- "- Jangan mengarang fitur/endpoint/kolom di luar PRD.md/specs/.",
10443
- "- Detail implementasi (pola, struktur file dalam scope, library yang sudah ada) milikmu; ikuti konvensi proyek.",
10444
- "- Jangan mengubah PRD.md/specs/kontrak. Butuh perubahan kontrak? STOP dan laporkan.",
10445
- "- Selesai: `npx jioogen task complete <ref>`, lalu `npx jioogen sync`."
10446
- );
10447
- const checklist = renderQualityChecklist(task.layer, context);
10448
- if (checklist.length > 0) lines.push("", ...checklist);
10449
- const breakdown = buildTaskBreakdown(task);
10450
- const breakdownLines = [...breakdown.authored, ...breakdown.derived];
10451
- if (breakdownLines.length > 0) {
10452
- lines.push("", BREAKDOWN_HEADING, ...BREAKDOWN_RULES);
10453
- for (const item of breakdownLines) lines.push(`- [ ] ${item}`);
10677
+ const parsed = ExecutionStateSchema.safeParse(payload);
10678
+ if (!parsed.success) {
10679
+ throw new Error(
10680
+ `Sidecar tidak cocok dengan schema v${EXECUTION_SIDECAR_VERSION}: ${sidecarPath(bundleDir)}`
10681
+ );
10454
10682
  }
10455
- lines.push("", "--- ISI TASK (otoritas scope) ---", task.content, "--- AKHIR ISI TASK ---");
10456
- return lines.join("\n");
10683
+ return parsed.data;
10457
10684
  }
10458
- function buildTaskBreakdown(task) {
10459
- const context = parseTaskContext(task.content, task.id);
10460
- const authored = (context.subtasks ?? []).filter((item) => !/^N\/A\b/i.test(item));
10461
- const derived = [];
10462
- const seen = /* @__PURE__ */ new Set();
10463
- const push = (item) => {
10464
- const key = item.trim().toLowerCase();
10465
- if (key.length === 0 || seen.has(key)) return;
10466
- seen.add(key);
10467
- derived.push(item);
10685
+ function createState(projectId, definitions, now = /* @__PURE__ */ new Date(), mode = DEFAULT_TASK_MODE) {
10686
+ const tasks = definitions.map(toTaskState);
10687
+ return {
10688
+ schemaVersion: EXECUTION_SIDECAR_VERSION,
10689
+ projectId,
10690
+ updatedAt: now.toISOString(),
10691
+ executor: { engine: "jioogen" },
10692
+ mode,
10693
+ counts: summarizeExecutionCounts(tasks),
10694
+ tasks
10468
10695
  };
10469
- for (const subfeature of context.subfeatures ?? []) {
10470
- push(`${subfeature} \u2014 petakan ke AC, flow/state, dan targetFiles`);
10471
- }
10472
- for (const acceptance of context.acceptance ?? []) {
10473
- if (/^N\/A\b/i.test(acceptance)) continue;
10474
- push(`${acceptance} \u2014 penuhi + catat bukti`);
10475
- }
10476
- for (const flow of context.flowRef ?? []) {
10477
- push(`${flow} \u2014 implement alur sampai outcome`);
10478
- }
10479
- for (const lifecycle of context.lifecycleRefs ?? []) {
10480
- push(`Lifecycle ${lifecycle} \u2014 state/transition yang relevan`);
10481
- }
10482
- for (const engine of context.engineRef ?? []) {
10483
- push(`Engine ${engine} \u2014 invariant/keputusan yang dijaga`);
10484
- }
10485
- for (const state of context.uiStates ?? []) {
10486
- push(`UI state ${state} \u2014 render + verifikasi`);
10487
- }
10488
- for (const isolation of context.isolationRefs ?? []) {
10489
- push(`${isolation} \u2014 tegakkan boundary + AC penolakan akses`);
10490
- }
10491
- for (const file of context.targetFiles ?? []) {
10492
- push(`File ${file} \u2014 buat/edit + test terkait`);
10493
- }
10494
- if (context.verificationCommand !== null && context.verificationCommand !== void 0) {
10495
- push(`Verifikasi: \`${context.verificationCommand}\` (wajib exit 0)`);
10496
- }
10497
- if (authored.length === 0 && derived.length === 0) {
10498
- push("Baca task + PRD/specs, lalu tulis langkah kerja eksplisit sebelum edit");
10499
- }
10500
- return { authored, derived };
10501
10696
  }
10502
- function renderQualityChecklist(layer, context) {
10503
- if (context === void 0 || layer === void 0) return [];
10504
- const items = [...LAYER_CHECKLISTS[layer] ?? []];
10505
- if (layer === "frontend_mock") {
10506
- const references = UI_SKILLS.filter((skill) => context.skills?.includes(skill) === true);
10507
- if (references.length > 0) items.push(`- Referensi skill: ${references.join(", ")}`);
10508
- }
10509
- if (items.length === 0) return [];
10510
- return [QUALITY_HEADING, ...items.slice(0, MAX_CHECKLIST_LINES)];
10697
+ function withMode(state, mode) {
10698
+ if (state.mode === mode) return state;
10699
+ return { ...state, mode };
10511
10700
  }
10512
- function resolveLayer(value) {
10513
- if (value === void 0) return void 0;
10514
- const token = value.trim().replace(/[`*]/g, "").split(/[\s,(]/)[0];
10515
- if (token === void 0) return void 0;
10516
- return TASK_LAYERS.includes(token) ? token : void 0;
10701
+ function assertModeAllowsNewTasks(mode, state, definitions) {
10702
+ if (mode !== "executor") return;
10703
+ const known = new Set(state.tasks.map((task) => task.ref.toUpperCase()));
10704
+ const unknown = definitions.filter((definition) => !known.has(definition.id.toUpperCase())).map((definition) => definition.id);
10705
+ if (unknown.length === 0) return;
10706
+ throw new Error(
10707
+ `Mode executor hanya menjalankan task yang sudah ada; task baru (${unknown.join(", ")}) harus lewat authoring JiooGen atau mode seed.`
10708
+ );
10517
10709
  }
10518
- function titleFromGoal(content) {
10519
- const match = /goal\s*\*{0,2}\s*[:=]\s*\*{0,2}\s*([^\n]+)/i.exec(content);
10520
- if (match?.[1] === void 0) return null;
10521
- return stripMarkup(match[1]);
10710
+ function mergeTasks(state, definitions) {
10711
+ const byId = new Map(definitions.map((task) => [task.id.toUpperCase(), task]));
10712
+ const known = new Set(state.tasks.map((task) => task.ref.toUpperCase()));
10713
+ let changed = false;
10714
+ const existing = state.tasks.map((task) => {
10715
+ const definition = byId.get(task.ref.toUpperCase());
10716
+ if (definition === void 0) return task;
10717
+ if (sameMetadata(task, definition)) return task;
10718
+ changed = true;
10719
+ const updated = {
10720
+ ...task,
10721
+ phase: definition.phase,
10722
+ checkpoint: definition.checkpoint
10723
+ };
10724
+ if (definition.layer !== void 0) updated.layer = definition.layer;
10725
+ else delete updated.layer;
10726
+ applyScopedMetadata(updated, taskScopedMetadata(definition));
10727
+ return updated;
10728
+ });
10729
+ const additions = definitions.filter((task) => !known.has(task.id.toUpperCase())).map(toTaskState);
10730
+ if (!changed && additions.length === 0) return state;
10731
+ return rebuild(state, [...existing, ...additions], state.current);
10522
10732
  }
10523
- function firstHeading(content) {
10524
- return HEADING_RE.exec(content)?.[1]?.trim() ?? null;
10733
+ function applyScopedMetadata(task, scope) {
10734
+ if (scope.featureId !== void 0) task.featureId = scope.featureId;
10735
+ else delete task.featureId;
10736
+ if (scope.subfeatures !== void 0) task.subfeatures = scope.subfeatures;
10737
+ else delete task.subfeatures;
10738
+ if (scope.moduleId !== void 0) task.moduleId = scope.moduleId;
10739
+ else delete task.moduleId;
10740
+ if (scope.cap !== void 0) task.cap = scope.cap;
10741
+ else delete task.cap;
10525
10742
  }
10526
- function titleFromHeading(heading) {
10527
- if (heading === null) return null;
10528
- const withoutId = heading.replace(/^(?:TASK|T)-\d{3,}\s*[—–:-]?\s*/i, "").trim();
10529
- return withoutId.length > 0 ? withoutId : heading;
10743
+ function sameMetadata(task, definition) {
10744
+ const scope = taskScopedMetadata(definition);
10745
+ return task.layer === definition.layer && task.phase === definition.phase && task.checkpoint === definition.checkpoint && task.featureId === scope.featureId && sameStringList(task.subfeatures, scope.subfeatures) && task.moduleId === scope.moduleId && task.cap === scope.cap;
10530
10746
  }
10531
- function stripMarkup(text2) {
10532
- return text2.replace(/[`*_]/g, "").replace(/^["'\s]+|["'\s]+$/g, "").trim();
10747
+ function sameStringList(left, right) {
10748
+ if (left === void 0 || right === void 0) return left === right;
10749
+ return left.length === right.length && left.every((entry, index) => entry === right[index]);
10533
10750
  }
10534
- function assertUniqueIds(tasks) {
10535
- const seen = /* @__PURE__ */ new Set();
10536
- for (const task of tasks) {
10537
- const key = task.id.toUpperCase();
10538
- if (seen.has(key)) throw new Error(`ID task duplikat: ${task.id}`);
10539
- seen.add(key);
10751
+ function withStatus(state, ref, status, options = {}) {
10752
+ const now = options.now ?? /* @__PURE__ */ new Date();
10753
+ const index = state.tasks.findIndex((task) => task.ref.toUpperCase() === ref.toUpperCase());
10754
+ const previous = index === -1 ? void 0 : state.tasks[index];
10755
+ if (previous === void 0) {
10756
+ throw new Error(`Task ${ref} tidak ada di sidecar. Jalankan \`jioogen task next\` lebih dulu.`);
10540
10757
  }
10758
+ const attempt = status === "in_progress" ? (previous.attempt ?? 0) + 1 : previous.attempt;
10759
+ const historyEntry = { status, at: now.toISOString() };
10760
+ if (options.note !== void 0 && options.note.length > 0) historyEntry.note = options.note;
10761
+ const updated = {
10762
+ ...previous,
10763
+ status,
10764
+ updatedAt: now.toISOString(),
10765
+ history: [...previous.history ?? [], historyEntry]
10766
+ };
10767
+ if (attempt !== void 0) updated.attempt = attempt;
10768
+ if (options.note !== void 0) {
10769
+ if (options.note.length > 0) updated.note = options.note;
10770
+ else delete updated.note;
10771
+ }
10772
+ const tasks = state.tasks.map((task, taskIndex) => taskIndex === index ? updated : task);
10773
+ const current = status === "in_progress" || status === "verifying" ? {
10774
+ ref: updated.ref,
10775
+ ...updated.layer !== void 0 ? { layer: updated.layer } : {},
10776
+ ...updated.phase !== void 0 ? { phase: updated.phase } : {},
10777
+ awaitingCheckpoint: options.awaitingCheckpoint === true
10778
+ } : void 0;
10779
+ return rebuild(state, tasks, current, now);
10541
10780
  }
10542
- function orderTasks(tasks) {
10543
- return [...tasks].sort(
10544
- (left, right) => left.phase - right.phase || layerRank(left.layer) - layerRank(right.layer) || numericId(left.id) - numericId(right.id) || left.id.localeCompare(right.id)
10545
- );
10546
- }
10547
- function layerRank(layer) {
10548
- return layer === void 0 ? 0 : LAYER_RANK[layer] ?? 0;
10781
+ function setCurrent(state, current) {
10782
+ return rebuild(state, state.tasks, current ?? void 0);
10549
10783
  }
10550
- function numericId(id) {
10551
- const leading = /^(\d+)/.exec(id);
10552
- if (leading?.[1] !== void 0) return Number.parseInt(leading[1], 10);
10553
- const trailing = /(?:^|[-\s])(\d{3,})$/.exec(id);
10554
- return trailing?.[1] !== void 0 ? Number.parseInt(trailing[1], 10) : Number.MAX_SAFE_INTEGER;
10784
+ function appendTaskEvidence(state, ref, evidence) {
10785
+ const index = state.tasks.findIndex((task2) => task2.ref.toUpperCase() === ref.toUpperCase());
10786
+ if (index === -1) return state;
10787
+ const previous = state.tasks[index];
10788
+ if (previous === void 0) return state;
10789
+ const task = {
10790
+ ...previous,
10791
+ evidence: [...previous.evidence ?? [], evidence]
10792
+ };
10793
+ const tasks = state.tasks.map((entry, i) => i === index ? task : entry);
10794
+ return rebuild(state, tasks, state.current);
10555
10795
  }
10556
- function selectNext(tasks, states) {
10557
- const byRef = new Map(states.map((state) => [state.ref.toUpperCase(), state]));
10558
- const ordered = orderTasks(tasks);
10559
- for (const task of ordered) {
10560
- const state = byRef.get(task.id.toUpperCase());
10561
- if (state !== void 0 && IN_PROGRESS.includes(state.status)) {
10562
- return { task, state, reason: "in_progress" };
10563
- }
10564
- }
10565
- for (const task of ordered) {
10566
- const state = byRef.get(task.id.toUpperCase());
10567
- if (state?.status === "done") continue;
10568
- if (hasUnfinishedDependency(task, byRef)) continue;
10569
- const effective = state ?? { ref: task.id, status: "todo" };
10570
- return { task, state: effective, reason: effective.status === "todo" ? "todo" : "retry" };
10571
- }
10572
- return null;
10796
+ function setTaskSource(state, ref, source) {
10797
+ const index = state.tasks.findIndex((task2) => task2.ref.toUpperCase() === ref.toUpperCase());
10798
+ if (index === -1) return state;
10799
+ const previous = state.tasks[index];
10800
+ if (previous === void 0) return state;
10801
+ const task = { ...previous, source };
10802
+ const tasks = state.tasks.map((entry, i) => i === index ? task : entry);
10803
+ return rebuild(state, tasks, state.current);
10573
10804
  }
10574
- function blockedTasks(tasks, states) {
10575
- const byRef = new Map(states.map((state) => [state.ref.toUpperCase(), state]));
10576
- return orderTasks(tasks).filter((task) => byRef.get(task.id.toUpperCase())?.status !== "done").map((task) => ({
10577
- task,
10578
- missing: task.dependsOn.filter(
10579
- (dependency) => byRef.get(dependency.toUpperCase())?.status !== "done"
10580
- )
10581
- })).filter((entry) => entry.missing.length > 0);
10582
- }
10583
- function hasUnfinishedDependency(task, byRef) {
10584
- return task.dependsOn.some(
10585
- (dependency) => byRef.get(dependency.toUpperCase())?.status !== "done"
10586
- );
10587
- }
10588
- function isBoundary(previous, next) {
10589
- if (next.checkpoint) return true;
10590
- if (previous.layer !== void 0 && next.layer !== void 0 && previous.layer !== next.layer) {
10591
- return true;
10592
- }
10593
- return previous.phase !== void 0 && next.phase !== previous.phase;
10594
- }
10595
- var RISKY_TASK_RE = /\b(migrat(?:e|ion|ions)?|migrasi|prisma|schema|rls|auth|permission|payment|checkout|webhook|secret|deploy|drop)\b/i;
10596
- var TARGET_FILES_LABEL_RE2 = /^\s*(?:[-*]\s*)?\*{0,2}targetFiles\*{0,2}\s*:\s*(.*)$/i;
10597
- function isRiskyTask(task) {
10598
- const targetFiles = task.targetFiles ?? targetFilesFromContent(task.content);
10599
- return RISKY_TASK_RE.test([task.id, task.title, ...targetFiles].join("\n"));
10805
+ function setDesignReview(state, ref, review) {
10806
+ const index = state.tasks.findIndex((task2) => task2.ref.toUpperCase() === ref.toUpperCase());
10807
+ if (index === -1) return state;
10808
+ const previous = state.tasks[index];
10809
+ if (previous === void 0) return state;
10810
+ const task = {
10811
+ ...previous,
10812
+ designReview: {
10813
+ passed: review.passed,
10814
+ findings: [...review.findings ?? []],
10815
+ summary: review.summary,
10816
+ at: review.at ?? (/* @__PURE__ */ new Date()).toISOString()
10817
+ },
10818
+ evidence: [
10819
+ ...previous.evidence ?? [],
10820
+ {
10821
+ type: "design_review",
10822
+ summary: `${review.passed ? "PASS" : "FAIL"}${review.summary ? ` \u2014 ${review.summary}` : ""}`,
10823
+ at: review.at ?? (/* @__PURE__ */ new Date()).toISOString()
10824
+ }
10825
+ ]
10826
+ };
10827
+ const tasks = state.tasks.map((entry, i) => i === index ? task : entry);
10828
+ return rebuild(state, tasks, state.current);
10600
10829
  }
10601
- function targetFilesFromContent(content) {
10602
- const lines = content.split(/\r?\n/);
10603
- const index = lines.findIndex((line) => TARGET_FILES_LABEL_RE2.test(line));
10604
- if (index === -1) return [];
10605
- const inline = (lines[index]?.match(TARGET_FILES_LABEL_RE2)?.[1] ?? "").trim();
10606
- if (inline.length > 0) return splitTargetFiles(inline);
10607
- const items = [];
10608
- for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
10609
- const line = lines[cursor] ?? "";
10610
- if (line.trim().length === 0) continue;
10611
- const item = /^\s*-\s+(.+?)\s*$/.exec(line);
10612
- if (item === null) break;
10613
- const cleaned = cleanTargetFile(item[1] ?? "");
10614
- if (cleaned.length > 0) items.push(cleaned);
10830
+ async function writeState(bundleDir, state) {
10831
+ const normalized = rebuild(state, state.tasks, state.current);
10832
+ const target = sidecarPath(bundleDir);
10833
+ await mkdir3(dirname3(target), { recursive: true });
10834
+ const temp = `${target}.${process.pid}.${randomUUID()}.tmp`;
10835
+ try {
10836
+ await writeFile3(temp, `${JSON.stringify(normalized, null, 2)}
10837
+ `, "utf8");
10838
+ await rename(temp, target);
10839
+ } catch (error) {
10840
+ await rm3(temp, { force: true }).catch(() => {
10841
+ });
10842
+ throw error;
10615
10843
  }
10616
- return items;
10617
- }
10618
- function splitTargetFiles(value) {
10619
- return value.replace(/[[\]`]/g, "").split(",").map(cleanTargetFile).filter((part) => part.length > 0 && !/^(?:\(?none\)?|n\/a|-+)$/i.test(part));
10844
+ return normalized;
10620
10845
  }
10621
- function cleanTargetFile(value) {
10622
- return value.replace(/^[-*\s]+/, "").trim();
10846
+ async function backupExecutionState(bundleDir) {
10847
+ const current = await readState(bundleDir);
10848
+ if (current === null) return null;
10849
+ const backupDir = join4(bundleDir, ".jioogen");
10850
+ await mkdir3(backupDir, { recursive: true });
10851
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
10852
+ const backupFile = join4(backupDir, `state.backup-${timestamp}.json`);
10853
+ await writeFile3(backupFile, `${JSON.stringify(current, null, 2)}
10854
+ `, "utf8");
10855
+ return backupFile;
10623
10856
  }
10624
- function verificationCommandFromContent(content) {
10625
- const inline = content.match(
10626
- /^\s*(?:[-*]\s*)?\*{0,2}verificationCommand\*{0,2}\s*:\s*(.+?)\s*$/im
10627
- );
10628
- if (inline?.[1] !== void 0) {
10629
- const value = stripVerificationBackticks(inline[1].trim());
10630
- if (isVerificationPlaceholder(value)) return null;
10631
- if (value.length > 0) return value;
10632
- }
10633
- const lines = content.split(/\r?\n/);
10634
- for (let i = 0; i < lines.length; i += 1) {
10635
- const heading = lines[i]?.trim() ?? "";
10636
- if (!/^#{1,6}\s+Verification(?:\s+Command)?\s*$/i.test(heading)) continue;
10637
- for (let j = i + 1; j < lines.length; j += 1) {
10638
- const next = (lines[j] ?? "").trim();
10639
- if (next.length === 0) continue;
10640
- if (/^#{1,6}\s/.test(next)) break;
10641
- const value = stripVerificationBackticks(next);
10642
- if (isVerificationPlaceholder(value)) return null;
10643
- return value.length > 0 ? value : null;
10644
- }
10645
- }
10646
- return null;
10857
+ function rebuild(state, tasks, current, now = /* @__PURE__ */ new Date()) {
10858
+ const next = {
10859
+ schemaVersion: state.schemaVersion,
10860
+ updatedAt: now.toISOString(),
10861
+ counts: summarizeExecutionCounts(tasks),
10862
+ tasks
10863
+ };
10864
+ if (state.projectId !== void 0) next.projectId = state.projectId;
10865
+ if (state.executor !== void 0) next.executor = state.executor;
10866
+ if (state.mode !== void 0) next.mode = state.mode;
10867
+ if (state.plan !== void 0) next.plan = state.plan;
10868
+ if (state.events !== void 0) next.events = state.events;
10869
+ if (current !== void 0) next.current = current;
10870
+ return next;
10647
10871
  }
10648
- function normalizeVerificationCommand(value) {
10649
- return stripVerificationBackticks(value.trim());
10872
+ function toTaskState(task) {
10873
+ const state = {
10874
+ ref: task.id,
10875
+ status: "todo",
10876
+ ...task.layer !== void 0 ? { layer: task.layer } : {},
10877
+ phase: task.phase,
10878
+ checkpoint: task.checkpoint
10879
+ };
10880
+ applyScopedMetadata(state, taskScopedMetadata(task));
10881
+ return state;
10650
10882
  }
10651
- function stripVerificationBackticks(value) {
10652
- const trimmed = value.replace(/^`+/, "").replace(/`+$/, "").trim();
10653
- if (trimmed.length >= 2) {
10654
- const first = trimmed[0];
10655
- const last = trimmed[trimmed.length - 1];
10656
- if (first === '"' && last === '"' || first === "'" && last === "'") {
10657
- return trimmed.slice(1, -1).trim();
10658
- }
10659
- }
10660
- return trimmed;
10883
+ function taskScopedMetadata(task) {
10884
+ const context = parseTaskContext(task.content, task.id);
10885
+ return {
10886
+ ...context.featureId !== void 0 ? { featureId: context.featureId } : {},
10887
+ ...context.subfeatures !== void 0 && context.subfeatures.length > 0 ? { subfeatures: context.subfeatures } : {},
10888
+ ...context.moduleId !== void 0 ? { moduleId: context.moduleId } : {},
10889
+ ...context.cap !== void 0 ? { cap: context.cap } : {}
10890
+ };
10661
10891
  }
10662
- function isVerificationPlaceholder(value) {
10663
- return /^(?:n\/a|—+|-+|none)$/i.test(value.trim());
10892
+ function completionDefinitions(definitions) {
10893
+ return definitions.map((definition) => ({
10894
+ id: definition.id,
10895
+ ...taskScopedMetadata(definition),
10896
+ ...definition.layer !== void 0 ? { layer: definition.layer } : {}
10897
+ }));
10664
10898
  }
10665
10899
  function isMissingFile2(error) {
10666
10900
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
10667
10901
  }
10668
-
10669
- // src/drift.ts
10670
- var DRIFT_BASELINE_PATH = join5("tasks", ".execution", "baseline.json");
10671
- var BASELINE_VERSION = 1;
10672
- var MAX_TARGET_FILES = 2e3;
10673
- var MAX_BUNDLE_FILE_BYTES = 1048576;
10674
- var IGNORED_DIRS = /* @__PURE__ */ new Set([
10675
- ".git",
10676
- "node_modules",
10677
- ".next",
10678
- "dist",
10679
- "build",
10680
- "coverage",
10681
- ".turbo",
10682
- ".cache",
10683
- ".vercel",
10684
- ".output",
10685
- "out",
10686
- ".expo",
10687
- ".jioogen",
10688
- ".claude",
10689
- ".opencode",
10690
- ".agent",
10691
- ".codex",
10692
- ".cursor"
10693
- ]);
10694
- var IGNORED_TOP_FILES = /* @__PURE__ */ new Set(["AGENTS.md"]);
10695
- function baselinePath(bundleDir) {
10696
- return join5(bundleDir, DRIFT_BASELINE_PATH);
10902
+ function isLockBusy(error) {
10903
+ return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
10697
10904
  }
10698
- async function readBaseline(bundleDir) {
10699
- let raw;
10700
- try {
10701
- raw = await readFile5(baselinePath(bundleDir), "utf8");
10702
- } catch {
10703
- return null;
10704
- }
10705
- let parsed;
10905
+ async function removeStaleLock(target) {
10706
10906
  try {
10707
- parsed = JSON.parse(raw);
10708
- } catch {
10709
- return null;
10710
- }
10711
- if (typeof parsed !== "object" || parsed === null) return null;
10712
- const record = parsed;
10713
- const tasks = record.tasks;
10714
- if (tasks === void 0 || typeof tasks !== "object" || tasks === null) return null;
10715
- const entries = {};
10716
- for (const [ref, value] of Object.entries(tasks)) {
10717
- if (typeof value !== "object" || value === null) continue;
10718
- const entry = value;
10719
- if (typeof entry.target !== "object" || entry.target === null) continue;
10720
- entries[ref] = {
10721
- at: typeof entry.at === "string" ? entry.at : "",
10722
- target: entry.target
10723
- };
10907
+ const info = await stat(target);
10908
+ if (Date.now() - info.mtimeMs < LOCK_STALE_MS) return false;
10909
+ await rm3(target, { force: true });
10910
+ return true;
10911
+ } catch (error) {
10912
+ if (isMissingFile2(error)) return true;
10913
+ throw error;
10724
10914
  }
10725
- return {
10726
- version: typeof record.version === "number" ? record.version : BASELINE_VERSION,
10727
- bundle: typeof record.bundle === "string" ? record.bundle : "",
10728
- tasks: entries
10729
- };
10730
- }
10731
- async function writeBaseline(bundleDir, baseline) {
10732
- const target = baselinePath(bundleDir);
10733
- await mkdir3(dirname3(target), { recursive: true });
10734
- await writeFile3(target, `${JSON.stringify(baseline, null, 2)}
10735
- `, "utf8");
10736
- }
10737
- async function clearBaseline(bundleDir) {
10738
- await rm3(baselinePath(bundleDir), { force: true });
10739
10915
  }
10740
- async function captureTaskBaseline(bundleDir, definition, now = /* @__PURE__ */ new Date()) {
10741
- const baseline = await readBaseline(bundleDir) ?? {
10742
- version: BASELINE_VERSION,
10743
- bundle: await bundleHashOf(bundleDir),
10744
- tasks: {}
10745
- };
10746
- if (baseline.bundle.length === 0) baseline.bundle = await bundleHashOf(bundleDir);
10747
- const target = await targetHashes(bundleDir, targetFilesFromContent(definition.content));
10748
- baseline.tasks[definition.id.toUpperCase()] = {
10749
- at: now.toISOString(),
10750
- target: target.hashes
10751
- };
10752
- await writeBaseline(bundleDir, baseline);
10916
+ function delay(ms) {
10917
+ return new Promise((resolve7) => setTimeout(resolve7, ms));
10753
10918
  }
10754
- async function detectDrift(bundleDir, definitions, state, options = {}) {
10755
- const baseline = await readBaseline(bundleDir);
10756
- const findings = [];
10757
- const focus = options.focusRef?.toUpperCase();
10758
- const byId = new Map(definitions.map((entry) => [entry.id.toUpperCase(), entry]));
10759
- const targetCache = /* @__PURE__ */ new Map();
10760
- const hashesFor = (definition) => {
10761
- const key = targetFilesFromContent(definition.content).join("\0");
10762
- let cached = targetCache.get(key);
10763
- if (cached === void 0) {
10764
- cached = targetHashes(bundleDir, targetFilesFromContent(definition.content));
10765
- targetCache.set(key, cached);
10766
- }
10767
- return cached;
10768
- };
10769
- if (baseline !== null) {
10770
- const currentBundle = await bundleHashOf(bundleDir);
10771
- if (baseline.bundle.length > 0 && currentBundle !== baseline.bundle) {
10772
- findings.push({
10773
- code: "BUNDLE_DRIFT",
10774
- severity: "warn",
10775
- message: "PRD.md/specs/tasks berubah di disk setelah baseline dibuat. Revisi resmi lewat workspace web (agar specs/tasks ditandai stale), atau kembalikan file itu; jangan diedit lokal diam-diam.",
10776
- files: []
10777
- });
10778
- }
10779
- for (const task of state.tasks) {
10780
- const definition = byId.get(task.ref.toUpperCase());
10781
- if (definition === void 0) continue;
10782
- const entry = baseline.tasks[task.ref.toUpperCase()];
10783
- if (entry === void 0) continue;
10784
- if (task.status !== "todo" && task.status !== "done") continue;
10785
- const current = await hashesFor(definition);
10786
- const changed = diffHashes(entry.target, current.hashes);
10787
- if (changed.length === 0) continue;
10788
- findings.push({
10789
- code: task.status === "todo" ? "OUT_OF_BAND_CHANGES" : "MODIFIED_AFTER_DONE",
10790
- severity: "warn",
10791
- taskRef: task.ref,
10792
- message: task.status === "todo" ? `File di scope ${task.ref} berubah padahal task belum dijalankan. Kalau ini hasil alat lain (Figma MCP/AI Studio/editor luar), jalankan \`jioogen task adopt ${task.ref}\` setelah verifikasi; kalau belum selesai, \`jioogen task start ${task.ref}\` dulu.` : `File milik ${task.ref} berubah setelah task selesai. Tinjau diff; bila perubahan disengaja, reset lalu adopsi ulang (\`jioogen task reset ${task.ref}\` \u2192 \`jioogen task adopt ${task.ref}\`).`,
10793
- files: changed
10794
- });
10919
+
10920
+ // src/tasks.ts
10921
+ var TASK_ID_RE2 = /\b(?:TASK|T)-\d{3,}\b/i;
10922
+ var HEADING_RE = /^#{1,4}\s+(.+)$/m;
10923
+ var LAYER_RANK = {
10924
+ frontend_mock: 0,
10925
+ database: 1,
10926
+ backend_api: 2,
10927
+ integration: 3,
10928
+ verification: 4
10929
+ };
10930
+ var IN_PROGRESS = ["in_progress", "verifying"];
10931
+ var QUALITY_HEADING = "## KUALITAS WAJIB (ringkas; detail di skill bila tersedia)";
10932
+ var BREAKDOWN_HEADING = "## BREAKDOWN WAJIB \u2014 SEBELUM CODING";
10933
+ var MAX_CHECKLIST_LINES = 12;
10934
+ var MAX_CUSTOM_KNOWLEDGE_FILES = 10;
10935
+ var CUSTOM_KNOWLEDGE_HEADER = "## KNOWLEDGE CUSTOM (user-owned, additive)";
10936
+ var BREAKDOWN_RULES = [
10937
+ "Breakdown ini mengikat: tulis/centang setiap item sebelum mulai edit, dan jangan `task complete` selama ada item tanpa bukti.",
10938
+ "Ini checklist kerja, bukan task baru; task baru hanya diizinkan pada `--mode seed`.",
10939
+ "Pratinjau ulang: `npx jioogen task expand <ref>`."
10940
+ ];
10941
+ var UI_SKILLS = ["ui-ux-pro-max", "impeccable"];
10942
+ var LAYER_CHECKLISTS = {
10943
+ frontend_mock: [
10944
+ "- Reuse token desain yang ada; jangan hardcode warna/spacing bila token tersedia.",
10945
+ "- Tangani semua state UI: loading, empty, error, success.",
10946
+ "- Responsive untuk mobile dan desktop.",
10947
+ "- Aksesibilitas dasar: label, aria, focus, keyboard.",
10948
+ "- Microcopy jelas dan konsisten dengan konteks.",
10949
+ "- Tanpa komponen/abstraksi baru untuk satu pemakaian; reuse yang ada."
10950
+ ],
10951
+ database: [
10952
+ "- Migrasi eksplisit dan aman (reversible, tanpa mengubah migrasi lama).",
10953
+ "- Constraint dan index sesuai pola query.",
10954
+ "- Relasi dan isolation sesuai specs (tenant/owner).",
10955
+ "- Seed idempotent (bisa dijalankan ulang tanpa duplikasi).",
10956
+ "- Tanpa query lintas pemilik.",
10957
+ "- Tanpa tabel/kolom spekulatif; hanya yang dipakai requirement."
10958
+ ],
10959
+ backend_api: [
10960
+ "- Validasi input di boundary.",
10961
+ "- Error contract konsisten (status + bentuk response).",
10962
+ "- Auth/permission dicek sebelum mutasi.",
10963
+ "- Idempotensi untuk operasi tulis/retry.",
10964
+ "- Logging tanpa secret/PII.",
10965
+ "- Tanpa helper/duplikasi untuk satu pemakaian; ekstrak hanya bila berulang."
10966
+ ],
10967
+ integration: [
10968
+ "- Mock dihapus dari jalur utama.",
10969
+ "- Kontrak CONTRACT-XXX sama dengan implementasi.",
10970
+ "- E2E memakai data nyata.",
10971
+ "- Error path diuji.",
10972
+ "- Tanpa layer/abstraksi tambahan; hubungkan langsung ke kontrak."
10973
+ ],
10974
+ verification: [
10975
+ "- Jalankan semua verificationCommand sampai exit 0.",
10976
+ "- Smoke route/navigasi utama.",
10977
+ "- UI states dan responsive dicek.",
10978
+ "- Bukti Acceptance Criteria \xA711.",
10979
+ "- Jangan menambah kode produksi baru hanya untuk verifikasi."
10980
+ ]
10981
+ };
10982
+ async function loadTasks(bundleDir) {
10983
+ const tasksDir = join5(bundleDir, "tasks");
10984
+ let entries;
10985
+ try {
10986
+ entries = await readdir3(tasksDir, { withFileTypes: true });
10987
+ } catch (error) {
10988
+ if (isMissingFile3(error)) throw new Error(`Direktori tasks/ tidak ditemukan di ${bundleDir}`);
10989
+ throw error;
10990
+ }
10991
+ const names = entries.filter(
10992
+ (entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md") && entry.name.toUpperCase() !== "TASKS.MD"
10993
+ ).map((entry) => entry.name).sort();
10994
+ const tasks = [];
10995
+ if (names.length > 0) {
10996
+ for (const name of names) {
10997
+ const content = await readFile5(join5(tasksDir, name), "utf8");
10998
+ tasks.push(parseSingleTask(name, content));
10795
10999
  }
11000
+ } else {
11001
+ const singlePath = join5(tasksDir, "TASKS.md");
11002
+ let content;
11003
+ try {
11004
+ content = await readFile5(singlePath, "utf8");
11005
+ } catch (error) {
11006
+ if (isMissingFile3(error)) throw new Error(`Tidak ada berkas task di ${tasksDir}`);
11007
+ throw error;
11008
+ }
11009
+ tasks.push(...parseSingleFile(content));
10796
11010
  }
10797
- if (options.includeInfo !== false) {
10798
- findings.push(...await detectPreExisting(definitions, state, baseline, focus, hashesFor));
11011
+ if (tasks.length === 0) throw new Error(`Tidak ada task yang bisa dibaca di ${tasksDir}`);
11012
+ assertUniqueIds(tasks);
11013
+ return tasks;
11014
+ }
11015
+ function parseSingleTask(file, content) {
11016
+ const heading = firstHeading(content);
11017
+ const explicit = TASK_ID_RE2.exec(file)?.[0] ?? explicitIdFromContent(content);
11018
+ const id = explicit ?? file.replace(/\.md$/i, "");
11019
+ if (id.length === 0) {
11020
+ throw new Error(`Berkas task tanpa ID: ${file}`);
10799
11021
  }
10800
- return findings;
11022
+ return buildTask(id, heading, file, content);
10801
11023
  }
10802
- async function detectPreExisting(definitions, state, baseline, focus, hashesFor) {
10803
- const byId = new Map(definitions.map((entry) => [entry.id.toUpperCase(), entry]));
10804
- const done = /* @__PURE__ */ new Set();
10805
- for (const task of state.tasks) {
10806
- if (task.status !== "done") continue;
10807
- const definition = byId.get(task.ref.toUpperCase());
10808
- if (definition === void 0) continue;
10809
- const current = await hashesFor(definition);
10810
- for (const path of Object.keys(current.hashes)) done.add(path);
11024
+ function explicitIdFromContent(content) {
11025
+ const heading = firstHeading(content);
11026
+ const fromHeading = heading !== null ? TASK_ID_RE2.exec(heading)?.[0] : void 0;
11027
+ if (fromHeading !== void 0) return fromHeading;
11028
+ return /(?:\*\*)?ID(?:\*\*)?\s*[:=]\s*`?((?:TASK|T)-\d{3,})/i.exec(content)?.[1];
11029
+ }
11030
+ function parseSingleFile(content) {
11031
+ const blocks = content.split(/\n(?=#{1,4}\s+(?:TASK|T)-\d{3,}\b)/i);
11032
+ const tasks = [];
11033
+ for (const block of blocks) {
11034
+ const heading = firstHeading(block);
11035
+ const id = heading !== null ? TASK_ID_RE2.exec(heading)?.[0] : void 0;
11036
+ if (id === void 0) continue;
11037
+ tasks.push(buildTask(id, heading, "TASKS.md", block));
10811
11038
  }
10812
- const findings = [];
10813
- for (const task of state.tasks) {
10814
- if (task.status !== "todo") continue;
10815
- const key = task.ref.toUpperCase();
10816
- if (focus !== void 0 && key !== focus) continue;
10817
- if (baseline?.tasks[key] !== void 0) continue;
10818
- const definition = byId.get(key);
10819
- if (definition === void 0) continue;
10820
- const current = await hashesFor(definition);
10821
- const preExisting = Object.keys(current.hashes).filter((path) => !done.has(path));
10822
- if (preExisting.length === 0) continue;
10823
- findings.push({
10824
- code: "PRE_EXISTING_SCOPE",
10825
- severity: "info",
10826
- taskRef: task.ref,
10827
- message: `Scope ${task.ref} sudah berisi file sebelum task dimulai. Bila ini hasil Figma MCP/AI Studio/editor lain, verifikasi lalu \`jioogen task adopt ${task.ref}\`; bila belum, \`jioogen task start ${task.ref}\`.`,
10828
- files: preExisting.slice(0, 8)
10829
- });
11039
+ return tasks;
11040
+ }
11041
+ function buildTask(id, heading, file, content) {
11042
+ const context = parseTaskContext(content, id);
11043
+ const layer = resolveLayer(context.layer);
11044
+ if (context.layer !== void 0 && layer === void 0) {
11045
+ throw new Error(`Task ${context.taskId} punya layer tidak dikenal: ${context.layer.trim()}`);
10830
11046
  }
10831
- return findings;
11047
+ return {
11048
+ // Prefer the declared `id:` so `T-001-x.md` + `dependsOn: [TASK-001]` agree.
11049
+ id: context.taskId,
11050
+ title: titleFromGoal(content) ?? titleFromHeading(heading) ?? context.taskId,
11051
+ file,
11052
+ content: content.trim(),
11053
+ layer,
11054
+ phase: context.phase ?? 1,
11055
+ checkpoint: context.checkpoint === true,
11056
+ dependsOn: context.dependsOn
11057
+ };
10832
11058
  }
10833
- function formatDrift(finding) {
10834
- const label = finding.taskRef === void 0 ? finding.code : `${finding.code} ${finding.taskRef}`;
10835
- const files = finding.files.length === 0 ? "" : ` (${finding.files.slice(0, 4).join(", ")}${finding.files.length > 4 ? ", \u2026" : ""})`;
10836
- return `${finding.severity === "warn" ? "\u26A0" : "\u2139"} ${label}: ${finding.message}${files}`;
11059
+ function renderActiveTask(task, context) {
11060
+ const lines = [
11061
+ "## TASK AKTIF \u2014 PRIORITASKAN INI (satu task per giliran)",
11062
+ `ref: ${task.id}`,
11063
+ `title: ${task.title}`,
11064
+ `layer: ${task.layer ?? "-"} | phase: ${task.phase} | checkpoint: ${task.checkpoint}`,
11065
+ `file: tasks/${task.file}`
11066
+ ];
11067
+ if (task.dependsOn.length > 0) lines.push(`dependsOn: ${task.dependsOn.join(", ")}`);
11068
+ lines.push(
11069
+ "",
11070
+ "Aturan mengikat:",
11071
+ "- Kerjakan HANYA task ini sampai semua Acceptance Criteria terpenuhi dan verificationCommand exit 0.",
11072
+ "- Jangan pindah task, jangan mengerjakan task lain, jangan melebar ke file di luar targetFiles (file/direktori/glob).",
11073
+ "- Jangan mengarang fitur/endpoint/kolom di luar PRD.md/specs/.",
11074
+ "- Detail implementasi (pola, struktur file dalam scope, library yang sudah ada) milikmu; ikuti konvensi proyek.",
11075
+ "- Jangan mengubah PRD.md/specs/kontrak. Butuh perubahan kontrak? STOP dan laporkan.",
11076
+ "- Selesai: `npx jioogen task complete <ref>`, lalu `npx jioogen sync`."
11077
+ );
11078
+ const checklist = renderQualityChecklist(task.layer, context);
11079
+ if (checklist.length > 0) lines.push("", ...checklist);
11080
+ const breakdown = buildTaskBreakdown(task);
11081
+ const breakdownLines = [...breakdown.authored, ...breakdown.derived];
11082
+ if (breakdownLines.length > 0) {
11083
+ lines.push("", BREAKDOWN_HEADING, ...BREAKDOWN_RULES);
11084
+ for (const item of breakdownLines) lines.push(`- [ ] ${item}`);
11085
+ }
11086
+ lines.push("", "--- ISI TASK (otoritas scope) ---", task.content, "--- AKHIR ISI TASK ---");
11087
+ if (context?.bundleDir !== void 0) {
11088
+ const preferencesBlock = buildCustomPreferencesBlock(context.bundleDir);
11089
+ if (preferencesBlock.length > 0) lines.push("", preferencesBlock);
11090
+ const knowledgeBlock = buildCustomKnowledgeBlock(context.bundleDir);
11091
+ if (knowledgeBlock.length > 0) lines.push("", knowledgeBlock);
11092
+ }
11093
+ return lines.join("\n");
10837
11094
  }
10838
- async function targetHashes(bundleDir, patterns) {
10839
- const files = /* @__PURE__ */ new Set();
10840
- let truncated = false;
10841
- for (const pattern of patterns) {
10842
- const resolved = await expandPattern(bundleDir, pattern);
10843
- for (const file of resolved) {
10844
- if (files.size >= MAX_TARGET_FILES) {
10845
- truncated = true;
10846
- break;
10847
- }
10848
- files.add(file);
10849
- }
10850
- if (truncated) break;
11095
+ function buildTaskBreakdown(task) {
11096
+ const context = parseTaskContext(task.content, task.id);
11097
+ const authored = (context.subtasks ?? []).filter((item) => !/^N\/A\b/i.test(item));
11098
+ const derived = [];
11099
+ const seen = /* @__PURE__ */ new Set();
11100
+ const push = (item) => {
11101
+ const key = item.trim().toLowerCase();
11102
+ if (key.length === 0 || seen.has(key)) return;
11103
+ seen.add(key);
11104
+ derived.push(item);
11105
+ };
11106
+ for (const subfeature of context.subfeatures ?? []) {
11107
+ push(`${subfeature} \u2014 petakan ke AC, flow/state, dan targetFiles`);
10851
11108
  }
10852
- const hashes = {};
10853
- for (const file of [...files].sort()) {
10854
- const fingerprint = await fingerprintRelative(bundleDir, file);
10855
- if (fingerprint !== null) hashes[file] = fingerprint;
11109
+ for (const acceptance of context.acceptance ?? []) {
11110
+ if (/^N\/A\b/i.test(acceptance)) continue;
11111
+ push(`${acceptance} \u2014 penuhi + catat bukti`);
10856
11112
  }
10857
- return { hashes, truncated };
11113
+ for (const flow of context.flowRef ?? []) {
11114
+ push(`${flow} \u2014 implement alur sampai outcome`);
11115
+ }
11116
+ for (const lifecycle of context.lifecycleRefs ?? []) {
11117
+ push(`Lifecycle ${lifecycle} \u2014 state/transition yang relevan`);
11118
+ }
11119
+ for (const engine of context.engineRef ?? []) {
11120
+ push(`Engine ${engine} \u2014 invariant/keputusan yang dijaga`);
11121
+ }
11122
+ for (const state of context.uiStates ?? []) {
11123
+ push(`UI state ${state} \u2014 render + verifikasi`);
11124
+ }
11125
+ for (const isolation of context.isolationRefs ?? []) {
11126
+ push(`${isolation} \u2014 tegakkan boundary + AC penolakan akses`);
11127
+ }
11128
+ for (const file of context.targetFiles ?? []) {
11129
+ push(`File ${file} \u2014 buat/edit + test terkait`);
11130
+ }
11131
+ if (context.verificationCommand !== null && context.verificationCommand !== void 0) {
11132
+ push(`Verifikasi: \`${context.verificationCommand}\` (wajib exit 0)`);
11133
+ }
11134
+ if (authored.length === 0 && derived.length === 0) {
11135
+ push("Baca task + PRD/specs, lalu tulis langkah kerja eksplisit sebelum edit");
11136
+ }
11137
+ return { authored, derived };
10858
11138
  }
10859
- async function expandPattern(bundleDir, raw) {
10860
- const pattern = normalizePattern(raw);
10861
- if (pattern === null) return [];
10862
- if (!/[*?[]/.test(pattern)) {
10863
- const info = await statMaybe(join5(bundleDir, pattern));
10864
- if (info === null) return [];
10865
- if (info.isDirectory()) {
10866
- return (await walk(bundleDir, pattern, MAX_TARGET_FILES)).files;
11139
+ function renderQualityChecklist(layer, context) {
11140
+ if (context === void 0 || layer === void 0) return [];
11141
+ const items = [...LAYER_CHECKLISTS[layer] ?? []];
11142
+ if (layer === "frontend_mock") {
11143
+ const references = UI_SKILLS.filter((skill) => context.skills?.includes(skill) === true);
11144
+ if (references.length > 0) items.push(`- Referensi skill: ${references.join(", ")}`);
11145
+ }
11146
+ if (items.length === 0) return [];
11147
+ return [QUALITY_HEADING, ...items.slice(0, MAX_CHECKLIST_LINES)];
11148
+ }
11149
+ function resolveLayer(value) {
11150
+ if (value === void 0) return void 0;
11151
+ const token = value.trim().replace(/[`*]/g, "").split(/[\s,(]/)[0];
11152
+ if (token === void 0) return void 0;
11153
+ return TASK_LAYERS.includes(token) ? token : void 0;
11154
+ }
11155
+ function titleFromGoal(content) {
11156
+ const match = /goal\s*\*{0,2}\s*[:=]\s*\*{0,2}\s*([^\n]+)/i.exec(content);
11157
+ if (match?.[1] === void 0) return null;
11158
+ return stripMarkup(match[1]);
11159
+ }
11160
+ function firstHeading(content) {
11161
+ return HEADING_RE.exec(content)?.[1]?.trim() ?? null;
11162
+ }
11163
+ function titleFromHeading(heading) {
11164
+ if (heading === null) return null;
11165
+ const withoutId = heading.replace(/^(?:TASK|T)-\d{3,}\s*[—–:-]?\s*/i, "").trim();
11166
+ return withoutId.length > 0 ? withoutId : heading;
11167
+ }
11168
+ function stripMarkup(text2) {
11169
+ return text2.replace(/[`*_]/g, "").replace(/^["'\s]+|["'\s]+$/g, "").trim();
11170
+ }
11171
+ function assertUniqueIds(tasks) {
11172
+ const seen = /* @__PURE__ */ new Set();
11173
+ for (const task of tasks) {
11174
+ const base = task.id.toUpperCase();
11175
+ if (!seen.has(base)) {
11176
+ seen.add(base);
11177
+ continue;
10867
11178
  }
10868
- return info.isFile() ? [pattern] : [];
11179
+ let suffix = 2;
11180
+ let key = `${base}-DUP-${suffix}`;
11181
+ while (seen.has(key)) {
11182
+ suffix += 1;
11183
+ key = `${base}-DUP-${suffix}`;
11184
+ }
11185
+ seen.add(key);
11186
+ task.id = `${task.id}-DUP-${suffix}`;
11187
+ console.warn(
11188
+ `[jioogen] WARNING: ID task duplikat di tasks/${task.file}: "${base}" sudah dipakai \u2014 dilanjutkan sebagai "${task.id}". Rename file dan id-nya ke TASK unik agar warning hilang.`
11189
+ );
10869
11190
  }
10870
- const matcher = globToRegExp(pattern);
10871
- const start = staticPrefix(pattern);
10872
- const walked = await walk(bundleDir, start, MAX_TARGET_FILES);
10873
- return walked.files.filter((file) => matcher.test(file));
10874
11191
  }
10875
- function normalizePattern(raw) {
10876
- let value = raw.trim().replace(/^`+|`+$/g, "").replace(/\\/g, "/");
10877
- value = value.replace(/^\.\//, "").replace(/\/+$/, "");
10878
- if (value.length === 0 || isAbsolute(value)) return null;
10879
- if (value.split("/").includes("..")) return null;
10880
- return value;
11192
+ function orderTasks(tasks) {
11193
+ return [...tasks].sort(
11194
+ (left, right) => left.phase - right.phase || layerRank(left.layer) - layerRank(right.layer) || numericId(left.id) - numericId(right.id) || left.id.localeCompare(right.id)
11195
+ );
10881
11196
  }
10882
- function staticPrefix(pattern) {
10883
- const index = pattern.search(/[*?[]/);
10884
- const head = index === -1 ? pattern : pattern.slice(0, index);
10885
- const trimmed = head.replace(/\/+$/, "");
10886
- if (trimmed.length === 0) return "";
10887
- if (head.endsWith("/")) return trimmed;
10888
- const slash = trimmed.lastIndexOf("/");
10889
- return slash === -1 ? "" : trimmed.slice(0, slash);
11197
+ function layerRank(layer) {
11198
+ return layer === void 0 ? 0 : LAYER_RANK[layer] ?? 0;
10890
11199
  }
10891
- function globToRegExp(pattern) {
10892
- let source = "^";
10893
- for (let index = 0; index < pattern.length; index += 1) {
10894
- const char = pattern[index] ?? "";
10895
- if (char === "*") {
10896
- if (pattern[index + 1] === "*") {
10897
- if (pattern[index + 2] === "/") {
10898
- source += "(?:.*/)?";
10899
- index += 2;
10900
- } else {
10901
- source += ".*";
10902
- index += 1;
10903
- }
10904
- } else {
10905
- source += "[^/]*";
10906
- }
10907
- } else if (char === "?") {
10908
- source += "[^/]";
10909
- } else if ("\\^$+.()|{}[]".includes(char)) {
10910
- source += `\\${char}`;
10911
- } else {
10912
- source += char;
11200
+ function numericId(id) {
11201
+ const leading = /^(\d+)/.exec(id);
11202
+ if (leading?.[1] !== void 0) return Number.parseInt(leading[1], 10);
11203
+ const trailing = /(?:^|[-\s])(\d{3,})$/.exec(id);
11204
+ return trailing?.[1] !== void 0 ? Number.parseInt(trailing[1], 10) : Number.MAX_SAFE_INTEGER;
11205
+ }
11206
+ function selectNext(tasks, states, options) {
11207
+ const byRef = new Map(states.map((state) => [state.ref.toUpperCase(), state]));
11208
+ const ordered = orderTasks(tasks);
11209
+ for (const task of ordered) {
11210
+ const state = byRef.get(task.id.toUpperCase());
11211
+ if (state !== void 0 && IN_PROGRESS.includes(state.status)) {
11212
+ return { task, state, reason: "in_progress" };
10913
11213
  }
10914
11214
  }
10915
- return new RegExp(`${source}$`);
11215
+ for (const task of ordered) {
11216
+ const state = byRef.get(task.id.toUpperCase());
11217
+ if (state?.status === "done") continue;
11218
+ if (hasUnfinishedDependency(task, byRef) && options?.lenient !== true) continue;
11219
+ const effective = state ?? { ref: task.id, status: "todo" };
11220
+ return { task, state: effective, reason: effective.status === "todo" ? "todo" : "retry" };
11221
+ }
11222
+ return null;
10916
11223
  }
10917
- async function walk(bundleDir, start, limit) {
10918
- const files = [];
10919
- let truncated = false;
10920
- const visit = async (relative2) => {
10921
- if (truncated) return;
10922
- let entries;
11224
+ async function taskTargetFilesExist(bundleDir, task) {
11225
+ const targets = task.targetFiles ?? targetFilesFromContent(task.content);
11226
+ if (targets.length === 0) return false;
11227
+ for (const raw of targets) {
11228
+ const cleaned = raw.trim().replace(/^`+|`+$/g, "").replace(/^\.\//, "");
11229
+ if (cleaned.length === 0) continue;
11230
+ const staticPart = cleaned.replace(/[*?[][\s\S]*$/, "").replace(/\/+$/, "");
11231
+ const testPath = staticPart.length > 0 ? staticPart : cleaned;
11232
+ const fullPath = isAbsolute(testPath) ? testPath : join5(bundleDir, testPath);
10923
11233
  try {
10924
- entries = await readdir4(relative2.length === 0 ? bundleDir : join5(bundleDir, relative2), {
10925
- withFileTypes: true
10926
- });
11234
+ await stat2(fullPath);
11235
+ return true;
10927
11236
  } catch {
10928
- return;
10929
11237
  }
10930
- entries.sort((left, right) => left.name.localeCompare(right.name));
10931
- for (const entry of entries) {
10932
- const child = relative2.length === 0 ? entry.name : `${relative2}/${entry.name}`;
10933
- if (entry.isDirectory()) {
10934
- if (IGNORED_DIRS.has(entry.name)) continue;
10935
- if (child === "tasks/.execution") continue;
10936
- await visit(child);
10937
- } else if (entry.isFile()) {
10938
- if (files.length >= limit) {
10939
- truncated = true;
10940
- return;
10941
- }
10942
- files.push(child);
10943
- }
11238
+ }
11239
+ return false;
11240
+ }
11241
+ async function reconcileCodebase(bundleDir, definitions, state) {
11242
+ let currentState = state;
11243
+ const adopted = [];
11244
+ const remaining = [];
11245
+ for (const task of definitions) {
11246
+ const existingTask = currentState.tasks.find(
11247
+ (t) => t.ref.toUpperCase() === task.id.toUpperCase()
11248
+ );
11249
+ if (existingTask?.status === "done") {
11250
+ continue;
11251
+ }
11252
+ const filesExist = await taskTargetFilesExist(bundleDir, task);
11253
+ if (filesExist) {
11254
+ currentState = withStatus(currentState, task.id, "done", {
11255
+ note: "reconciled: target files exist on disk",
11256
+ awaitingCheckpoint: false
11257
+ });
11258
+ currentState = setTaskSource(currentState, task.id, "user");
11259
+ currentState = appendTaskEvidence(currentState, task.id, {
11260
+ type: "text",
11261
+ summary: "reconciled from codebase: target files found on disk",
11262
+ at: (/* @__PURE__ */ new Date()).toISOString()
11263
+ });
11264
+ adopted.push(task.id);
11265
+ } else {
11266
+ remaining.push(task.id);
11267
+ }
11268
+ }
11269
+ return {
11270
+ state: currentState,
11271
+ result: {
11272
+ adopted,
11273
+ remaining,
11274
+ total: definitions.length
11275
+ }
11276
+ };
11277
+ }
11278
+ function blockedTasks(tasks, states) {
11279
+ const byRef = new Map(states.map((state) => [state.ref.toUpperCase(), state]));
11280
+ return orderTasks(tasks).filter((task) => byRef.get(task.id.toUpperCase())?.status !== "done").map((task) => ({
11281
+ task,
11282
+ missing: task.dependsOn.filter(
11283
+ (dependency) => byRef.get(dependency.toUpperCase())?.status !== "done"
11284
+ )
11285
+ })).filter((entry) => entry.missing.length > 0);
11286
+ }
11287
+ function hasUnfinishedDependency(task, byRef) {
11288
+ return task.dependsOn.some(
11289
+ (dependency) => byRef.get(dependency.toUpperCase())?.status !== "done"
11290
+ );
11291
+ }
11292
+ function isBoundary(previous, next) {
11293
+ if (next.checkpoint) return true;
11294
+ if (previous.layer !== void 0 && next.layer !== void 0 && previous.layer !== next.layer) {
11295
+ return true;
11296
+ }
11297
+ return previous.phase !== void 0 && next.phase !== previous.phase;
11298
+ }
11299
+ var RISKY_TASK_RE = /\b(migrat(?:e|ion|ions)?|migrasi|prisma|schema|rls|auth|permission|payment|checkout|webhook|secret|deploy|drop)\b/i;
11300
+ var TARGET_FILES_LABEL_RE2 = /^\s*(?:[-*]\s*)?\*{0,2}targetFiles\*{0,2}\s*:\s*(.*)$/i;
11301
+ function isRiskyTask(task) {
11302
+ const targetFiles = task.targetFiles ?? targetFilesFromContent(task.content);
11303
+ return RISKY_TASK_RE.test([task.id, task.title, ...targetFiles].join("\n"));
11304
+ }
11305
+ function targetFilesFromContent(content) {
11306
+ const lines = content.split(/\r?\n/);
11307
+ const index = lines.findIndex((line) => TARGET_FILES_LABEL_RE2.test(line));
11308
+ if (index === -1) return [];
11309
+ const inline = (lines[index]?.match(TARGET_FILES_LABEL_RE2)?.[1] ?? "").trim();
11310
+ if (inline.length > 0) return splitTargetFiles(inline);
11311
+ const items = [];
11312
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
11313
+ const line = lines[cursor] ?? "";
11314
+ if (line.trim().length === 0) continue;
11315
+ const item = /^\s*-\s+(.+?)\s*$/.exec(line);
11316
+ if (item === null) break;
11317
+ const cleaned = cleanTargetFile(item[1] ?? "");
11318
+ if (cleaned.length > 0) items.push(cleaned);
11319
+ }
11320
+ return items;
11321
+ }
11322
+ function splitTargetFiles(value) {
11323
+ return value.replace(/[[\]`]/g, "").split(",").map(cleanTargetFile).filter((part) => part.length > 0 && !/^(?:\(?none\)?|n\/a|-+)$/i.test(part));
11324
+ }
11325
+ function cleanTargetFile(value) {
11326
+ return value.replace(/^[-*\s]+/, "").trim();
11327
+ }
11328
+ function verificationCommandFromContent(content) {
11329
+ const inline = content.match(
11330
+ /^\s*(?:[-*]\s*)?\*{0,2}verificationCommand\*{0,2}\s*:\s*(.+?)\s*$/im
11331
+ );
11332
+ if (inline?.[1] !== void 0) {
11333
+ const value = stripVerificationBackticks(inline[1].trim());
11334
+ if (isVerificationPlaceholder(value)) return null;
11335
+ if (value.length > 0) return value;
11336
+ }
11337
+ const lines = content.split(/\r?\n/);
11338
+ for (let i = 0; i < lines.length; i += 1) {
11339
+ const heading = lines[i]?.trim() ?? "";
11340
+ if (!/^#{1,6}\s+Verification(?:\s+Command)?\s*$/i.test(heading)) continue;
11341
+ for (let j = i + 1; j < lines.length; j += 1) {
11342
+ const next = (lines[j] ?? "").trim();
11343
+ if (next.length === 0) continue;
11344
+ if (/^#{1,6}\s/.test(next)) break;
11345
+ const value = stripVerificationBackticks(next);
11346
+ if (isVerificationPlaceholder(value)) return null;
11347
+ return value.length > 0 ? value : null;
11348
+ }
11349
+ }
11350
+ return null;
11351
+ }
11352
+ function normalizeVerificationCommand(value) {
11353
+ const stripped = stripVerificationBackticks(value.trim());
11354
+ return stripped.replace(/\b(?:pnpm|yarn|bun|npm)\s+(?:run\s+)?/g, "npm run ").replace(/\bnpx\s+/g, "npm exec ").replace(/\s+--(?:run|silent)\b/g, "").replace(/\s+-s\b/g, "").replace(/\s+--reporter(?:=\S+|\s+\S+)/g, "").replace(/\s+/g, " ").trim();
11355
+ }
11356
+ function stripVerificationBackticks(value) {
11357
+ const trimmed = value.replace(/^`+/, "").replace(/`+$/, "").trim();
11358
+ if (trimmed.length >= 2) {
11359
+ const first = trimmed[0];
11360
+ const last = trimmed[trimmed.length - 1];
11361
+ if (first === '"' && last === '"' || first === "'" && last === "'") {
11362
+ return trimmed.slice(1, -1).trim();
10944
11363
  }
10945
- };
10946
- await visit(start);
10947
- return { files, truncated };
11364
+ }
11365
+ return trimmed;
10948
11366
  }
10949
- async function fingerprintRelative(bundleDir, relative2) {
10950
- const info = await statMaybe(join5(bundleDir, relative2));
10951
- if (info === null || !info.isFile()) return null;
10952
- return `${info.size}:${Math.trunc(info.mtimeMs)}`;
11367
+ function isVerificationPlaceholder(value) {
11368
+ return /^(?:n\/a|—+|-+|none)$/i.test(value.trim());
10953
11369
  }
10954
- async function hashRelative(bundleDir, relative2) {
10955
- const info = await statMaybe(join5(bundleDir, relative2));
10956
- if (info === null || !info.isFile()) return null;
10957
- if (info.size > MAX_BUNDLE_FILE_BYTES) return `size:${info.size}`;
11370
+ var CUSTOM_PREFERENCES_HEADER = "## USER CUSTOM PREFERENCES & STACK (.jioogen/custom/)";
11371
+ function buildCustomPreferencesBlock(bundleDir) {
11372
+ const parts = [];
11373
+ const stackFile = join5(bundleDir, ".jioogen", "custom", "stack", "STACK.md");
10958
11374
  try {
10959
- const bytes = await readFile5(join5(bundleDir, relative2));
10960
- return createHash("sha256").update(bytes).digest("hex");
11375
+ const stackContent = readFileSync(stackFile, "utf8").trim();
11376
+ if (stackContent.length > 0) {
11377
+ parts.push(`### User Custom Stack (.jioogen/custom/stack/STACK.md)
11378
+ ${stackContent}`);
11379
+ }
10961
11380
  } catch {
10962
- return null;
10963
11381
  }
10964
- }
10965
- async function statMaybe(path) {
11382
+ const designFile = join5(bundleDir, ".jioogen", "custom", "design", "DESIGN.md");
10966
11383
  try {
10967
- return await stat(path);
11384
+ const designContent = readFileSync(designFile, "utf8").trim();
11385
+ if (designContent.length > 0) {
11386
+ parts.push(`### User Custom Design (.jioogen/custom/design/DESIGN.md)
11387
+ ${designContent}`);
11388
+ }
10968
11389
  } catch {
10969
- return null;
10970
- }
10971
- }
10972
- function diffHashes(before, after) {
10973
- const changed = /* @__PURE__ */ new Set();
10974
- for (const [path, hash] of Object.entries(before)) {
10975
- if (after[path] !== hash) changed.add(path);
10976
- }
10977
- for (const path of Object.keys(after)) {
10978
- if (!(path in before)) changed.add(path);
10979
11390
  }
10980
- return [...changed].sort();
11391
+ if (parts.length === 0) return "";
11392
+ return [
11393
+ CUSTOM_PREFERENCES_HEADER,
11394
+ "Perhatikan preferensi teknologi dan arsitektur custom user di bawah ini saat mengeksekusi task:",
11395
+ ...parts
11396
+ ].join("\n\n");
10981
11397
  }
10982
- async function bundleHashOf(bundleDir) {
10983
- const files = [];
10984
- for (const name of ["PRD.md", "traceability.md"]) {
10985
- const info = await statMaybe(join5(bundleDir, name));
10986
- if (info?.isFile()) files.push(name);
11398
+ function listCustomKnowledgeFiles(bundleDir) {
11399
+ const dir = join5(bundleDir, ".jioogen", "custom", "knowledge");
11400
+ let entries;
11401
+ try {
11402
+ entries = readdirSync(dir, { withFileTypes: true });
11403
+ } catch {
11404
+ return [];
10987
11405
  }
10988
- for (const directory of ["specs", "tasks"]) {
10989
- const walked = await walk(bundleDir, directory, MAX_TARGET_FILES);
10990
- for (const file of walked.files) {
10991
- if (file.startsWith("tasks/.execution/")) continue;
10992
- if (IGNORED_TOP_FILES.has(file)) continue;
10993
- if (!file.toLowerCase().endsWith(".md")) continue;
10994
- files.push(file);
11406
+ const names = entries.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md")).map((entry) => entry.name).sort();
11407
+ const result = [];
11408
+ for (const name of names) {
11409
+ if (result.length >= MAX_CUSTOM_KNOWLEDGE_FILES) break;
11410
+ const full = join5(dir, name);
11411
+ try {
11412
+ const content = readFileSync(full, "utf8");
11413
+ if (content.trim().length === 0) continue;
11414
+ } catch {
11415
+ continue;
10995
11416
  }
11417
+ result.push(`.jioogen/custom/knowledge/${name}`);
10996
11418
  }
10997
- const lines = [];
10998
- for (const file of files.sort()) {
10999
- const hash = await hashRelative(bundleDir, file);
11000
- if (hash !== null) lines.push(`${file}\0${hash}`);
11001
- }
11002
- return createHash("sha256").update(lines.join("\n")).digest("hex");
11419
+ return result.slice(0, MAX_CUSTOM_KNOWLEDGE_FILES);
11003
11420
  }
11004
-
11005
- // src/sidecar.ts
11006
- import { randomUUID } from "node:crypto";
11007
- import { mkdir as mkdir4, open, readFile as readFile6, rename, rm as rm4, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
11008
- import { dirname as dirname4, join as join6 } from "node:path";
11009
- var LOCK_RETRY_MS = 25;
11010
- var LOCK_TIMEOUT_MS = 3e3;
11011
- var LOCK_STALE_MS = 1e4;
11012
- function sidecarPath(bundleDir) {
11013
- return join6(bundleDir, EXECUTION_SIDECAR_PATH);
11421
+ function buildCustomKnowledgeBlock(bundleDir) {
11422
+ const files = listCustomKnowledgeFiles(bundleDir);
11423
+ if (files.length === 0) return "";
11424
+ const lines = [
11425
+ CUSTOM_KNOWLEDGE_HEADER,
11426
+ ...files.map((file) => `- ${file}`),
11427
+ "Baca file-file di atas sebagai konteks tambahan user sebelum coding."
11428
+ ];
11429
+ return lines.join("\n");
11014
11430
  }
11015
- function lockPath(bundleDir) {
11016
- return `${sidecarPath(bundleDir)}.lock`;
11431
+ function isMissingFile3(error) {
11432
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
11017
11433
  }
11018
- async function withStateLock(bundleDir, fn) {
11019
- const target = lockPath(bundleDir);
11020
- await mkdir4(dirname4(target), { recursive: true });
11021
- const deadline = Date.now() + LOCK_TIMEOUT_MS;
11022
- let handle = null;
11023
- let staleRemoved = false;
11024
- while (handle === null) {
11025
- try {
11026
- handle = await open(target, "wx");
11027
- } catch (error) {
11028
- if (!isLockBusy(error)) throw error;
11029
- if (!staleRemoved && await removeStaleLock(target)) {
11030
- staleRemoved = true;
11031
- continue;
11032
- }
11033
- if (Date.now() >= deadline) {
11034
- throw new Error(
11035
- `Gagal mengambil lock sidecar setelah ${LOCK_TIMEOUT_MS / 1e3} detik: ${target}. Kemungkinan proses lain masih menulis; hapus file lock itu bila proses tersebut sudah mati.`
11036
- );
11037
- }
11038
- await delay(LOCK_RETRY_MS);
11039
- }
11434
+
11435
+ // src/drift.ts
11436
+ var DRIFT_BASELINE_PATH = join6("tasks", ".execution", "baseline.json");
11437
+ var BASELINE_VERSION = 1;
11438
+ var MAX_TARGET_FILES = 2e3;
11439
+ var MAX_BUNDLE_FILE_BYTES = 1048576;
11440
+ var IGNORED_DIRS = /* @__PURE__ */ new Set([
11441
+ ".git",
11442
+ "node_modules",
11443
+ ".next",
11444
+ "dist",
11445
+ "build",
11446
+ "coverage",
11447
+ ".turbo",
11448
+ ".cache",
11449
+ ".vercel",
11450
+ ".output",
11451
+ "out",
11452
+ ".expo",
11453
+ ".jioogen",
11454
+ ".claude",
11455
+ ".opencode",
11456
+ ".agent",
11457
+ ".codex",
11458
+ ".cursor"
11459
+ ]);
11460
+ var IGNORED_TOP_FILES = /* @__PURE__ */ new Set(["AGENTS.md"]);
11461
+ async function readAcknowledged(bundleDir) {
11462
+ let raw;
11463
+ try {
11464
+ raw = await readFile6(join6(bundleDir, "tasks", ".execution", "acknowledged.json"), "utf8");
11465
+ } catch {
11466
+ return null;
11040
11467
  }
11468
+ let parsed;
11041
11469
  try {
11042
- await handle.writeFile(`${process.pid}
11043
- `, "utf8");
11044
- return await fn();
11045
- } finally {
11046
- await handle.close().catch(() => {
11047
- });
11048
- await rm4(target, { force: true }).catch(() => {
11049
- });
11470
+ parsed = JSON.parse(raw);
11471
+ } catch {
11472
+ return null;
11050
11473
  }
11474
+ if (typeof parsed !== "object" || parsed === null) return null;
11475
+ const record = parsed;
11476
+ const marker = { at: typeof record.at === "string" ? record.at : "" };
11477
+ if (typeof record.pruned === "boolean") marker.pruned = record.pruned;
11478
+ if (typeof record.prd === "boolean") marker.prd = record.prd;
11479
+ if (typeof record.specs === "boolean") marker.specs = record.specs;
11480
+ if (typeof record.tasks === "boolean") marker.tasks = record.tasks;
11481
+ if (typeof record.note === "string") marker.note = record.note;
11482
+ return marker;
11483
+ }
11484
+ async function acknowledgeDrift(bundleDir, flags = {}, note, now = /* @__PURE__ */ new Date()) {
11485
+ const existing = await readAcknowledged(bundleDir);
11486
+ const merged = {
11487
+ pruned: flags.pruned === true || existing?.pruned === true,
11488
+ prd: flags.prd === true || existing?.prd === true,
11489
+ specs: flags.specs === true || existing?.specs === true,
11490
+ tasks: flags.tasks === true || existing?.tasks === true,
11491
+ at: now.toISOString()
11492
+ };
11493
+ const mergedNote = note ?? existing?.note;
11494
+ if (mergedNote !== void 0) merged.note = mergedNote;
11495
+ const target = join6(bundleDir, "tasks", ".execution", "acknowledged.json");
11496
+ await mkdir4(dirname4(target), { recursive: true });
11497
+ await writeFile4(target, `${JSON.stringify(merged, null, 2)}
11498
+ `, "utf8");
11499
+ return merged;
11051
11500
  }
11052
- async function readState(bundleDir) {
11501
+ function baselinePath(bundleDir) {
11502
+ return join6(bundleDir, DRIFT_BASELINE_PATH);
11503
+ }
11504
+ async function readBaseline(bundleDir) {
11053
11505
  let raw;
11054
11506
  try {
11055
- raw = await readFile6(sidecarPath(bundleDir), "utf8");
11056
- } catch (error) {
11057
- if (isMissingFile3(error)) return null;
11058
- throw error;
11507
+ raw = await readFile6(baselinePath(bundleDir), "utf8");
11508
+ } catch {
11509
+ return null;
11059
11510
  }
11060
- let payload;
11511
+ let parsed;
11061
11512
  try {
11062
- payload = JSON.parse(raw);
11513
+ parsed = JSON.parse(raw);
11063
11514
  } catch {
11064
- throw new Error(`Sidecar bukan JSON yang valid: ${sidecarPath(bundleDir)}`);
11515
+ return null;
11065
11516
  }
11066
- const parsed = ExecutionStateSchema.safeParse(payload);
11067
- if (!parsed.success) {
11068
- throw new Error(
11069
- `Sidecar tidak cocok dengan schema v${EXECUTION_SIDECAR_VERSION}: ${sidecarPath(bundleDir)}`
11070
- );
11517
+ if (typeof parsed !== "object" || parsed === null) return null;
11518
+ const record = parsed;
11519
+ const tasks = record.tasks;
11520
+ if (tasks === void 0 || typeof tasks !== "object" || tasks === null) return null;
11521
+ const entries = {};
11522
+ for (const [ref, value] of Object.entries(tasks)) {
11523
+ if (typeof value !== "object" || value === null) continue;
11524
+ const entry = value;
11525
+ if (typeof entry.target !== "object" || entry.target === null) continue;
11526
+ entries[ref] = {
11527
+ at: typeof entry.at === "string" ? entry.at : "",
11528
+ target: entry.target
11529
+ };
11071
11530
  }
11072
- return parsed.data;
11073
- }
11074
- function createState(projectId, definitions, now = /* @__PURE__ */ new Date(), mode = DEFAULT_TASK_MODE) {
11075
- const tasks = definitions.map(toTaskState);
11076
11531
  return {
11077
- schemaVersion: EXECUTION_SIDECAR_VERSION,
11078
- projectId,
11079
- updatedAt: now.toISOString(),
11080
- executor: { engine: "jioogen" },
11081
- mode,
11082
- counts: summarizeExecutionCounts(tasks),
11083
- tasks
11532
+ version: typeof record.version === "number" ? record.version : BASELINE_VERSION,
11533
+ bundle: typeof record.bundle === "string" ? record.bundle : "",
11534
+ tasks: entries
11084
11535
  };
11085
11536
  }
11086
- function withMode(state, mode) {
11087
- if (state.mode === mode) return state;
11088
- return { ...state, mode };
11537
+ async function writeBaseline(bundleDir, baseline) {
11538
+ const target = baselinePath(bundleDir);
11539
+ await mkdir4(dirname4(target), { recursive: true });
11540
+ await writeFile4(target, `${JSON.stringify(baseline, null, 2)}
11541
+ `, "utf8");
11089
11542
  }
11090
- function assertModeAllowsNewTasks(mode, state, definitions) {
11091
- if (mode !== "executor") return;
11092
- const known = new Set(state.tasks.map((task) => task.ref.toUpperCase()));
11093
- const unknown = definitions.filter((definition) => !known.has(definition.id.toUpperCase())).map((definition) => definition.id);
11094
- if (unknown.length === 0) return;
11095
- throw new Error(
11096
- `Mode executor hanya menjalankan task yang sudah ada; task baru (${unknown.join(", ")}) harus lewat authoring JiooGen atau mode seed.`
11097
- );
11543
+ async function clearBaseline(bundleDir) {
11544
+ await rm4(baselinePath(bundleDir), { force: true });
11545
+ }
11546
+ async function captureTaskBaseline(bundleDir, definition, now = /* @__PURE__ */ new Date()) {
11547
+ const baseline = await readBaseline(bundleDir) ?? {
11548
+ version: BASELINE_VERSION,
11549
+ bundle: await bundleHashOf(bundleDir),
11550
+ tasks: {}
11551
+ };
11552
+ if (baseline.bundle.length === 0) baseline.bundle = await bundleHashOf(bundleDir);
11553
+ const target = await targetHashes(bundleDir, targetFilesFromContent(definition.content));
11554
+ baseline.tasks[definition.id.toUpperCase()] = {
11555
+ at: now.toISOString(),
11556
+ target: target.hashes
11557
+ };
11558
+ await writeBaseline(bundleDir, baseline);
11559
+ }
11560
+ async function updateContractBaseline(bundleDir) {
11561
+ const newBundleHash = await bundleHashOf(bundleDir);
11562
+ const baseline = await readBaseline(bundleDir) ?? {
11563
+ version: BASELINE_VERSION,
11564
+ bundle: newBundleHash,
11565
+ tasks: {}
11566
+ };
11567
+ baseline.bundle = newBundleHash;
11568
+ await writeBaseline(bundleDir, baseline);
11569
+ return newBundleHash;
11570
+ }
11571
+ async function detectDrift(bundleDir, definitions, state, options = {}) {
11572
+ const baseline = await readBaseline(bundleDir);
11573
+ const acknowledged = await readAcknowledged(bundleDir);
11574
+ const bundleDriftAcknowledged = acknowledged !== null && (acknowledged.prd === true || acknowledged.specs === true || acknowledged.tasks === true);
11575
+ const findings = [];
11576
+ const focus = options.focusRef?.toUpperCase();
11577
+ const byId = new Map(definitions.map((entry) => [entry.id.toUpperCase(), entry]));
11578
+ const targetCache = /* @__PURE__ */ new Map();
11579
+ const hashesFor = (definition) => {
11580
+ const key = targetFilesFromContent(definition.content).join("\0");
11581
+ let cached = targetCache.get(key);
11582
+ if (cached === void 0) {
11583
+ cached = targetHashes(bundleDir, targetFilesFromContent(definition.content));
11584
+ targetCache.set(key, cached);
11585
+ }
11586
+ return cached;
11587
+ };
11588
+ if (baseline !== null) {
11589
+ const currentBundle = await bundleHashOf(bundleDir);
11590
+ if (baseline.bundle.length > 0 && currentBundle !== baseline.bundle) {
11591
+ findings.push({
11592
+ code: "BUNDLE_DRIFT",
11593
+ severity: bundleDriftAcknowledged ? "info" : "warn",
11594
+ message: "PRD.md/specs/tasks berubah di disk setelah baseline dibuat. Revisi resmi lewat workspace web (agar specs/tasks ditandai stale), atau kembalikan file itu; jangan diedit lokal diam-diam.",
11595
+ files: []
11596
+ });
11597
+ }
11598
+ for (const task of state.tasks) {
11599
+ const definition = byId.get(task.ref.toUpperCase());
11600
+ if (definition === void 0) continue;
11601
+ const entry = baseline.tasks[task.ref.toUpperCase()];
11602
+ if (entry === void 0) continue;
11603
+ if (task.status !== "todo" && task.status !== "done") continue;
11604
+ const current = await hashesFor(definition);
11605
+ const changed = diffHashes(entry.target, current.hashes);
11606
+ if (changed.length === 0) continue;
11607
+ findings.push({
11608
+ code: task.status === "todo" ? "OUT_OF_BAND_CHANGES" : "MODIFIED_AFTER_DONE",
11609
+ severity: "warn",
11610
+ taskRef: task.ref,
11611
+ message: task.status === "todo" ? `File di scope ${task.ref} berubah padahal task belum dijalankan. Kalau ini hasil alat lain (Figma MCP/AI Studio/editor luar), jalankan \`jioogen task adopt ${task.ref}\` setelah verifikasi; kalau belum selesai, \`jioogen task start ${task.ref}\` dulu.` : `File milik ${task.ref} berubah setelah task selesai. Tinjau diff; bila perubahan disengaja, reset lalu adopsi ulang (\`jioogen task reset ${task.ref}\` \u2192 \`jioogen task adopt ${task.ref}\`).`,
11612
+ files: changed
11613
+ });
11614
+ }
11615
+ }
11616
+ if (options.includeInfo !== false) {
11617
+ findings.push(...await detectPreExisting(definitions, state, baseline, focus, hashesFor));
11618
+ }
11619
+ return findings;
11098
11620
  }
11099
- function mergeTasks(state, definitions) {
11100
- const byId = new Map(definitions.map((task) => [task.id.toUpperCase(), task]));
11101
- const known = new Set(state.tasks.map((task) => task.ref.toUpperCase()));
11102
- let changed = false;
11103
- const existing = state.tasks.map((task) => {
11621
+ async function detectPreExisting(definitions, state, baseline, focus, hashesFor) {
11622
+ const byId = new Map(definitions.map((entry) => [entry.id.toUpperCase(), entry]));
11623
+ const done = /* @__PURE__ */ new Set();
11624
+ for (const task of state.tasks) {
11625
+ if (task.status !== "done") continue;
11104
11626
  const definition = byId.get(task.ref.toUpperCase());
11105
- if (definition === void 0) return task;
11106
- if (sameMetadata(task, definition)) return task;
11107
- changed = true;
11108
- const updated = {
11109
- ...task,
11110
- phase: definition.phase,
11111
- checkpoint: definition.checkpoint
11112
- };
11113
- if (definition.layer !== void 0) updated.layer = definition.layer;
11114
- else delete updated.layer;
11115
- return updated;
11116
- });
11117
- const additions = definitions.filter((task) => !known.has(task.id.toUpperCase())).map(toTaskState);
11118
- if (!changed && additions.length === 0) return state;
11119
- return rebuild(state, [...existing, ...additions], state.current);
11627
+ if (definition === void 0) continue;
11628
+ const current = await hashesFor(definition);
11629
+ for (const path of Object.keys(current.hashes)) done.add(path);
11630
+ }
11631
+ const findings = [];
11632
+ for (const task of state.tasks) {
11633
+ if (task.status !== "todo") continue;
11634
+ const key = task.ref.toUpperCase();
11635
+ if (focus !== void 0 && key !== focus) continue;
11636
+ if (baseline?.tasks[key] !== void 0) continue;
11637
+ const definition = byId.get(key);
11638
+ if (definition === void 0) continue;
11639
+ const current = await hashesFor(definition);
11640
+ const preExisting = Object.keys(current.hashes).filter((path) => !done.has(path));
11641
+ if (preExisting.length === 0) continue;
11642
+ findings.push({
11643
+ code: "PRE_EXISTING_SCOPE",
11644
+ severity: "info",
11645
+ taskRef: task.ref,
11646
+ message: `Scope ${task.ref} sudah berisi file sebelum task dimulai. Bila ini hasil alat luar (Stitch/v0/Lovable/Figma/AI Studio/editor lain) atau tulisan tangan, verifikasi lalu \`jioogen task adopt ${task.ref}\`; bila belum, \`jioogen task start ${task.ref}\`.`,
11647
+ files: preExisting.slice(0, 8)
11648
+ });
11649
+ }
11650
+ return findings;
11120
11651
  }
11121
- function sameMetadata(task, definition) {
11122
- return task.layer === definition.layer && task.phase === definition.phase && task.checkpoint === definition.checkpoint;
11652
+ function formatDrift(finding) {
11653
+ const label = finding.taskRef === void 0 ? finding.code : `${finding.code} ${finding.taskRef}`;
11654
+ const files = finding.files.length === 0 ? "" : ` (${finding.files.slice(0, 4).join(", ")}${finding.files.length > 4 ? ", \u2026" : ""})`;
11655
+ return `${finding.severity === "warn" ? "\u26A0" : "\u2139"} ${label}: ${finding.message}${files}`;
11123
11656
  }
11124
- function withStatus(state, ref, status, options = {}) {
11125
- const now = options.now ?? /* @__PURE__ */ new Date();
11126
- const index = state.tasks.findIndex((task) => task.ref.toUpperCase() === ref.toUpperCase());
11127
- const previous = index === -1 ? void 0 : state.tasks[index];
11128
- if (previous === void 0) {
11129
- throw new Error(`Task ${ref} tidak ada di sidecar. Jalankan \`jioogen task next\` lebih dulu.`);
11657
+ async function targetHashes(bundleDir, patterns) {
11658
+ const files = /* @__PURE__ */ new Set();
11659
+ let truncated = false;
11660
+ for (const pattern of patterns) {
11661
+ const resolved = await expandPattern(bundleDir, pattern);
11662
+ for (const file of resolved) {
11663
+ if (files.size >= MAX_TARGET_FILES) {
11664
+ truncated = true;
11665
+ break;
11666
+ }
11667
+ files.add(file);
11668
+ }
11669
+ if (truncated) break;
11130
11670
  }
11131
- const attempt = status === "in_progress" ? (previous.attempt ?? 0) + 1 : previous.attempt;
11132
- const historyEntry = { status, at: now.toISOString() };
11133
- if (options.note !== void 0 && options.note.length > 0) historyEntry.note = options.note;
11134
- const updated = {
11135
- ...previous,
11136
- status,
11137
- updatedAt: now.toISOString(),
11138
- history: [...previous.history ?? [], historyEntry]
11139
- };
11140
- if (attempt !== void 0) updated.attempt = attempt;
11141
- if (options.note !== void 0) {
11142
- if (options.note.length > 0) updated.note = options.note;
11143
- else delete updated.note;
11671
+ const hashes = {};
11672
+ for (const file of [...files].sort()) {
11673
+ const fingerprint = await fingerprintRelative(bundleDir, file);
11674
+ if (fingerprint !== null) hashes[file] = fingerprint;
11144
11675
  }
11145
- const tasks = state.tasks.map((task, taskIndex) => taskIndex === index ? updated : task);
11146
- const current = status === "in_progress" || status === "verifying" ? {
11147
- ref: updated.ref,
11148
- ...updated.layer !== void 0 ? { layer: updated.layer } : {},
11149
- ...updated.phase !== void 0 ? { phase: updated.phase } : {},
11150
- awaitingCheckpoint: options.awaitingCheckpoint === true
11151
- } : void 0;
11152
- return rebuild(state, tasks, current, now);
11676
+ return { hashes, truncated };
11153
11677
  }
11154
- function setCurrent(state, current) {
11155
- return rebuild(state, state.tasks, current ?? void 0);
11678
+ async function expandPattern(bundleDir, raw) {
11679
+ const pattern = normalizePattern(raw);
11680
+ if (pattern === null) return [];
11681
+ if (!/[*?[]/.test(pattern)) {
11682
+ const info = await statMaybe(join6(bundleDir, pattern));
11683
+ if (info === null) return [];
11684
+ if (info.isDirectory()) {
11685
+ return (await walk(bundleDir, pattern, MAX_TARGET_FILES)).files;
11686
+ }
11687
+ return info.isFile() ? [pattern] : [];
11688
+ }
11689
+ const matcher = globToRegExp(pattern);
11690
+ const start = staticPrefix(pattern);
11691
+ const walked = await walk(bundleDir, start, MAX_TARGET_FILES);
11692
+ return walked.files.filter((file) => matcher.test(file));
11156
11693
  }
11157
- function appendTaskEvidence(state, ref, evidence) {
11158
- const index = state.tasks.findIndex((task2) => task2.ref.toUpperCase() === ref.toUpperCase());
11159
- if (index === -1) return state;
11160
- const previous = state.tasks[index];
11161
- if (previous === void 0) return state;
11162
- const task = {
11163
- ...previous,
11164
- evidence: [...previous.evidence ?? [], evidence]
11165
- };
11166
- const tasks = state.tasks.map((entry, i) => i === index ? task : entry);
11167
- return rebuild(state, tasks, state.current);
11694
+ function normalizePattern(raw) {
11695
+ let value = raw.trim().replace(/^`+|`+$/g, "").replace(/\\/g, "/");
11696
+ value = value.replace(/^\.\//, "").replace(/\/+$/, "");
11697
+ if (value.length === 0 || isAbsolute2(value)) return null;
11698
+ if (value.split("/").includes("..")) return null;
11699
+ return value;
11168
11700
  }
11169
- function setTaskSource(state, ref, source) {
11170
- const index = state.tasks.findIndex((task2) => task2.ref.toUpperCase() === ref.toUpperCase());
11171
- if (index === -1) return state;
11172
- const previous = state.tasks[index];
11173
- if (previous === void 0) return state;
11174
- const task = { ...previous, source };
11175
- const tasks = state.tasks.map((entry, i) => i === index ? task : entry);
11176
- return rebuild(state, tasks, state.current);
11701
+ function staticPrefix(pattern) {
11702
+ const index = pattern.search(/[*?[]/);
11703
+ const head = index === -1 ? pattern : pattern.slice(0, index);
11704
+ const trimmed = head.replace(/\/+$/, "");
11705
+ if (trimmed.length === 0) return "";
11706
+ if (head.endsWith("/")) return trimmed;
11707
+ const slash = trimmed.lastIndexOf("/");
11708
+ return slash === -1 ? "" : trimmed.slice(0, slash);
11177
11709
  }
11178
- function setDesignReview(state, ref, review) {
11179
- const index = state.tasks.findIndex((task2) => task2.ref.toUpperCase() === ref.toUpperCase());
11180
- if (index === -1) return state;
11181
- const previous = state.tasks[index];
11182
- if (previous === void 0) return state;
11183
- const task = {
11184
- ...previous,
11185
- designReview: {
11186
- passed: review.passed,
11187
- findings: [...review.findings ?? []],
11188
- summary: review.summary,
11189
- at: review.at ?? (/* @__PURE__ */ new Date()).toISOString()
11190
- },
11191
- evidence: [
11192
- ...previous.evidence ?? [],
11193
- {
11194
- type: "design_review",
11195
- summary: `${review.passed ? "PASS" : "FAIL"}${review.summary ? ` \u2014 ${review.summary}` : ""}`,
11196
- at: review.at ?? (/* @__PURE__ */ new Date()).toISOString()
11710
+ function globToRegExp(pattern) {
11711
+ let source = "^";
11712
+ for (let index = 0; index < pattern.length; index += 1) {
11713
+ const char = pattern[index] ?? "";
11714
+ if (char === "*") {
11715
+ if (pattern[index + 1] === "*") {
11716
+ if (pattern[index + 2] === "/") {
11717
+ source += "(?:.*/)?";
11718
+ index += 2;
11719
+ } else {
11720
+ source += ".*";
11721
+ index += 1;
11722
+ }
11723
+ } else {
11724
+ source += "[^/]*";
11197
11725
  }
11198
- ]
11199
- };
11200
- const tasks = state.tasks.map((entry, i) => i === index ? task : entry);
11201
- return rebuild(state, tasks, state.current);
11202
- }
11203
- async function writeState(bundleDir, state) {
11204
- const normalized = rebuild(state, state.tasks, state.current);
11205
- const target = sidecarPath(bundleDir);
11206
- await mkdir4(dirname4(target), { recursive: true });
11207
- const temp = `${target}.${process.pid}.${randomUUID()}.tmp`;
11208
- try {
11209
- await writeFile4(temp, `${JSON.stringify(normalized, null, 2)}
11210
- `, "utf8");
11211
- await rename(temp, target);
11212
- } catch (error) {
11213
- await rm4(temp, { force: true }).catch(() => {
11214
- });
11215
- throw error;
11726
+ } else if (char === "?") {
11727
+ source += "[^/]";
11728
+ } else if ("\\^$+.()|{}[]".includes(char)) {
11729
+ source += `\\${char}`;
11730
+ } else {
11731
+ source += char;
11732
+ }
11216
11733
  }
11217
- return normalized;
11218
- }
11219
- function rebuild(state, tasks, current, now = /* @__PURE__ */ new Date()) {
11220
- const next = {
11221
- schemaVersion: state.schemaVersion,
11222
- updatedAt: now.toISOString(),
11223
- counts: summarizeExecutionCounts(tasks),
11224
- tasks
11225
- };
11226
- if (state.projectId !== void 0) next.projectId = state.projectId;
11227
- if (state.executor !== void 0) next.executor = state.executor;
11228
- if (state.mode !== void 0) next.mode = state.mode;
11229
- if (state.plan !== void 0) next.plan = state.plan;
11230
- if (state.events !== void 0) next.events = state.events;
11231
- if (current !== void 0) next.current = current;
11232
- return next;
11734
+ return new RegExp(`${source}$`);
11233
11735
  }
11234
- function toTaskState(task) {
11235
- return {
11236
- ref: task.id,
11237
- status: "todo",
11238
- ...task.layer !== void 0 ? { layer: task.layer } : {},
11239
- phase: task.phase,
11240
- checkpoint: task.checkpoint
11736
+ async function walk(bundleDir, start, limit) {
11737
+ const files = [];
11738
+ let truncated = false;
11739
+ const visit = async (relative2) => {
11740
+ if (truncated) return;
11741
+ let entries;
11742
+ try {
11743
+ entries = await readdir4(relative2.length === 0 ? bundleDir : join6(bundleDir, relative2), {
11744
+ withFileTypes: true
11745
+ });
11746
+ } catch {
11747
+ return;
11748
+ }
11749
+ entries.sort((left, right) => left.name.localeCompare(right.name));
11750
+ for (const entry of entries) {
11751
+ const child = relative2.length === 0 ? entry.name : `${relative2}/${entry.name}`;
11752
+ if (entry.isDirectory()) {
11753
+ if (IGNORED_DIRS.has(entry.name)) continue;
11754
+ if (child === "tasks/.execution") continue;
11755
+ await visit(child);
11756
+ } else if (entry.isFile()) {
11757
+ if (files.length >= limit) {
11758
+ truncated = true;
11759
+ return;
11760
+ }
11761
+ files.push(child);
11762
+ }
11763
+ }
11241
11764
  };
11765
+ await visit(start);
11766
+ return { files, truncated };
11242
11767
  }
11243
- function isMissingFile3(error) {
11244
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
11768
+ async function fingerprintRelative(bundleDir, relative2) {
11769
+ const info = await statMaybe(join6(bundleDir, relative2));
11770
+ if (info === null || !info.isFile()) return null;
11771
+ return `${info.size}:${Math.trunc(info.mtimeMs)}`;
11245
11772
  }
11246
- function isLockBusy(error) {
11247
- return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
11773
+ async function hashRelative(bundleDir, relative2) {
11774
+ const info = await statMaybe(join6(bundleDir, relative2));
11775
+ if (info === null || !info.isFile()) return null;
11776
+ if (info.size > MAX_BUNDLE_FILE_BYTES) return `size:${info.size}`;
11777
+ try {
11778
+ const bytes = await readFile6(join6(bundleDir, relative2));
11779
+ return createHash("sha256").update(bytes).digest("hex");
11780
+ } catch {
11781
+ return null;
11782
+ }
11248
11783
  }
11249
- async function removeStaleLock(target) {
11784
+ async function statMaybe(path) {
11250
11785
  try {
11251
- const info = await stat2(target);
11252
- if (Date.now() - info.mtimeMs < LOCK_STALE_MS) return false;
11253
- await rm4(target, { force: true });
11254
- return true;
11255
- } catch (error) {
11256
- if (isMissingFile3(error)) return true;
11257
- throw error;
11786
+ return await stat3(path);
11787
+ } catch {
11788
+ return null;
11258
11789
  }
11259
11790
  }
11260
- function delay(ms) {
11261
- return new Promise((resolve7) => setTimeout(resolve7, ms));
11791
+ function diffHashes(before, after) {
11792
+ const changed = /* @__PURE__ */ new Set();
11793
+ for (const [path, hash] of Object.entries(before)) {
11794
+ if (after[path] !== hash) changed.add(path);
11795
+ }
11796
+ for (const path of Object.keys(after)) {
11797
+ if (!(path in before)) changed.add(path);
11798
+ }
11799
+ return [...changed].sort();
11800
+ }
11801
+ async function bundleHashOf(bundleDir) {
11802
+ const files = [];
11803
+ for (const name of ["PRD.md", "traceability.md"]) {
11804
+ const info = await statMaybe(join6(bundleDir, name));
11805
+ if (info?.isFile()) files.push(name);
11806
+ }
11807
+ for (const directory of ["specs", "tasks"]) {
11808
+ const walked = await walk(bundleDir, directory, MAX_TARGET_FILES);
11809
+ for (const file of walked.files) {
11810
+ if (file.startsWith("tasks/.execution/")) continue;
11811
+ if (IGNORED_TOP_FILES.has(file)) continue;
11812
+ if (!file.toLowerCase().endsWith(".md")) continue;
11813
+ files.push(file);
11814
+ }
11815
+ }
11816
+ const lines = [];
11817
+ for (const file of files.sort()) {
11818
+ const hash = await hashRelative(bundleDir, file);
11819
+ if (hash !== null) lines.push(`${file}\0${hash}`);
11820
+ }
11821
+ return createHash("sha256").update(lines.join("\n")).digest("hex");
11262
11822
  }
11263
11823
 
11264
11824
  // src/skills.ts
11265
11825
  import { createHash as createHash2 } from "node:crypto";
11266
- import { cp as cp2, mkdir as mkdir5, readdir as readdir5, readFile as readFile7, rm as rm5, stat as stat3, writeFile as writeFile5 } from "node:fs/promises";
11826
+ import { cp as cp2, mkdir as mkdir5, readdir as readdir5, readFile as readFile7, rename as rename2, rm as rm5, stat as stat4, writeFile as writeFile5 } from "node:fs/promises";
11267
11827
  import { homedir as homedir2 } from "node:os";
11268
11828
  import { dirname as dirname5, join as join7, resolve as resolve3 } from "node:path";
11269
11829
  import { fileURLToPath as fileURLToPath2 } from "node:url";
@@ -11282,6 +11842,7 @@ var SKILL_PACKS = {
11282
11842
  "backend-rules": []
11283
11843
  };
11284
11844
  var HARNESS_MANIFEST_PATH = ".jioogen/harness.json";
11845
+ var CUSTOM_SKILLS_DIR = ".jioogen/custom/skills";
11285
11846
  var HARNESS_SCHEMA_VERSION = 1;
11286
11847
  var FRONTEND_MOCK_LAYER_RE = /^[ \t]*(?:[-*][ \t]+)?layer[ \t]*[:=][ \t]*[`"']?frontend_mock\b/im;
11287
11848
  var MARKER_PREFIX = "<!-- jioogen-execution-skill:";
@@ -11344,6 +11905,17 @@ var JIOOGEN_AGENTS_MD = `${MARKER}
11344
11905
  - Dilarang pindah task sebelum task aktif \`done\` atau \`failed\`.
11345
11906
  - Jangan mengarang fitur/endpoint/kolom yang tidak ada di \`PRD.md\`/\`specs/\`.
11346
11907
  - Jangan mengubah \`PRD.md\` atau \`specs/\`; itu kontrak, bukan hasil eksekusi.
11908
+ - **Warning CLI \u2260 BLOCKER, jangan loop.** Warning seperti ID task duplikat atau
11909
+ drift bukan alasan menghentikan atau mengulang-ulang eksekusi: baca pesannya,
11910
+ tandai kondisi di note (\`task start/complete --note "...id duplikat, default pakai
11911
+ yang pertama..."\`), lalu lanjutkan task. Berhenti HANYA pada hal yang benar-benar
11912
+ menghentikan Acceptance Criteria atau melanggar kontrak. Satu error CLI yang sama
11913
+ tidak boleh dijalankan ulang lebih dari sekali.
11914
+ - **Project dihapus = dead end, jangan usahakan lagi.** Bila CLI melaporkan project
11915
+ tidak ditemukan/dihapus dan link lokal sudah dilepas otomatis, direktori ini tidak
11916
+ terikat project apa pun: BERHENTI (tandai \`fail\`/catat di note), jangan ulangi
11917
+ perintah, jangan coba bind-paksa, jangan buat file baru. Laporkan ke user bahwa
11918
+ bundle sudah dilepas dan bisa di-pull ulang secara manual bila memang ingin lanjut.
11347
11919
 
11348
11920
  ## 2. Alur per giliran
11349
11921
  1. \`npx jioogen task next\` \u2014 baca blok **TASK AKTIF**, **BREAKDOWN WAJIB**, + isi file task.
@@ -11356,16 +11928,21 @@ var JIOOGEN_AGENTS_MD = `${MARKER}
11356
11928
 
11357
11929
  ## 2b. Pekerjaan yang dibangun di luar harness
11358
11930
 
11359
- Kalau sebuah layar/komponen sudah dibuat di alat lain (Figma MCP, Google AI Studio,
11360
- editor lain) sebelum task dijalankan, jangan pura-pura mengerjakannya:
11931
+ Kalau sebuah layar/komponen sudah dibuat di luar harness (alat UI generator seperti
11932
+ Stitch/v0/Lovable/Bolt/screenshot-to-code, AI studio, plugin desain, atau tulisan
11933
+ tangan) sebelum task dijalankan, jangan pura-pura mengerjakannya:
11361
11934
  - \`npx jioogen task next\`/\`npx jioogen doctor\` menandai \`PRE_EXISTING_SCOPE\` atau
11362
11935
  \`OUT_OF_BAND_CHANGES\`.
11936
+ - Petakan hasilnya ke \`targetFiles\` task aktif (framework apa pun). File baru hanya
11937
+ di dalam area itu.
11363
11938
  - Verifikasi hasilnya lalu \`npx jioogen task adopt <ref> --note "<alat>"\` (task UI:
11364
11939
  tambahkan \`--visual "<catatan>"\`). Command itu menjalankan \`verificationCommand\`
11365
11940
  dan mencatat \`source: user\` + bukti adopsi di sidecar.
11366
11941
  - Kalau hasil alat itu menyimpang dari \`specs/\`/\`CONTRACT-XXX\`, STOP: revisi
11367
11942
  kontrak lewat workspace web, jangan mengadopsi diam-diam.
11368
11943
  - Jangan edit \`PRD.md\`/\`specs/\` lokal; \`BUNDLE_DRIFT\` akan muncul.
11944
+ - Port dev server jangan ditebak: JiooGen/app lain bisa sudah memakainya. Pakai port
11945
+ bebas (mis. \`PORT=3001\`), catat di note; jangan ubah kontrak/spec demi port.
11369
11946
 
11370
11947
  ## 3. Batas scope
11371
11948
  - Edit **hanya** file/direktori/glob di \`targetFiles\` task aktif. Jangan melebar.
@@ -11418,13 +11995,19 @@ diturunkan dari AC, subfeature, flow/step, lifecycle, engine, UI states,
11418
11995
  - Kalau test belum ada, task belum selesai.
11419
11996
  - Bukti verifikasi dicatat CLI lewat \`npx jioogen task verify <ref>\`; \`task complete\` menolak tanpa bukti exit 0.
11420
11997
 
11421
- ## 5. Checkpoint
11422
- Berhenti dan minta konfirmasi user bila task berikutnya berpindah layer, nomor
11423
- \`phase\` naik, task bertanda \`checkpoint: true\`, atau task tergolong berisiko
11424
- (migrasi/schema/akses/izin/integrasi-eksternal/secret/deploy/infra). Jangan lanjut
11425
- sebelum user memutuskan. Setelah user memutuskan, jalankan salah satu:
11426
- \`npx jioogen review --approve\`, \`npx jioogen review --request-changes "<teks>"\`,
11427
- atau \`npx jioogen review --stop\`, lalu \`npx jioogen sync\`.
11998
+ ## 5. Berhenti sebentar untuk konfirmasi
11999
+ Berhenti setelah satu bagian besar selesai, sebelum beralih ke bagian berikutnya,
12000
+ atau sebelum pekerjaan sensitif (data, akses, integrasi eksternal, rahasia,
12001
+ deploy/infra). Jangan pakai istilah teknis saat bertanya. Tanyakan dengan bahasa
12002
+ sehari-hari: "Bagian ini selesai. Silakan cek hasilnya. Mau lanjut, perbaiki dulu,
12003
+ atau batalkan dulu?"
12004
+ - **Lanjut** \u2014 kerjakan bagian berikutnya.
12005
+ - **Perbaiki dulu** \u2014 dengarkan bagian yang salah, perbaiki, lalu tanya lagi.
12006
+ - **Batalkan dulu** \u2014 jangan lanjut; laporkan kondisi saat ini.
12007
+
12008
+ Setelah user memilih, catat di sistem dengan \`npx jioogen review --approve\`,
12009
+ \`--request-changes "<teks>"\`, atau \`--stop\`, lalu \`npx jioogen sync\`. Jangan
12010
+ menampilkan perintah itu sebagai pertanyaan ke user.
11428
12011
 
11429
12012
  ## 6. Skill eksekusi
11430
12013
  Baca skill \`${EXECUTION_SKILL_NAME}\` di awal prompt
@@ -11493,16 +12076,22 @@ atas ide, refactor, perbaikan, atau fitur lain.
11493
12076
 
11494
12077
  ## 2b. Pekerjaan yang dibangun di luar harness
11495
12078
 
11496
- Kalau sebuah layar/komponen sudah dibuat di alat lain (Figma MCP, Google AI Studio,
11497
- editor lain) sebelum task dijalankan, jangan pura-pura mengerjakannya:
12079
+ Kalau sebuah layar/komponen sudah dibuat di luar harness \u2014 alat UI generator
12080
+ (Stitch, v0, Lovable, Bolt, screenshot-to-code, dsb.), AI studio, plugin desain,
12081
+ atau ditulis tangan \u2014 sebelum task dijalankan, jangan pura-pura mengerjakannya:
11498
12082
  - \`npx jioogen task next\`/\`npx jioogen doctor\` menandai \`PRE_EXISTING_SCOPE\` atau
11499
12083
  \`OUT_OF_BAND_CHANGES\`.
12084
+ - Petakan hasilnya ke \`targetFiles\` task aktif, framework apa pun (HTML/CSS, React,
12085
+ Vue, Svelte, dsb.). File baru hanya di dalam area itu.
11500
12086
  - Verifikasi hasilnya lalu \`npx jioogen task adopt <ref> --note "<alat>"\` (task UI:
11501
12087
  tambahkan \`--visual "<catatan>"\`). Command itu menjalankan \`verificationCommand\`
11502
12088
  dan mencatat \`source: user\` + bukti adopsi di sidecar.
11503
12089
  - Kalau hasil alat itu menyimpang dari \`specs/\`/\`CONTRACT-XXX\`, STOP: revisi
11504
12090
  kontrak lewat workspace web, jangan mengadopsi diam-diam.
11505
12091
  - Jangan edit \`PRD.md\`/\`specs/\` lokal; \`BUNDLE_DRIFT\` akan muncul.
12092
+ - **Port dev server jangan ditebak.** JiooGen/monitor atau app lain bisa sudah
12093
+ memakai port default; pakai port bebas (mis. \`PORT=3001\`), catat di note, dan
12094
+ jangan mengubah kontrak/spec demi port.
11506
12095
 
11507
12096
  ## 3. Batas scope
11508
12097
 
@@ -11572,6 +12161,24 @@ Tulis kode **minimum** yang menyelesaikan task. Gemuk = gagal review.
11572
12161
 
11573
12162
  Tanya: "Apakah senior engineer bilang ini overcomplicated?" Bila ya, sederhanakan.
11574
12163
 
12164
+ ## 3f. Design Token & design.md (kontekstual)
12165
+
12166
+ - Baca \`specs/design.md\` bila ada (design contract: token/visual). User boleh
12167
+ mengeditnya antar-sesi; agent **reuse/extend**, **jangan menimpa** edit user saat
12168
+ task berjalan. Preferensi tambahan user di \`.jioogen/custom/design/\` (additive).
12169
+ - Inspeksi token/theme/CSS variables/Tailwind/komponen/design reference yang sudah ada
12170
+ (specs/design.md, custom/design/, docs/DESIGN.md, specs, codebase). Reuse dulu;
12171
+ token baru hanya untuk nilai visual berulang yang nyata; jangan hardcode nilai yang
12172
+ sudah punya token; jangan membuat design system baru atau mengganti styling di luar
12173
+ scope. Produk tanpa UI: \`N/A \u2014 tidak ada surface visual\`.
12174
+ - Auto-generate \`specs/design.md\` bila belum ada & produk ber-surface UI (pada scaffold
12175
+ task phase 1 FE), dari ui-ux-pro-max + impeccable (+ gamedev skills eksternal untuk
12176
+ produk game). Untuk produk tanpa UI: token minimal (spacing/typography/neutral) atau
12177
+ N/A beralasan. Jika sudah ada (user-provided), merge: preferensi user = constraint,
12178
+ skill isi gap; jangan timpa.
12179
+ - Task UI wajib \`designTokens\` (\`reuse\`/\`extend\`/\`minimal\`/\`N/A\` beralasan) dan
12180
+ AC menolak hardcoded value bila token tersedia.
12181
+
11575
12182
  ## 4. Verifikasi jujur (jangan dipalsukan)
11576
12183
 
11577
12184
  - Pakai test runner yang dideklarasikan di \`specs/\` atau dibuat task scaffold.
@@ -11584,18 +12191,21 @@ Tanya: "Apakah senior engineer bilang ini overcomplicated?" Bila ya, sederhanaka
11584
12191
  - Task \`layer: verification\` menjalankan semua \`verificationCommand\`, smoke test
11585
12192
  route/navigasi, cek UI states + responsive, dan verifikasi AC.
11586
12193
 
11587
- ## 5. Checkpoint
12194
+ ## 5. Berhenti sebentar untuk konfirmasi
11588
12195
 
11589
- Berhenti dan minta konfirmasi user bila:
11590
- - task berikutnya berpindah \`layer\` (mis. \`frontend_mock\` \u2192 \`backend_api\`/\`database\`),
11591
- - nomor \`phase\` naik,
11592
- - task bertanda \`checkpoint: true\`,
11593
- - task tergolong berisiko (migrasi/schema/akses/izin/integrasi-eksternal/secret/deploy/infra).
12196
+ Berhenti setelah satu bagian besar selesai, sebelum beralih ke bagian berikutnya,
12197
+ atau sebelum pekerjaan sensitif (data, akses, integrasi eksternal, rahasia,
12198
+ deploy/infra). Jangan pakai istilah teknis saat bertanya. Tanyakan dengan bahasa
12199
+ sehari-hari: "Bagian ini selesai. Silakan cek hasilnya. Mau lanjut, perbaiki dulu,
12200
+ atau batalkan dulu?"
12201
+ - **Lanjut** \u2014 kerjakan bagian berikutnya.
12202
+ - **Perbaiki dulu** \u2014 dengarkan bagian yang salah, perbaiki, lalu tanya lagi.
12203
+ - **Batalkan dulu** \u2014 jangan lanjut; laporkan kondisi saat ini.
11594
12204
 
11595
- Jangan lanjut sebelum user memutuskan. Set \`current.awaitingCheckpoint = true\` di
11596
- sidecar saat berhenti, lalu setelah user memutuskan jalankan
11597
- \`npx jioogen review --approve\` / \`--request-changes "<teks>"\` / \`--stop\`,
11598
- diikuti \`npx jioogen sync\`.
12205
+ Set \`current.awaitingCheckpoint = true\` di sidecar saat berhenti. Setelah user
12206
+ memilih, catat di sistem dengan \`npx jioogen review --approve\`,
12207
+ \`--request-changes "<teks>"\`, atau \`--stop\`, lalu \`npx jioogen sync\`. Jangan
12208
+ menampilkan perintah itu sebagai pertanyaan ke user.
11599
12209
 
11600
12210
  ## 6. Larangan ringkas
11601
12211
 
@@ -11604,6 +12214,12 @@ diikuti \`npx jioogen sync\`.
11604
12214
  - Jangan menunda entrypoint/scaffold ke fase backend.
11605
12215
  - Jangan mengganti ownership/consistency boundary tanpa memperbarui spec.
11606
12216
  - Jangan menandai \`done\` sebelum verification exit 0.
12217
+ - **Jangan loop pada warning CLI.** Warning (mis. ID task duplikat, drift,
12218
+ item breakdown belum dicentang) bukan BLOCKER: tandai di note, lanjut.
12219
+ Perintah CLI yang sama tidak boleh diulang demi hasil yang sama; kalau tetap
12220
+ gagal setelah 1 ulangan, tandai \`fail\` + alasan singkat.
12221
+ - **Project dihapus = dead end.** CLI sudah melepas link otomatis; jangan ulangi
12222
+ perintah, jangan coba re-bind paksa; berhenti dan lapor.
11607
12223
  - Jangan diam-diam lanjut setelah gagal; tandai \`fail\` + alasan singkat.
11608
12224
  - Jangan membuat task/laporan baru untuk micro-fix; cukup catat di note task aktif.
11609
12225
 
@@ -11639,7 +12255,7 @@ function isMissingFile4(error) {
11639
12255
  }
11640
12256
  async function isFile(path) {
11641
12257
  try {
11642
- return (await stat3(path)).isFile();
12258
+ return (await stat4(path)).isFile();
11643
12259
  } catch (error) {
11644
12260
  if (isMissingFile4(error)) return false;
11645
12261
  throw error;
@@ -11647,7 +12263,7 @@ async function isFile(path) {
11647
12263
  }
11648
12264
  async function isDirectory(path) {
11649
12265
  try {
11650
- return (await stat3(path)).isDirectory();
12266
+ return (await stat4(path)).isDirectory();
11651
12267
  } catch (error) {
11652
12268
  if (isMissingFile4(error)) return false;
11653
12269
  throw error;
@@ -11687,7 +12303,7 @@ function parsePack(value) {
11687
12303
  }
11688
12304
  function parseHarnessManifest(value) {
11689
12305
  if (!isRecord2(value)) return null;
11690
- const { schemaVersion, productKind, packs, updatedAt } = value;
12306
+ const { schemaVersion, productKind, packs, custom: custom2, updatedAt } = value;
11691
12307
  if (schemaVersion !== HARNESS_SCHEMA_VERSION) return null;
11692
12308
  if (!isProductKind(productKind)) return null;
11693
12309
  if (!Array.isArray(packs)) return null;
@@ -11697,8 +12313,22 @@ function parseHarnessManifest(value) {
11697
12313
  if (parsed === null) return null;
11698
12314
  parsedPacks.push(parsed);
11699
12315
  }
12316
+ const parsedCustom = [];
12317
+ if (Array.isArray(custom2)) {
12318
+ for (const entry of custom2) {
12319
+ const parsed = parseSkillEntry(entry);
12320
+ if (parsed === null) return null;
12321
+ parsedCustom.push(parsed);
12322
+ }
12323
+ }
11700
12324
  if (typeof updatedAt !== "string" || updatedAt.length === 0) return null;
11701
- return { schemaVersion: HARNESS_SCHEMA_VERSION, productKind, packs: parsedPacks, updatedAt };
12325
+ return {
12326
+ schemaVersion: HARNESS_SCHEMA_VERSION,
12327
+ productKind,
12328
+ packs: parsedPacks,
12329
+ custom: parsedCustom,
12330
+ updatedAt
12331
+ };
11702
12332
  }
11703
12333
  async function readHarnessManifest(bundleDir) {
11704
12334
  const path = join7(resolve3(bundleDir), HARNESS_MANIFEST_PATH);
@@ -11738,8 +12368,15 @@ async function detectProductKind(bundleDir) {
11738
12368
  }
11739
12369
  return "non-ui";
11740
12370
  }
11741
- function packsForProduct(productKind) {
11742
- return productKind === "ui" ? ["baseline", "ui-quality", "backend-rules"] : ["baseline", "backend-rules"];
12371
+ function packsForProduct(productKind, uiQuality = "auto") {
12372
+ const packs = productKind === "ui" ? ["baseline", "ui-quality", "backend-rules"] : ["baseline", "backend-rules"];
12373
+ if (uiQuality === "on" && !packs.includes("ui-quality")) {
12374
+ return [...packs, "ui-quality"];
12375
+ }
12376
+ if (uiQuality === "off") {
12377
+ return packs.filter((pack) => pack !== "ui-quality");
12378
+ }
12379
+ return packs;
11743
12380
  }
11744
12381
  function cliPackageRoot2() {
11745
12382
  return resolve3(dirname5(fileURLToPath2(import.meta.url)), "..");
@@ -11836,8 +12473,85 @@ async function provisionPack(root, pack, prior, written, preserved) {
11836
12473
  }
11837
12474
  return { name: pack, skills, missing };
11838
12475
  }
11839
- function sameManifestBody(manifest, productKind, packs) {
11840
- return manifest.productKind === productKind && JSON.stringify(manifest.packs) === JSON.stringify(packs);
12476
+ async function provisionCustomSkills(root, prior) {
12477
+ const written = [];
12478
+ const preserved = [];
12479
+ const custom2 = [];
12480
+ const conflicts = [];
12481
+ const removed = [];
12482
+ const sources = /* @__PURE__ */ new Set();
12483
+ const base = join7(root, CUSTOM_SKILLS_DIR);
12484
+ const reserved = /* @__PURE__ */ new Set([EXECUTION_SKILL_NAME, ...Object.values(SKILL_PACKS).flat()]);
12485
+ let entries = [];
12486
+ try {
12487
+ entries = await readdir5(base, { withFileTypes: true });
12488
+ } catch (error) {
12489
+ if (!isMissingFile4(error)) throw error;
12490
+ }
12491
+ const names = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
12492
+ for (const name of names) {
12493
+ const source = join7(base, name);
12494
+ if (!await isFile(join7(source, "SKILL.md"))) continue;
12495
+ sources.add(name);
12496
+ if (reserved.has(name)) {
12497
+ conflicts.push(name);
12498
+ continue;
12499
+ }
12500
+ const sha256 = await hashSkillDirectory(source);
12501
+ const previous = prior.find((entry) => entry.name === name);
12502
+ let owned = previous !== void 0;
12503
+ for (const dir of AGENT_SKILL_DIRS) {
12504
+ const targetDir = join7(root, dir, name);
12505
+ const skillMd = join7(targetDir, "SKILL.md");
12506
+ if (await isFile(skillMd)) {
12507
+ const targetHash = await hashSkillDirectory(targetDir);
12508
+ if (previous === void 0) {
12509
+ preserved.push(`${dir}/${name}/SKILL.md`);
12510
+ continue;
12511
+ }
12512
+ if (targetHash === sha256) {
12513
+ owned = true;
12514
+ continue;
12515
+ }
12516
+ if (targetHash === previous.sha256) {
12517
+ await replaceDirectory(source, targetDir);
12518
+ written.push(`${dir}/${name}/SKILL.md`);
12519
+ owned = true;
12520
+ continue;
12521
+ }
12522
+ preserved.push(`${dir}/${name}/SKILL.md`);
12523
+ continue;
12524
+ }
12525
+ await replaceDirectory(source, targetDir);
12526
+ written.push(`${dir}/${name}/SKILL.md`);
12527
+ owned = true;
12528
+ }
12529
+ if (owned) {
12530
+ custom2.push({ name, source: `custom/${name}`, sha256 });
12531
+ } else if (previous !== void 0) {
12532
+ custom2.push(previous);
12533
+ }
12534
+ }
12535
+ for (const entry of prior) {
12536
+ if (sources.has(entry.name) && !reserved.has(entry.name)) continue;
12537
+ if (reserved.has(entry.name)) continue;
12538
+ for (const dir of AGENT_SKILL_DIRS) {
12539
+ const targetDir = join7(root, dir, entry.name);
12540
+ const skillMd = join7(targetDir, "SKILL.md");
12541
+ if (!await isFile(skillMd)) continue;
12542
+ const targetHash = await hashSkillDirectory(targetDir);
12543
+ if (targetHash !== entry.sha256) {
12544
+ preserved.push(`${dir}/${entry.name}/SKILL.md`);
12545
+ continue;
12546
+ }
12547
+ await rm5(targetDir, { recursive: true, force: true });
12548
+ removed.push(`${dir}/${entry.name}/SKILL.md`);
12549
+ }
12550
+ }
12551
+ return { custom: custom2, conflicts, removed, written, preserved };
12552
+ }
12553
+ function sameManifestBody(manifest, productKind, packs, custom2) {
12554
+ return manifest.productKind === productKind && JSON.stringify(manifest.packs) === JSON.stringify(packs) && JSON.stringify(manifest.custom) === JSON.stringify(custom2);
11841
12555
  }
11842
12556
  async function provisionSkillPacks(bundleDir, packNames, productKind) {
11843
12557
  const root = resolve3(bundleDir);
@@ -11849,20 +12563,27 @@ async function provisionSkillPacks(bundleDir, packNames, productKind) {
11849
12563
  const prior = existing?.packs.find((entry) => entry.name === pack);
11850
12564
  packs.push(await provisionPack(root, pack, prior, written, preserved));
11851
12565
  }
11852
- const changed = existing === null || !sameManifestBody(existing, productKind, packs);
12566
+ const custom2 = await provisionCustomSkills(root, existing?.custom ?? []);
12567
+ written.push(...custom2.written);
12568
+ preserved.push(...custom2.preserved);
12569
+ const changed = existing === null || !sameManifestBody(existing, productKind, packs, custom2.custom);
11853
12570
  const manifest = {
11854
12571
  schemaVersion: HARNESS_SCHEMA_VERSION,
11855
12572
  productKind,
11856
12573
  packs,
12574
+ custom: custom2.custom,
11857
12575
  updatedAt: changed ? (/* @__PURE__ */ new Date()).toISOString() : existing?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
11858
12576
  };
11859
12577
  const harnessPath = await writeHarnessManifest(root, manifest);
11860
12578
  return {
11861
12579
  written,
11862
12580
  preserved,
12581
+ removed: custom2.removed,
11863
12582
  productKind,
11864
12583
  packs,
12584
+ custom: custom2.custom,
11865
12585
  missing: packs.flatMap((pack) => pack.missing),
12586
+ conflicts: custom2.conflicts,
11866
12587
  harnessPath
11867
12588
  };
11868
12589
  }
@@ -11906,20 +12627,35 @@ async function installAgentSkills(bundleDir, options = {}) {
11906
12627
  if (gitignore !== null) written.push(gitignore);
11907
12628
  written.push(...await ensureCustomScaffold(root));
11908
12629
  if (options.noSkills === true) {
11909
- return { written, preserved, productKind, packs: [], missing: [], harnessPath };
12630
+ return {
12631
+ written,
12632
+ preserved,
12633
+ removed: [],
12634
+ productKind,
12635
+ packs: [],
12636
+ custom: [],
12637
+ missing: [],
12638
+ conflicts: [],
12639
+ harnessPath
12640
+ };
11910
12641
  }
12642
+ const uiQuality = options.uiQuality ?? await readUiQuality(root);
11911
12643
  const current = await readHarnessManifest(root);
12644
+ const priorPacks = current?.packs.map((pack) => pack.name) ?? [];
11912
12645
  const requested = options.packs ?? packNamesInCanonicalOrder([
11913
- ...packsForProduct(productKind),
11914
- ...current?.packs.map((pack) => pack.name) ?? []
12646
+ ...packsForProduct(productKind, uiQuality),
12647
+ ...priorPacks.filter((pack) => !(uiQuality === "off" && pack === "ui-quality"))
11915
12648
  ]);
11916
12649
  const provision = await provisionSkillPacks(root, requested, productKind);
11917
12650
  return {
11918
12651
  written: [...written, ...provision.written],
11919
12652
  preserved: [...preserved, ...provision.preserved],
12653
+ removed: provision.removed,
11920
12654
  productKind,
11921
12655
  packs: provision.packs,
12656
+ custom: provision.custom,
11922
12657
  missing: provision.missing,
12658
+ conflicts: provision.conflicts,
11923
12659
  harnessPath: provision.harnessPath
11924
12660
  };
11925
12661
  }
@@ -11948,6 +12684,34 @@ async function updateSkillPacks(bundleDir) {
11948
12684
  existing.productKind
11949
12685
  );
11950
12686
  }
12687
+ async function removeExecutionContract(bundleDir) {
12688
+ const root = resolve3(bundleDir);
12689
+ const removed = [];
12690
+ const preserved = [];
12691
+ const agentsPath = join7(root, "AGENTS.md");
12692
+ const existingAgents = await readFileSafe(agentsPath);
12693
+ if (existingAgents !== void 0) {
12694
+ if (existingAgents.includes(MARKER_PREFIX)) {
12695
+ await rm5(agentsPath, { force: true });
12696
+ removed.push("AGENTS.md");
12697
+ } else {
12698
+ preserved.push("AGENTS.md");
12699
+ }
12700
+ }
12701
+ for (const dir of AGENT_SKILL_DIRS) {
12702
+ const target = join7(root, dir, EXECUTION_SKILL_NAME);
12703
+ try {
12704
+ const info = await stat4(target);
12705
+ if (info.isDirectory()) {
12706
+ await rm5(target, { recursive: true, force: true });
12707
+ removed.push(`${dir}/${EXECUTION_SKILL_NAME}`);
12708
+ }
12709
+ } catch (error) {
12710
+ if (!isMissingFile4(error)) throw error;
12711
+ }
12712
+ }
12713
+ return { removed, preserved };
12714
+ }
11951
12715
  async function removeSkillPack(bundleDir, pack) {
11952
12716
  const root = resolve3(bundleDir);
11953
12717
  const existing = await readHarnessManifest(root);
@@ -11979,6 +12743,79 @@ async function removeSkillPack(bundleDir, pack) {
11979
12743
  });
11980
12744
  return { removed, preserved, packs };
11981
12745
  }
12746
+ async function restoreSkillPack(bundleDir, packArgument) {
12747
+ const root = resolve3(bundleDir);
12748
+ const packNames = parseSkillPackArgument(packArgument);
12749
+ if (packNames === null) {
12750
+ throw new Error("Pack tidak dikenal. Pilih: baseline | ui-quality | backend-rules | all.");
12751
+ }
12752
+ const existing = await readHarnessManifest(root);
12753
+ const productKind = existing?.productKind ?? await detectProductKind(root);
12754
+ const updatedPacks = existing?.packs ? [...existing.packs] : [];
12755
+ const restored = [];
12756
+ const missing = [];
12757
+ for (const pack of packNames) {
12758
+ const skills = [];
12759
+ const packMissing = [];
12760
+ for (const name of SKILL_PACKS[pack]) {
12761
+ const source = await resolveSkillSource(pack, name);
12762
+ if (source === null) {
12763
+ packMissing.push(name);
12764
+ missing.push(name);
12765
+ continue;
12766
+ }
12767
+ const sha256 = await hashSkillDirectory(source);
12768
+ for (const dir of AGENT_SKILL_DIRS) {
12769
+ const targetDir = join7(root, dir, name);
12770
+ await replaceDirectory(source, targetDir);
12771
+ restored.push(`${dir}/${name}`);
12772
+ }
12773
+ skills.push({ name, source: `${pack}/${name}`, sha256 });
12774
+ }
12775
+ const manifestEntry = { name: pack, skills, missing: packMissing };
12776
+ const index = updatedPacks.findIndex((candidate) => candidate.name === pack);
12777
+ if (index >= 0) updatedPacks[index] = manifestEntry;
12778
+ else updatedPacks.push(manifestEntry);
12779
+ }
12780
+ const orderedNames = packNamesInCanonicalOrder(updatedPacks.map((pack) => pack.name));
12781
+ const finalPacks = orderedNames.map((name) => updatedPacks.find((pack) => pack.name === name)).filter((pack) => pack !== void 0);
12782
+ await writeHarnessManifest(root, {
12783
+ schemaVersion: HARNESS_SCHEMA_VERSION,
12784
+ productKind,
12785
+ packs: finalPacks,
12786
+ custom: existing?.custom ?? [],
12787
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
12788
+ });
12789
+ return { restored, packs: finalPacks, missing };
12790
+ }
12791
+ async function disableSkill(bundleDir, name) {
12792
+ const root = resolve3(bundleDir);
12793
+ const disabled = [];
12794
+ for (const dir of AGENT_SKILL_DIRS) {
12795
+ const targetDir = join7(root, dir, name);
12796
+ const disabledDir = `${targetDir}.disabled`;
12797
+ if (!await isDirectory(targetDir)) continue;
12798
+ if (await isDirectory(disabledDir)) await rm5(disabledDir, { recursive: true, force: true });
12799
+ await rename2(targetDir, disabledDir);
12800
+ disabled.push(`${dir}/${name}`);
12801
+ }
12802
+ return { disabled };
12803
+ }
12804
+ async function enableSkill(bundleDir, name) {
12805
+ const root = resolve3(bundleDir);
12806
+ const enabled = [];
12807
+ for (const dir of AGENT_SKILL_DIRS) {
12808
+ const targetDir = join7(root, dir, name);
12809
+ const disabledDir = `${targetDir}.disabled`;
12810
+ if (!await isDirectory(disabledDir)) continue;
12811
+ if (await isDirectory(targetDir)) await rm5(disabledDir, { recursive: true, force: true });
12812
+ else {
12813
+ await rename2(disabledDir, targetDir);
12814
+ enabled.push(`${dir}/${name}`);
12815
+ }
12816
+ }
12817
+ return { enabled };
12818
+ }
11982
12819
  function skillsDisabled(options) {
11983
12820
  if (options.noSkills === true) return true;
11984
12821
  const value = process.env.JIOOGEN_NO_SKILLS?.trim().toLowerCase();
@@ -12135,14 +12972,14 @@ async function checkProject(deps, credentials, projectId) {
12135
12972
  }
12136
12973
  async function isFile2(path) {
12137
12974
  try {
12138
- return (await stat4(path)).isFile();
12975
+ return (await stat5(path)).isFile();
12139
12976
  } catch {
12140
12977
  return false;
12141
12978
  }
12142
12979
  }
12143
12980
  async function isDirectory2(path) {
12144
12981
  try {
12145
- return (await stat4(path)).isDirectory();
12982
+ return (await stat5(path)).isDirectory();
12146
12983
  } catch {
12147
12984
  return false;
12148
12985
  }
@@ -12264,7 +13101,7 @@ async function checkLock(bundleDir) {
12264
13101
  const target = lockPath(bundleDir);
12265
13102
  let info;
12266
13103
  try {
12267
- info = await stat4(target);
13104
+ info = await stat5(target);
12268
13105
  } catch (error) {
12269
13106
  if (isMissingFile5(error)) {
12270
13107
  return makeCheck("lock", "pass", "Tidak ada lock; sidecar bebas ditulis.");
@@ -12396,6 +13233,7 @@ async function checkSkillPacks(bundleDir) {
12396
13233
  );
12397
13234
  }
12398
13235
  var CAP_ID_RE = /\bCAP-[A-Z0-9-]+\b/g;
13236
+ var CAP_PLACEHOLDER_RE = /^CAP-X+$/;
12399
13237
  var TASK_CAP_RE = /^\s*cap:\s*(CAP-[A-Z0-9-]+)/im;
12400
13238
  async function collectMarkdownFiles2(root, prefix = "") {
12401
13239
  const dir = join8(root, prefix);
@@ -12425,7 +13263,11 @@ async function checkCapabilityCoverage(bundleDir) {
12425
13263
  const specCaps = /* @__PURE__ */ new Set();
12426
13264
  for (const relative2 of await collectMarkdownFiles2(bundleDir, "specs")) {
12427
13265
  const content = await readFile8(join8(bundleDir, relative2), "utf8");
12428
- for (const match of content.matchAll(CAP_ID_RE)) specCaps.add(match[0].toUpperCase());
13266
+ for (const match of content.matchAll(CAP_ID_RE)) {
13267
+ const id = match[0].toUpperCase();
13268
+ if (CAP_PLACEHOLDER_RE.test(id)) continue;
13269
+ specCaps.add(id);
13270
+ }
12429
13271
  }
12430
13272
  if (taskCaps.size === 0 && specCaps.size === 0) {
12431
13273
  return makeCheck("capability-coverage", "pass", "Tidak ada CAP-* (bundle legacy).");
@@ -12596,7 +13438,7 @@ function formatTable(headers, rows) {
12596
13438
 
12597
13439
  // src/recovery.ts
12598
13440
  import { randomUUID as randomUUID2 } from "node:crypto";
12599
- import { mkdir as mkdir6, readFile as readFile9, rename as rename2, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
13441
+ import { mkdir as mkdir6, readFile as readFile9, rename as rename3, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
12600
13442
  import { dirname as dirname6, join as join9 } from "node:path";
12601
13443
  var RECOVERY_PATH = "tasks/.execution/recovery.json";
12602
13444
  var RECOVERY_BUDGET = { maxAttempts: 3 };
@@ -12654,7 +13496,7 @@ async function writeRecovery(bundleDir, journal) {
12654
13496
  try {
12655
13497
  await writeFile6(temp, `${JSON.stringify(journal, null, 2)}
12656
13498
  `, "utf8");
12657
- await rename2(temp, target);
13499
+ await rename3(temp, target);
12658
13500
  } catch (error) {
12659
13501
  await rm7(temp, { force: true }).catch(() => {
12660
13502
  });
@@ -12739,7 +13581,7 @@ function describeRecovery(entry) {
12739
13581
  }
12740
13582
 
12741
13583
  // src/session.ts
12742
- import { rm as rm8, stat as stat5 } from "node:fs/promises";
13584
+ import { rm as rm8, stat as stat6 } from "node:fs/promises";
12743
13585
  import { resolve as resolve4 } from "node:path";
12744
13586
  var LOCK_STALE_MS3 = 1e4;
12745
13587
  var CHANGE_REQUEST_PREFIX = "Perubahan diminta:";
@@ -12892,7 +13734,7 @@ async function removeStaleLock2(bundleDir) {
12892
13734
  const target = lockPath(bundleDir);
12893
13735
  let info;
12894
13736
  try {
12895
- info = await stat5(target);
13737
+ info = await stat6(target);
12896
13738
  } catch (error) {
12897
13739
  if (isMissingFile6(error)) return;
12898
13740
  throw error;
@@ -12976,15 +13818,27 @@ async function loginCommand(options) {
12976
13818
  options.api ?? envFirst2("JIOOGEN_API", "JIOOCODE_API") ?? DEFAULT_API_URL
12977
13819
  );
12978
13820
  const client = new ApiClient(apiUrl, `${SESSION_COOKIE}=${token}`);
12979
- const body = await client.getJson(ENDPOINTS.me);
13821
+ let body;
13822
+ try {
13823
+ body = await client.getJson(ENDPOINTS.me);
13824
+ } catch (error) {
13825
+ if (error instanceof ApiError && error.status === 401) {
13826
+ throw new Error(
13827
+ `Token ditolak (401) oleh ${apiUrl}. Token mungkin ditandatangani secret lama sebelum migrasi VPS. Login ulang dengan --email/--password-stdin, atau set AUTH_TOKEN_SECRET_PREVIOUS di server berisi secret lama agar token diperbarui otomatis.`
13828
+ );
13829
+ }
13830
+ throw error;
13831
+ }
13832
+ const renewed = client.renewedCookie !== null;
12980
13833
  await writeCredentials({
12981
13834
  apiUrl,
12982
- cookie: `${SESSION_COOKIE}=${token}`,
13835
+ cookie: client.renewedCookie ?? `${SESSION_COOKIE}=${token}`,
12983
13836
  savedAt: (/* @__PURE__ */ new Date()).toISOString()
12984
13837
  });
12985
13838
  console.log(
12986
13839
  `Login sebagai ${body.user.email} (${body.user.role}/${body.user.subscriptionPlan}) di ${apiUrl}`
12987
13840
  );
13841
+ if (renewed) console.log("Token lama diperbarui otomatis ke secret aktif.");
12988
13842
  console.log(`Credential disimpan di ${credentialsPath()} (mode 0600).`);
12989
13843
  return;
12990
13844
  }
@@ -13016,6 +13870,48 @@ async function logoutCommand() {
13016
13870
  const removed = await clearCredentials();
13017
13871
  console.log(removed ? "Credential lokal dihapus." : "Tidak ada credential tersimpan.");
13018
13872
  }
13873
+ async function unlinkCommand(options) {
13874
+ const link = await findProjectLink(options.dir ?? process.cwd());
13875
+ const bundleDir = resolve6(link?.bundleDir ?? options.dir ?? process.cwd());
13876
+ const removed = await removeProjectLink(bundleDir);
13877
+ if (!removed) {
13878
+ console.log(
13879
+ "Tidak ada project link lokal (.jioogen/project.json) \u2014 bundle tidak terikat project."
13880
+ );
13881
+ return;
13882
+ }
13883
+ console.log(
13884
+ "Project link lokal dilepas (.jioogen/project.json dihapus). Isi bundle dan sidecar tetap tersimpan. Jalankan `jioogen projects` lalu `jioogen pull <id>` untuk bind project lain."
13885
+ );
13886
+ }
13887
+ async function executionStatusCommand(options) {
13888
+ const bundleDir = resolve6(options.dir ?? process.cwd());
13889
+ const hasMarker = await containsExecutionMarker(bundleDir);
13890
+ if (options.json === true) {
13891
+ console.log(JSON.stringify({ bundleDir, executionContract: hasMarker }, null, 2));
13892
+ return;
13893
+ }
13894
+ console.log(
13895
+ hasMarker ? "Kontrak eksekusi: TERPASANG (AGENTS.md/skill eksekusi ada)." : "Kontrak eksekusi: TIDAK terpasang \u2014 bundle bisa dijalankan manual."
13896
+ );
13897
+ }
13898
+ async function executionDisableCommand(options) {
13899
+ const bundleDir = resolve6(options.dir ?? process.cwd());
13900
+ const result = await removeExecutionContract(bundleDir);
13901
+ if (result.removed.length === 0) {
13902
+ console.log("Kontrak eksekusi sudah tidak terpasang (tidak ada yang dihapus).");
13903
+ return;
13904
+ }
13905
+ console.log("Kontrak eksekusi dilepas:");
13906
+ for (const entry of result.removed) console.log(`- ${entry}`);
13907
+ if (result.preserved.length > 0) {
13908
+ console.log("Dilewati (milik user, tidak diubah):");
13909
+ for (const entry of result.preserved) console.log(`- ${entry}`);
13910
+ }
13911
+ console.log(
13912
+ "Bundle sekarang bisa dijalankan manual. Untuk authoring-only: `jioogen authoring install`."
13913
+ );
13914
+ }
13019
13915
  async function whoamiCommand(options) {
13020
13916
  const { apiUrl, client } = await resolveApi(options);
13021
13917
  const body = await client.getJson(ENDPOINTS.me);
@@ -13062,8 +13958,19 @@ async function pullCommand(projectId, options) {
13062
13958
  const written = await extractBundle(bytes, target);
13063
13959
  await clearBaseline(target).catch(() => {
13064
13960
  });
13065
- const skills = await installAgentSkills(target, { noSkills: skillsDisabled(options) });
13066
- await writeProjectLink(target, { projectId, apiUrl, taskMode: options.taskMode });
13961
+ const uiQuality = options.uiQuality ?? await readUiQuality(target);
13962
+ const skills = await installAgentSkills(target, {
13963
+ noSkills: skillsDisabled(options),
13964
+ uiQuality
13965
+ });
13966
+ await writeProjectLink(target, {
13967
+ projectId,
13968
+ apiUrl,
13969
+ taskMode: options.taskMode,
13970
+ execution: { uiQuality }
13971
+ });
13972
+ await scaffoldCustomLayer(target).catch(() => {
13973
+ });
13067
13974
  if (options.json === true) {
13068
13975
  console.log(JSON.stringify({ projectId, target, files: written, skills }, null, 2));
13069
13976
  return;
@@ -13071,7 +13978,7 @@ async function pullCommand(projectId, options) {
13071
13978
  console.log(`Pulled ${written.length} file ke ${target}`);
13072
13979
  console.log("Project ter-bind lewat .jioogen/project.json.");
13073
13980
  console.log(`Skills eksekusi terpasang: ${skills.written.length} file.`);
13074
- printSkillPacks(skills.packs, skills.missing);
13981
+ printSkillPacks(skills.packs, skills.missing, skills.custom, skills.conflicts);
13075
13982
  }
13076
13983
  async function linkCommand(projectId, options) {
13077
13984
  const { apiUrl, client } = await resolveApi(options);
@@ -13079,8 +13986,19 @@ async function linkCommand(projectId, options) {
13079
13986
  await assertLinkTarget(target, projectId);
13080
13987
  await verifyProjectAccess(client, projectId);
13081
13988
  const taskMode = options.taskMode ?? await readTaskMode(target);
13082
- await writeProjectLink(target, { projectId, apiUrl, taskMode });
13083
- const skills = await installAgentSkills(target, { noSkills: skillsDisabled(options) });
13989
+ const uiQuality = options.uiQuality ?? await readUiQuality(target);
13990
+ await writeProjectLink(target, {
13991
+ projectId,
13992
+ apiUrl,
13993
+ taskMode,
13994
+ execution: { uiQuality }
13995
+ });
13996
+ await scaffoldCustomLayer(target).catch(() => {
13997
+ });
13998
+ const skills = await installAgentSkills(target, {
13999
+ noSkills: skillsDisabled(options),
14000
+ uiQuality
14001
+ });
13084
14002
  const linkedFile = join10(target, ".jioogen", "project.json");
13085
14003
  if (options.json === true) {
13086
14004
  console.log(JSON.stringify({ projectId, target, apiUrl, linkedFile, skills }, null, 2));
@@ -13089,7 +14007,7 @@ async function linkCommand(projectId, options) {
13089
14007
  console.log(`Project ${projectId} ter-bind ke ${target}.`);
13090
14008
  console.log(`File link: ${linkedFile} (API ${apiUrl}).`);
13091
14009
  console.log(`Skills eksekusi terpasang: ${skills.written.length} file.`);
13092
- printSkillPacks(skills.packs, skills.missing);
14010
+ printSkillPacks(skills.packs, skills.missing, skills.custom, skills.conflicts);
13093
14011
  await printPreExistingScope(target, projectId);
13094
14012
  }
13095
14013
  async function printPreExistingScope(bundleDir, projectId) {
@@ -13110,7 +14028,11 @@ async function printPreExistingScope(bundleDir, projectId) {
13110
14028
  }
13111
14029
  async function skillsInstallCommand(options) {
13112
14030
  const bundleDir = await resolveSkillsBundleDir(options);
13113
- const skills = await installAgentSkills(bundleDir, { noSkills: skillsDisabled(options) });
14031
+ const uiQuality = options.uiQuality ?? await readUiQuality(bundleDir);
14032
+ const skills = await installAgentSkills(bundleDir, {
14033
+ noSkills: skillsDisabled(options),
14034
+ uiQuality
14035
+ });
13114
14036
  if (options.json === true) {
13115
14037
  console.log(JSON.stringify({ bundleDir, ...skills }, null, 2));
13116
14038
  return;
@@ -13118,15 +14040,17 @@ async function skillsInstallCommand(options) {
13118
14040
  console.log(`Skills eksekusi terpasang di ${bundleDir}:`);
13119
14041
  for (const file of skills.written) console.log(`- ${file}`);
13120
14042
  for (const file of skills.preserved) console.log(`- ${file} (dilewati: milik user)`);
13121
- printSkillPacks(skills.packs, skills.missing);
14043
+ printSkillPacks(skills.packs, skills.missing, skills.custom, skills.conflicts);
13122
14044
  }
13123
14045
  async function skillsListCommand(options) {
13124
14046
  const bundleDir = await resolveSkillsBundleDir(options);
13125
14047
  const manifest = await readHarnessManifest(bundleDir);
14048
+ const uiQuality = await readUiQuality(bundleDir);
13126
14049
  if (options.json === true) {
13127
- console.log(JSON.stringify({ bundleDir, harness: manifest }, null, 2));
14050
+ console.log(JSON.stringify({ bundleDir, uiQuality, harness: manifest }, null, 2));
13128
14051
  return;
13129
14052
  }
14053
+ console.log(`UI/UX quality: ${uiQuality}`);
13130
14054
  if (manifest === null) {
13131
14055
  console.log(`Belum ada skill pack terpasang di ${bundleDir}.`);
13132
14056
  return;
@@ -13141,6 +14065,12 @@ async function skillsListCommand(options) {
13141
14065
  for (const name of pack.missing) console.log(`- ${name} (missing)`);
13142
14066
  if (pack.skills.length === 0 && pack.missing.length === 0) console.log("- (tidak ada skill)");
13143
14067
  }
14068
+ if (manifest.custom.length > 0) {
14069
+ console.log("custom:");
14070
+ for (const skill of manifest.custom) {
14071
+ console.log(`- ${skill.name} (installed, ${skill.sha256.slice(0, 12)})`);
14072
+ }
14073
+ }
13144
14074
  }
13145
14075
  async function skillsAddCommand(packArgument, options) {
13146
14076
  const packNames = parseSkillPackArgument(packArgument);
@@ -13154,7 +14084,7 @@ async function skillsAddCommand(packArgument, options) {
13154
14084
  return;
13155
14085
  }
13156
14086
  console.log(`Skill pack ditambahkan ke ${bundleDir}: ${result.added.join(", ")}`);
13157
- printSkillPacks(result.packs, result.missing);
14087
+ printSkillPacks(result.packs, result.missing, result.custom, result.conflicts);
13158
14088
  }
13159
14089
  async function skillsUpdateCommand(options) {
13160
14090
  const bundleDir = await resolveSkillsBundleDir(options);
@@ -13172,7 +14102,7 @@ async function skillsUpdateCommand(options) {
13172
14102
  return;
13173
14103
  }
13174
14104
  console.log(`Skill pack diperbarui di ${bundleDir}.`);
13175
- printSkillPacks(result.packs, result.missing);
14105
+ printSkillPacks(result.packs, result.missing, result.custom, result.conflicts);
13176
14106
  }
13177
14107
  async function skillsRemoveCommand(packArgument, options) {
13178
14108
  const packNames = parseSkillPackArgument(packArgument);
@@ -13191,17 +14121,57 @@ async function skillsRemoveCommand(packArgument, options) {
13191
14121
  console.log(`- ${file} (dilewati: milik user / sudah berubah)`);
13192
14122
  }
13193
14123
  }
14124
+ async function skillsRestoreCommand(packArgument, options) {
14125
+ const packNames = parseSkillPackArgument(packArgument);
14126
+ if (packNames === null) {
14127
+ throw new UsageError("Pack tidak dikenal. Pilih: baseline | ui-quality | backend-rules | all.");
14128
+ }
14129
+ const bundleDir = await resolveSkillsBundleDir(options);
14130
+ const result = await restoreSkillPack(bundleDir, packArgument);
14131
+ if (options.json === true) {
14132
+ console.log(JSON.stringify({ bundleDir, ...result }, null, 2));
14133
+ return;
14134
+ }
14135
+ console.log(`Skill pack dipulihkan di ${bundleDir}: ${result.restored.length} file.`);
14136
+ for (const file of result.restored) console.log(`- ${file}`);
14137
+ }
14138
+ async function skillsDisableCommand(name, options) {
14139
+ const bundleDir = await resolveSkillsBundleDir(options);
14140
+ const result = await disableSkill(bundleDir, name);
14141
+ if (options.json === true) {
14142
+ console.log(JSON.stringify({ bundleDir, name, ...result }, null, 2));
14143
+ return;
14144
+ }
14145
+ console.log(`Skill ${name} dinonaktifkan di ${bundleDir}: ${result.disabled.length} lokasi.`);
14146
+ }
14147
+ async function skillsEnableCommand(name, options) {
14148
+ const bundleDir = await resolveSkillsBundleDir(options);
14149
+ const result = await enableSkill(bundleDir, name);
14150
+ if (options.json === true) {
14151
+ console.log(JSON.stringify({ bundleDir, name, ...result }, null, 2));
14152
+ return;
14153
+ }
14154
+ console.log(`Skill ${name} diaktifkan di ${bundleDir}: ${result.enabled.length} lokasi.`);
14155
+ }
13194
14156
  async function resolveSkillsBundleDir(options) {
13195
14157
  const link = await findProjectLink(options.dir ?? process.cwd());
13196
14158
  return resolve6(link?.bundleDir ?? options.dir ?? process.cwd());
13197
14159
  }
13198
- function printSkillPacks(packs, missing) {
13199
- if (packs.length === 0 && missing.length === 0) return;
14160
+ function printSkillPacks(packs, missing, custom2 = [], conflicts = []) {
14161
+ if (packs.length === 0 && missing.length === 0 && custom2.length === 0) return;
13200
14162
  const installed = packs.filter((pack) => pack.skills.length > 0).map((pack) => `${pack.name} (${pack.skills.map((skill) => skill.name).join(", ")})`);
13201
14163
  if (installed.length > 0) console.log(`Skill pack: ${installed.join("; ")}.`);
14164
+ if (custom2.length > 0) {
14165
+ console.log(`Skill custom: ${custom2.map((entry) => entry.name).join(", ")}.`);
14166
+ }
13202
14167
  if (missing.length > 0) {
13203
14168
  console.warn(`Peringatan: skill tidak ditemukan (dilewati): ${missing.join(", ")}.`);
13204
14169
  }
14170
+ if (conflicts.length > 0) {
14171
+ console.warn(
14172
+ `Peringatan: skill custom bentrok dengan skill bawaan (dilewati): ${conflicts.join(", ")}.`
14173
+ );
14174
+ }
13205
14175
  }
13206
14176
  async function checkCommand(options) {
13207
14177
  const link = await findProjectLink(options.dir ?? process.cwd());
@@ -13339,7 +14309,7 @@ async function taskNextCommand(options) {
13339
14309
  bundleDir: local.bundleDir,
13340
14310
  definitions: local.definitions,
13341
14311
  written: written2,
13342
- next: selectNext(local.definitions, written2.tasks)
14312
+ next: selectNext(local.definitions, written2.tasks, { lenient: options.lenient })
13343
14313
  };
13344
14314
  }
13345
14315
  );
@@ -13350,12 +14320,18 @@ async function taskNextCommand(options) {
13350
14320
  next === null ? {} : { focusRef: next.task.id }
13351
14321
  ).catch(() => []);
13352
14322
  if (next === null) {
14323
+ const completion = computeCompletion(written.tasks, completionDefinitions(definitions));
13353
14324
  if (options.json === true) {
13354
- console.log(JSON.stringify({ done: true, projectId, drift }, null, 2));
14325
+ console.log(JSON.stringify({ done: true, projectId, drift, completion }, null, 2));
13355
14326
  return;
13356
14327
  }
13357
14328
  for (const finding of drift) console.warn(formatDrift(finding));
13358
- console.log("Semua task selesai.");
14329
+ if (completion.projectComplete) {
14330
+ console.log("Semua task selesai.");
14331
+ } else {
14332
+ console.log(printCompletionGaps(completion));
14333
+ printSeedReBreakdown();
14334
+ }
13359
14335
  const blocked = blockedTasks(definitions, written.tasks);
13360
14336
  if (blocked.length > 0) {
13361
14337
  console.log("\nTask yang masih menunggu dependency:");
@@ -13382,9 +14358,10 @@ async function taskNextCommand(options) {
13382
14358
  return;
13383
14359
  }
13384
14360
  const manifest = await readHarnessManifest(bundleDir);
13385
- const context = manifest === null ? void 0 : {
14361
+ const context = manifest === null ? { bundleDir } : {
13386
14362
  productKind: manifest.productKind,
13387
- skills: manifest.packs.flatMap((pack) => pack.skills.map((skill) => skill.name))
14363
+ skills: manifest.packs.flatMap((pack) => pack.skills.map((skill) => skill.name)),
14364
+ bundleDir
13388
14365
  };
13389
14366
  const instruction = renderActiveTask(next.task, context);
13390
14367
  if (options.json === true) {
@@ -13406,6 +14383,18 @@ async function taskNextCommand(options) {
13406
14383
  );
13407
14384
  return;
13408
14385
  }
14386
+ const hasBundleDrift = drift.some((finding) => finding.code === "BUNDLE_DRIFT");
14387
+ if (hasBundleDrift) {
14388
+ console.log("");
14389
+ console.log("\u26A0 BUNDLE_DRIFT terdeteksi: PRD.md/specs/tasks berubah di disk.");
14390
+ console.log(" Contract tidak boleh diedit lokal. Pilih:");
14391
+ console.log(" - perubahan tidak disengaja: `git checkout -- PRD.md specs tasks`");
14392
+ console.log(
14393
+ " - perubahan disengaja: revisi via https://gen.jioo.site lalu `jioogen pull --force`"
14394
+ );
14395
+ console.log(" - audit detail: `jioogen drift`");
14396
+ console.log("");
14397
+ }
13409
14398
  if (awaitingCheckpoint) {
13410
14399
  console.log(
13411
14400
  `Checkpoint aktif: ${written.current?.ref ?? "-"}. Minta konfirmasi user sebelum melanjutkan.`
@@ -13487,8 +14476,15 @@ async function taskStartCommand(ref, options) {
13487
14476
  `Task ${ref} berstatus RECOVERY_EXHAUSTED. Jalankan \`jioogen resume\` lalu ulangi dengan pendekatan berbeda.`
13488
14477
  );
13489
14478
  }
13490
- assertStartDependencies(ref, local.definitions, local.state.tasks);
13491
- const updated = withStatus(local.state, ref, "in_progress", {
14479
+ const resolvedState = await resolveOrAssertDependencies(
14480
+ ref,
14481
+ local.definitions,
14482
+ local.state,
14483
+ local.bundleDir,
14484
+ options,
14485
+ "start"
14486
+ );
14487
+ const updated = withStatus(resolvedState, ref, "in_progress", {
13492
14488
  awaitingCheckpoint: false,
13493
14489
  note: ""
13494
14490
  });
@@ -13508,11 +14504,18 @@ async function taskStartCommand(ref, options) {
13508
14504
  }
13509
14505
  async function finishTask(ref, options, extra = {}) {
13510
14506
  return withLocalState(options, async (local) => {
13511
- assertCompleteDependencies(ref, local.definitions, local.state.tasks, options.force === true);
14507
+ const resolvedState = await resolveOrAssertDependencies(
14508
+ ref,
14509
+ local.definitions,
14510
+ local.state,
14511
+ local.bundleDir,
14512
+ options,
14513
+ "complete"
14514
+ );
13512
14515
  const key = ref.trim().toUpperCase();
13513
14516
  const definition = local.definitions.find((entry) => entry.id.toUpperCase() === key);
13514
14517
  const verificationCommand = definition === void 0 ? null : verificationCommandFromContent(definition.content);
13515
- const stateTask = local.state.tasks.find((entry) => entry.ref.toUpperCase() === key);
14518
+ const stateTask = resolvedState.tasks.find((entry) => entry.ref.toUpperCase() === key);
13516
14519
  if (options.force !== true) {
13517
14520
  if (verificationCommand === null) {
13518
14521
  throw new Error(
@@ -13521,7 +14524,9 @@ async function finishTask(ref, options, extra = {}) {
13521
14524
  }
13522
14525
  const proof = stateTask?.verification;
13523
14526
  const proofCommand = proof?.command === void 0 ? void 0 : normalizeVerificationCommand(proof.command);
13524
- if (proof === void 0 || proof.exitCode !== 0 || proofCommand !== verificationCommand) {
14527
+ const expectedCommand = normalizeVerificationCommand(verificationCommand);
14528
+ const commandMatches = proofCommand !== void 0 && (proofCommand === expectedCommand || options.lenient === true);
14529
+ if (proof === void 0 || proof.exitCode !== 0 || !commandMatches) {
13525
14530
  throw new Error(`Task ${ref} belum diverifikasi. Jalankan \`jioogen task verify ${ref}\`.`);
13526
14531
  }
13527
14532
  if (stateTask?.designReview?.passed === false) {
@@ -13533,7 +14538,8 @@ async function finishTask(ref, options, extra = {}) {
13533
14538
  if (verificationCommand !== null) {
13534
14539
  const proof = stateTask?.verification;
13535
14540
  const proofCommand = proof?.command === void 0 ? void 0 : normalizeVerificationCommand(proof.command);
13536
- if (proof === void 0 || proof.exitCode !== 0 || proofCommand !== verificationCommand) {
14541
+ const expectedCommand = normalizeVerificationCommand(verificationCommand);
14542
+ if (proof === void 0 || proof.exitCode !== 0 || proofCommand !== expectedCommand) {
13537
14543
  console.warn(`Warning: bypass verification requirement for ${ref}.`);
13538
14544
  }
13539
14545
  if (stateTask?.designReview?.passed === false) {
@@ -13543,7 +14549,7 @@ async function finishTask(ref, options, extra = {}) {
13543
14549
  console.warn(`Warning: task ${ref} has no verificationCommand (legacy bypass).`);
13544
14550
  }
13545
14551
  }
13546
- let completed = withStatus(local.state, ref, "done", {
14552
+ let completed = withStatus(resolvedState, ref, "done", {
13547
14553
  note: options.note ?? "",
13548
14554
  awaitingCheckpoint: false
13549
14555
  });
@@ -13556,7 +14562,7 @@ async function finishTask(ref, options, extra = {}) {
13556
14562
  });
13557
14563
  }
13558
14564
  const completedTask = completed.tasks.find((entry) => entry.ref.toUpperCase() === key);
13559
- const next = selectNext(local.definitions, completed.tasks);
14565
+ const next = selectNext(local.definitions, completed.tasks, { lenient: options.lenient });
13560
14566
  const risky = definition !== void 0 && isRiskyTask(definition);
13561
14567
  const boundary = completedTask !== void 0 && (next !== null && isBoundary(completedTask, next.task) || risky);
13562
14568
  let finalState = completed;
@@ -13578,19 +14584,24 @@ async function finishTask(ref, options, extra = {}) {
13578
14584
  completedTask: written.tasks.find((entry) => entry.ref.toUpperCase() === key),
13579
14585
  next,
13580
14586
  checkpoint: boundary,
14587
+ completion: computeCompletion(written.tasks, completionDefinitions(local.definitions)),
13581
14588
  bundleDir: local.bundleDir,
13582
14589
  context: local
13583
14590
  };
13584
14591
  });
13585
14592
  }
13586
14593
  async function taskCompleteCommand(ref, options) {
13587
- const { completedTask, next, checkpoint, bundleDir, context } = await finishTask(ref, options);
14594
+ const { completedTask, next, checkpoint, completion, bundleDir, context } = await finishTask(
14595
+ ref,
14596
+ options
14597
+ );
13588
14598
  await recordSuccess(bundleDir, ref.trim().toUpperCase());
13589
14599
  await pushSidecarBestEffort(options, context);
13590
14600
  console.log(`Done ${completedTask?.ref ?? ref}.`);
13591
14601
  if (checkpoint) {
13592
14602
  if (next === null) {
13593
14603
  console.log("Semua task selesai; menunggu review terakhir.");
14604
+ printSeedGapTrigger(completion, next);
13594
14605
  } else {
13595
14606
  console.log(
13596
14607
  `Checkpoint berikutnya: ${next.task.id} (${next.task.layer ?? "-"} / phase ${next.task.phase}).`
@@ -13602,6 +14613,7 @@ async function taskCompleteCommand(ref, options) {
13602
14613
  return;
13603
14614
  }
13604
14615
  if (next !== null) console.log(`Berikutnya: ${next.task.id} \u2014 ${next.task.title}`);
14616
+ printSeedGapTrigger(completion, next);
13605
14617
  console.log(
13606
14618
  "Monitor web: status dikirim otomatis; jalankan `jioogen sync` bila tadi ada peringatan."
13607
14619
  );
@@ -13646,6 +14658,33 @@ async function stampVerification(context, definitions, ref, proof, visualSummary
13646
14658
  await writeState(context.bundleDir, next);
13647
14659
  });
13648
14660
  }
14661
+ async function resolveFallbackVerificationCommand(bundleDir, failedCommand) {
14662
+ let pkgRaw;
14663
+ try {
14664
+ pkgRaw = await readFile10(join10(bundleDir, "package.json"), "utf8");
14665
+ } catch {
14666
+ return null;
14667
+ }
14668
+ let pkg;
14669
+ try {
14670
+ pkg = JSON.parse(pkgRaw);
14671
+ } catch {
14672
+ return null;
14673
+ }
14674
+ const scripts = pkg.scripts;
14675
+ if (!scripts || typeof scripts !== "object") return null;
14676
+ const candidateKeys = ["test", "test:unit", "check", "lint", "build"];
14677
+ const normFailed = normalizeVerificationCommand(failedCommand);
14678
+ for (const key of candidateKeys) {
14679
+ if (typeof scripts[key] === "string" && scripts[key].trim().length > 0) {
14680
+ const candidateCmd = key === "test" ? "npm test" : `npm run ${key}`;
14681
+ if (normalizeVerificationCommand(candidateCmd) !== normFailed) {
14682
+ return candidateCmd;
14683
+ }
14684
+ }
14685
+ }
14686
+ return null;
14687
+ }
13649
14688
  async function taskVerifyCommand(ref, options) {
13650
14689
  const context = await resolveLocalBundle(options);
13651
14690
  const definitions = await loadTasks(context.bundleDir);
@@ -13661,20 +14700,32 @@ async function taskVerifyCommand(ref, options) {
13661
14700
  }
13662
14701
  const timeoutMs = verifyTimeoutMs();
13663
14702
  const startedAt = Date.now();
13664
- const result = await runVerification(command, context.bundleDir, timeoutMs);
14703
+ let executedCommand = command;
14704
+ let result = await runVerification(command, context.bundleDir, timeoutMs);
14705
+ if (result.exitCode !== 0) {
14706
+ const fallback = await resolveFallbackVerificationCommand(context.bundleDir, command);
14707
+ if (fallback !== null) {
14708
+ const fallbackResult = await runVerification(fallback, context.bundleDir, timeoutMs);
14709
+ if (fallbackResult.exitCode === 0) {
14710
+ executedCommand = fallback;
14711
+ result = fallbackResult;
14712
+ console.log(`\u2139 Perintah utama gagal, tetapi fallback verifikasi berhasil: \`${fallback}\``);
14713
+ }
14714
+ }
14715
+ }
13665
14716
  const durationMs = Date.now() - startedAt;
13666
14717
  const at = (/* @__PURE__ */ new Date()).toISOString();
13667
14718
  await stampVerification(
13668
14719
  context,
13669
14720
  definitions,
13670
14721
  definition.id,
13671
- { command, exitCode: result.exitCode, durationMs, at },
14722
+ { command: executedCommand, exitCode: result.exitCode, durationMs, at },
13672
14723
  options.visual?.trim()
13673
14724
  );
13674
14725
  await pushSidecarBestEffort(options, context);
13675
14726
  const payload = {
13676
14727
  ref: definition.id,
13677
- command,
14728
+ command: executedCommand,
13678
14729
  exitCode: result.exitCode,
13679
14730
  durationMs,
13680
14731
  at,
@@ -13706,12 +14757,38 @@ async function taskAdoptCommand(ref, options) {
13706
14757
  }
13707
14758
  const existing = await readState(context.bundleDir);
13708
14759
  const known = existing ?? createState(context.projectId, definitions);
13709
- assertCompleteDependencies(definition.id, definitions, known.tasks, options.force === true);
14760
+ const resolvedState = await resolveOrAssertDependencies(
14761
+ definition.id,
14762
+ definitions,
14763
+ known,
14764
+ context.bundleDir,
14765
+ options,
14766
+ "adopt"
14767
+ );
14768
+ await writeState(context.bundleDir, resolvedState);
13710
14769
  const command = verificationCommandFromContent(definition.content);
13711
14770
  let verification = null;
13712
14771
  if (command !== null) {
13713
14772
  const startedAt = Date.now();
13714
- const result2 = await runVerification(command, context.bundleDir, verifyTimeoutMs());
14773
+ let executedCommand = command;
14774
+ let result2 = await runVerification(command, context.bundleDir, verifyTimeoutMs());
14775
+ if (result2.exitCode !== 0) {
14776
+ const fallback = await resolveFallbackVerificationCommand(context.bundleDir, command);
14777
+ if (fallback !== null) {
14778
+ const fallbackResult = await runVerification(
14779
+ fallback,
14780
+ context.bundleDir,
14781
+ verifyTimeoutMs()
14782
+ );
14783
+ if (fallbackResult.exitCode === 0) {
14784
+ executedCommand = fallback;
14785
+ result2 = fallbackResult;
14786
+ console.log(
14787
+ `\u2139 Perintah utama gagal, tetapi fallback verifikasi berhasil: \`${fallback}\``
14788
+ );
14789
+ }
14790
+ }
14791
+ }
13715
14792
  const durationMs = Date.now() - startedAt;
13716
14793
  if (result2.exitCode !== 0) {
13717
14794
  throw new Error(
@@ -13723,10 +14800,10 @@ async function taskAdoptCommand(ref, options) {
13723
14800
  context,
13724
14801
  definitions,
13725
14802
  definition.id,
13726
- { command, exitCode: 0, durationMs, at },
14803
+ { command: executedCommand, exitCode: 0, durationMs, at },
13727
14804
  options.visual?.trim()
13728
14805
  );
13729
- verification = { command, exitCode: 0, durationMs, at };
14806
+ verification = { command: executedCommand, exitCode: 0, durationMs, at };
13730
14807
  } else if (options.force !== true) {
13731
14808
  throw new Error(
13732
14809
  `Task ${ref} tidak punya verificationCommand. Gunakan --force hanya untuk task legacy, dan catat alasan di --note.`
@@ -13762,6 +14839,7 @@ async function taskAdoptCommand(ref, options) {
13762
14839
  console.log(
13763
14840
  result.next === null ? "Semua task selesai; menunggu review terakhir." : `Checkpoint berikutnya: ${result.next.task.id} (${result.next.task.layer ?? "-"} / phase ${result.next.task.phase}).`
13764
14841
  );
14842
+ printSeedGapTrigger(result.completion, result.next);
13765
14843
  console.log(
13766
14844
  'Berhenti. Setelah user memutuskan: `jioogen review --approve`, `--request-changes "<teks>"`, atau `--stop`.'
13767
14845
  );
@@ -13769,6 +14847,7 @@ async function taskAdoptCommand(ref, options) {
13769
14847
  }
13770
14848
  if (result.next !== null)
13771
14849
  console.log(`Berikutnya: ${result.next.task.id} \u2014 ${result.next.task.title}`);
14850
+ printSeedGapTrigger(result.completion, result.next);
13772
14851
  console.log(
13773
14852
  "Monitor web: status dikirim otomatis; jalankan `jioogen sync` bila tadi ada peringatan."
13774
14853
  );
@@ -13899,19 +14978,177 @@ async function statusCommand(options) {
13899
14978
  console.log(`Project ${projectId}: belum ada sidecar. Jalankan \`jioogen task next\`.`);
13900
14979
  return;
13901
14980
  }
14981
+ let reconciled = existing;
14982
+ try {
14983
+ reconciled = mergeTasks(existing, await loadTasks(bundleDir));
14984
+ } catch {
14985
+ }
13902
14986
  printExecution(
13903
14987
  {
13904
- tasks: existing.tasks,
13905
- counts: existing.counts ?? summarizeExecutionCounts(existing.tasks),
13906
- current: existing.current ?? null,
13907
- updatedAt: existing.updatedAt ?? null
14988
+ tasks: reconciled.tasks,
14989
+ counts: reconciled.counts ?? summarizeExecutionCounts(reconciled.tasks),
14990
+ current: reconciled.current ?? null,
14991
+ updatedAt: reconciled.updatedAt ?? null
13908
14992
  },
13909
14993
  options.json === true
13910
14994
  );
13911
14995
  }
14996
+ async function contractUpdateBaselineCommand(options) {
14997
+ const { bundleDir } = await resolveLocalBundle(options);
14998
+ const newBundleHash = await updateContractBaseline(bundleDir);
14999
+ console.log(`Baseline kontrak diupdate. Hash baru: ${newBundleHash}`);
15000
+ console.log(`File terverifikasi: PRD.md, traceability.md, specs/, tasks/`);
15001
+ console.log(`Perubahan lokal disetujui sebagai baseline baru.`);
15002
+ console.log(`Jalankan \`jioogen task next\` untuk melanjutkan.`);
15003
+ }
15004
+ async function driftCommand(options) {
15005
+ const { bundleDir } = await resolveLocalBundle(options);
15006
+ if (options.acknowledge === true) {
15007
+ const marker = await acknowledgeDrift(
15008
+ bundleDir,
15009
+ {
15010
+ pruned: options.pruned === true,
15011
+ prd: options.prd === true,
15012
+ specs: options.specs === true,
15013
+ tasks: options.tasks === true
15014
+ },
15015
+ options.note
15016
+ );
15017
+ if (options.json === true) {
15018
+ console.log(JSON.stringify({ bundleDir, acknowledged: marker }, null, 2));
15019
+ return;
15020
+ }
15021
+ console.log(`Drift acknowledged di ${bundleDir}: ${JSON.stringify(marker)}`);
15022
+ return;
15023
+ }
15024
+ const definitions = await loadTasks(bundleDir);
15025
+ const state = await readState(bundleDir);
15026
+ if (state === null) {
15027
+ if (options.json === true) {
15028
+ console.log(JSON.stringify({ bundleDir, findings: [] }, null, 2));
15029
+ return;
15030
+ }
15031
+ console.log(`Project bundle ${bundleDir}: belum ada sidecar; drift belum bisa dibandingkan.`);
15032
+ console.log("Jalankan `jioogen task next` dulu untuk membuat baseline.");
15033
+ return;
15034
+ }
15035
+ const findings = await detectDrift(bundleDir, definitions, state);
15036
+ if (options.json === true) {
15037
+ console.log(JSON.stringify({ bundleDir, findings }, null, 2));
15038
+ if (options.strict === true && findings.some((finding) => finding.severity === "warn")) {
15039
+ process.exitCode = 1;
15040
+ }
15041
+ return;
15042
+ }
15043
+ if (findings.length === 0) {
15044
+ console.log(`Drift check ${bundleDir}: tidak ada perubahan di luar harness.`);
15045
+ return;
15046
+ }
15047
+ for (const finding of findings) {
15048
+ console.log(formatDrift(finding));
15049
+ }
15050
+ const hasWarn = findings.some((finding) => finding.severity === "warn");
15051
+ if (hasWarn) {
15052
+ console.log("");
15053
+ console.log("Saran:");
15054
+ console.log(
15055
+ "- Perubahan tidak disengaja pada PRD.md/specs/tasks: `git checkout -- PRD.md specs tasks`"
15056
+ );
15057
+ console.log(
15058
+ "- Perubahan kontrak disengaja: revisi via workspace web (https://gen.jioo.site), lalu `jioogen pull --force`."
15059
+ );
15060
+ console.log(
15061
+ "- Perubahan di scope task: `jioogen task adopt <ref>` (setelah verifikasi) atau `jioogen task reset <ref>`."
15062
+ );
15063
+ }
15064
+ if (options.strict === true && hasWarn) process.exitCode = 1;
15065
+ }
15066
+ async function baselineListCommand(options) {
15067
+ const bundleDir = await resolveSkillsBundleDir(options);
15068
+ const manifest = await readHarnessManifest(bundleDir);
15069
+ const knowledgeDir = join10(bundleDir, ".jioogen", "custom", "knowledge");
15070
+ let knowledgeFiles = [];
15071
+ try {
15072
+ const entries = await readdir7(knowledgeDir, { withFileTypes: true });
15073
+ knowledgeFiles = entries.filter((entry) => entry.isFile()).map((entry) => entry.name).sort();
15074
+ } catch {
15075
+ knowledgeFiles = [];
15076
+ }
15077
+ const nonEmptyKnowledge = [];
15078
+ for (const name of knowledgeFiles) {
15079
+ try {
15080
+ const content = await readFile10(join10(knowledgeDir, name), "utf8");
15081
+ if (content.trim().length > 0) nonEmptyKnowledge.push(name);
15082
+ } catch {
15083
+ }
15084
+ }
15085
+ const customSkillsDir = join10(bundleDir, ".jioogen", "custom", "skills");
15086
+ let customSkillNames = [];
15087
+ try {
15088
+ const entries = await readdir7(customSkillsDir, { withFileTypes: true });
15089
+ customSkillNames = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
15090
+ } catch {
15091
+ customSkillNames = [];
15092
+ }
15093
+ const agentsPath = join10(bundleDir, "AGENTS.md");
15094
+ let agentsExists = false;
15095
+ let agentsBaseline = false;
15096
+ try {
15097
+ const content = await readFile10(agentsPath, "utf8");
15098
+ agentsExists = true;
15099
+ agentsBaseline = content.includes("jioogen-execution-skill");
15100
+ } catch {
15101
+ agentsExists = false;
15102
+ }
15103
+ const areas = [
15104
+ {
15105
+ area: "skills packs",
15106
+ baselineInstalled: manifest !== null && (manifest.packs?.length ?? 0) > 0,
15107
+ customized: (manifest?.custom?.length ?? 0) > 0,
15108
+ path: ".jioogen/harness.json"
15109
+ },
15110
+ {
15111
+ area: "custom skills",
15112
+ baselineInstalled: customSkillNames.length > 0,
15113
+ customized: customSkillNames.length > 0,
15114
+ path: ".jioogen/custom/skills"
15115
+ },
15116
+ {
15117
+ area: "knowledge",
15118
+ baselineInstalled: knowledgeFiles.length > 0,
15119
+ customized: nonEmptyKnowledge.length > 0,
15120
+ path: ".jioogen/custom/knowledge"
15121
+ },
15122
+ {
15123
+ area: "AGENTS.md/instructions",
15124
+ baselineInstalled: agentsBaseline,
15125
+ customized: agentsExists && !agentsBaseline,
15126
+ path: "AGENTS.md"
15127
+ }
15128
+ ];
15129
+ if (options.json === true) {
15130
+ console.log(JSON.stringify({ bundleDir, areas }, null, 2));
15131
+ return;
15132
+ }
15133
+ console.log(`Baseline status ${bundleDir}:`);
15134
+ for (const area of areas) {
15135
+ console.log(
15136
+ `- ${area.area}: baseline=${area.baselineInstalled ? "yes" : "no"}, customized=${area.customized ? "yes" : "no"}, path=${area.path}`
15137
+ );
15138
+ }
15139
+ }
13912
15140
  async function monitorCommand(options) {
13913
- const { client, projectId } = await resolveBundle(options);
13914
- const snapshot = await client.getJson(projectPath(projectId, "/execution"));
15141
+ const { client, projectId, bundleDir } = await resolveBundle(options);
15142
+ let snapshot;
15143
+ try {
15144
+ snapshot = await client.getJson(projectPath(projectId, "/execution"));
15145
+ } catch (error) {
15146
+ if (error instanceof ApiError && error.status === 404) {
15147
+ await handleProjectGone(bundleDir);
15148
+ return;
15149
+ }
15150
+ throw error;
15151
+ }
13915
15152
  if (options.json === true) {
13916
15153
  console.log(JSON.stringify(snapshot, null, 2));
13917
15154
  return;
@@ -13950,21 +15187,102 @@ async function syncCommand(options) {
13950
15187
  });
13951
15188
  }
13952
15189
  }
13953
- const result = await client.postJson(projectPath(projectId, "/artifacts"), {
13954
- files
13955
- });
15190
+ let result;
15191
+ try {
15192
+ result = await client.postJson(projectPath(projectId, "/artifacts"), {
15193
+ files
15194
+ });
15195
+ } catch (error) {
15196
+ if (error instanceof ApiError && error.status === 404) {
15197
+ await handleProjectGone(bundleDir);
15198
+ return;
15199
+ }
15200
+ throw error;
15201
+ }
13956
15202
  if (options.json === true) {
13957
15203
  console.log(JSON.stringify(result, null, 2));
13958
15204
  return;
13959
15205
  }
13960
15206
  console.log(`Synced ${result.written?.length ?? 0} file.`);
15207
+ const sidecarSynced = result.written?.some((p) => p.startsWith("tasks/.execution/")) ?? false;
15208
+ if (sidecarSynced) {
15209
+ console.log("\u2714 Status eksekusi & kemajuan task berhasil disinkronkan ke monitor web.");
15210
+ }
13961
15211
  if (result.rejected !== void 0 && result.rejected.length > 0) {
13962
15212
  for (const rejection of result.rejected) {
13963
- console.log(`Ditolak: ${rejection.path} (${rejection.code}) \u2014 ${rejection.reason}`);
15213
+ if (rejection.code === "PRD_CONFIRMED") {
15214
+ console.log(
15215
+ `\u2139 PRD.md di server dipertahankan (karena sudah dikonfirmasi di web). Gunakan web UI bila ingin merevisi PRD.`
15216
+ );
15217
+ } else {
15218
+ console.log(`Ditolak: ${rejection.path} (${rejection.code}) \u2014 ${rejection.reason}`);
15219
+ }
13964
15220
  }
13965
15221
  }
13966
15222
  if (result.warning !== void 0) console.log(`Peringatan: ${result.warning}`);
13967
15223
  }
15224
+ async function reconcileCommand(options) {
15225
+ const result = await withLocalState(options, async (local) => {
15226
+ const backupFile = await backupExecutionState(local.bundleDir);
15227
+ const { state: reconciledState, result: recResult } = await reconcileCodebase(
15228
+ local.bundleDir,
15229
+ local.definitions,
15230
+ local.state
15231
+ );
15232
+ let writtenState = reconciledState;
15233
+ if (options.dryRun !== true) {
15234
+ writtenState = await writeState(local.bundleDir, reconciledState);
15235
+ }
15236
+ const next = selectNext(local.definitions, writtenState.tasks, {
15237
+ lenient: options.lenient
15238
+ });
15239
+ return {
15240
+ backupFile,
15241
+ recResult,
15242
+ next,
15243
+ writtenState,
15244
+ context: local
15245
+ };
15246
+ });
15247
+ if (options.dryRun !== true) {
15248
+ await pushSidecarBestEffort(options, result.context);
15249
+ }
15250
+ if (options.json === true) {
15251
+ console.log(
15252
+ JSON.stringify(
15253
+ {
15254
+ backupFile: result.backupFile,
15255
+ dryRun: options.dryRun === true,
15256
+ adopted: result.recResult.adopted,
15257
+ remaining: result.recResult.remaining,
15258
+ total: result.recResult.total,
15259
+ next: result.next?.task.id ?? null
15260
+ },
15261
+ null,
15262
+ 2
15263
+ )
15264
+ );
15265
+ return;
15266
+ }
15267
+ console.log("\u2714 Rekonsiliasi codebase selesai.");
15268
+ if (result.backupFile !== null) {
15269
+ console.log(` Backup state disimpan di: ${result.backupFile}`);
15270
+ }
15271
+ if (result.recResult.adopted.length > 0) {
15272
+ console.log(
15273
+ ` - ${result.recResult.adopted.length} task terdeteksi sudah memiliki berkas kode (diadopsi): ${result.recResult.adopted.join(", ")}`
15274
+ );
15275
+ } else {
15276
+ console.log(" - Tidak ada task baru yang berkasnya ditemukan di disk.");
15277
+ }
15278
+ console.log(` - ${result.recResult.remaining.length} task tersisa.`);
15279
+ if (result.next !== null) {
15280
+ console.log(`
15281
+ Task berikutnya: ${result.next.task.id} \u2014 ${result.next.task.title}`);
15282
+ } else {
15283
+ console.log("\nSemua task selesai.");
15284
+ }
15285
+ }
13968
15286
  async function resolveApi(options) {
13969
15287
  const stored = await readCredentials();
13970
15288
  const apiUrl = normalizeBaseUrl(
@@ -14004,34 +15322,50 @@ async function resolveBundle(options) {
14004
15322
  }
14005
15323
  async function pushSidecarBestEffort(options, local) {
14006
15324
  if (options.noSync === true || process.env.JIOOGEN_NO_SYNC === "1") return;
14007
- try {
14008
- const api = await resolveApi({ api: options.api ?? local.linkedApiUrl });
14009
- const state = await readState(local.bundleDir);
14010
- if (state === null) return;
14011
- await api.client.postJson(
14012
- projectPath(local.projectId, "/artifacts"),
14013
- {
14014
- files: [
14015
- {
14016
- path: EXECUTION_SIDECAR_PATH,
14017
- content: `${JSON.stringify(
14018
- { ...state, counts: summarizeExecutionCounts(state.tasks) },
14019
- null,
14020
- 2
14021
- )}
15325
+ const maxAttempts = 2;
15326
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
15327
+ try {
15328
+ const api = await resolveApi({ api: options.api ?? local.linkedApiUrl });
15329
+ const state = await readState(local.bundleDir);
15330
+ if (state === null) return;
15331
+ await api.client.postJson(
15332
+ projectPath(local.projectId, "/artifacts"),
15333
+ {
15334
+ files: [
15335
+ {
15336
+ path: EXECUTION_SIDECAR_PATH,
15337
+ content: `${JSON.stringify(
15338
+ { ...state, counts: summarizeExecutionCounts(state.tasks) },
15339
+ null,
15340
+ 2
15341
+ )}
14022
15342
  `
14023
- }
14024
- ]
14025
- },
14026
- { signal: AbortSignal.timeout(STATUS_PUSH_TIMEOUT_MS) }
14027
- );
14028
- } catch (error) {
14029
- const message = error instanceof Error ? error.message : String(error);
14030
- console.warn(
14031
- `Status tersimpan lokal; belum terkirim ke monitor (${message}). Jalankan \`jioogen sync\` nanti.`
14032
- );
15343
+ }
15344
+ ]
15345
+ },
15346
+ { signal: AbortSignal.timeout(STATUS_PUSH_TIMEOUT_MS) }
15347
+ );
15348
+ return;
15349
+ } catch (error) {
15350
+ if (error instanceof ApiError && error.status === 404) {
15351
+ await handleProjectGone(local.bundleDir);
15352
+ return;
15353
+ }
15354
+ if (attempt === maxAttempts) {
15355
+ const message = error instanceof Error ? error.message : String(error);
15356
+ console.warn(
15357
+ `Status tersimpan lokal; belum terkirim ke monitor (${message}). Jalankan \`jioogen sync\` nanti.`
15358
+ );
15359
+ }
15360
+ }
14033
15361
  }
14034
15362
  }
15363
+ async function handleProjectGone(bundleDir) {
15364
+ const removed = await removeProjectLink(bundleDir);
15365
+ console.warn(
15366
+ removed ? "Project dihapus/tidak ditemukan di server. Link lokal dilepas (.jioogen/project.json dihapus); bundle ini tidak terikat project apa pun. Jalankan `jioogen projects` untuk memilih project lain lalu `jioogen pull <id>` untuk bind ulang." : "Project dihapus/tidak ditemukan di server. Bundle ini juga sudah tidak punya link lokal (.jioogen/project.json); ia tidak terikat project apa pun."
15367
+ );
15368
+ }
14035
15369
  async function withLocalState(options, fn) {
14036
15370
  const context = await resolveLocalBundle(options);
14037
15371
  return withStateLock(context.bundleDir, async () => {
@@ -14055,20 +15389,43 @@ function unmetDependencies(ref, definitions, states) {
14055
15389
  (dependency) => byRef.get(dependency.toUpperCase())?.status !== "done"
14056
15390
  );
14057
15391
  }
14058
- function assertStartDependencies(ref, definitions, states) {
14059
- const missing = unmetDependencies(ref, definitions, states);
14060
- if (missing.length === 0) return;
14061
- throw new Error(
14062
- `Tidak bisa memulai ${ref}: dependency belum selesai (${missing.join(", ")}). Selesaikan dependency itu lebih dulu.`
14063
- );
14064
- }
14065
- function assertCompleteDependencies(ref, definitions, states, force) {
14066
- if (force) return;
14067
- const missing = unmetDependencies(ref, definitions, states);
14068
- if (missing.length === 0) return;
14069
- throw new Error(
14070
- `Tidak bisa menyelesaikan ${ref}: dependency belum selesai (${missing.join(", ")}). Selesaikan dependency itu lebih dulu, atau tambahkan --force bila memang disengaja.`
14071
- );
15392
+ async function resolveOrAssertDependencies(ref, definitions, state, bundleDir, options, action) {
15393
+ const key = ref.toUpperCase();
15394
+ const definition = definitions.find((task) => task.id.toUpperCase() === key);
15395
+ if (definition === void 0) return state;
15396
+ let currentState = state;
15397
+ const missing = unmetDependencies(ref, definitions, currentState.tasks);
15398
+ if (missing.length === 0) return currentState;
15399
+ const stillMissing = [];
15400
+ for (const depId of missing) {
15401
+ const depDef = definitions.find((task) => task.id.toUpperCase() === depId.toUpperCase());
15402
+ const filesExist = depDef !== void 0 ? await taskTargetFilesExist(bundleDir, depDef) : false;
15403
+ if (options.lenient === true || filesExist) {
15404
+ const reason = filesExist ? `target files terdeteksi di disk (diperlukan oleh ${ref})` : `auto-adopted via --lenient (diperlukan oleh ${ref})`;
15405
+ currentState = withStatus(currentState, depId, "done", {
15406
+ note: reason,
15407
+ awaitingCheckpoint: false
15408
+ });
15409
+ currentState = setTaskSource(currentState, depId, "user");
15410
+ currentState = appendTaskEvidence(currentState, depId, {
15411
+ type: "text",
15412
+ summary: `auto-adopted outside harness as dependency of ${ref}`,
15413
+ at: (/* @__PURE__ */ new Date()).toISOString()
15414
+ });
15415
+ console.log(
15416
+ `\u2139 Auto-mengadopsi dependensi hulu ${depId} (source: user) agar ${ref} tidak terblokir.`
15417
+ );
15418
+ } else {
15419
+ stillMissing.push(depId);
15420
+ }
15421
+ }
15422
+ if (stillMissing.length > 0 && options.force !== true) {
15423
+ const verb = action === "start" ? "memulai" : action === "adopt" ? "mengadopsi" : "menyelesaikan";
15424
+ throw new Error(
15425
+ `Tidak bisa ${verb} ${ref}: dependency belum selesai (${stillMissing.join(", ")}). Selesaikan dependency itu lebih dulu, atau gunakan --lenient / --force bila disengaja.`
15426
+ );
15427
+ }
15428
+ return currentState;
14072
15429
  }
14073
15430
  async function assertPullDefaultDir(cwd, dirOption) {
14074
15431
  if (dirOption) return;
@@ -14132,6 +15489,33 @@ async function hasTaskMarkdown(directory) {
14132
15489
  }
14133
15490
  return names.some((name) => name.toLowerCase().endsWith(".md"));
14134
15491
  }
15492
+ async function scaffoldCustomLayer(bundleDir) {
15493
+ const stackDir = join10(bundleDir, ".jioogen", "custom", "stack");
15494
+ const knowledgeDir = join10(bundleDir, ".jioogen", "custom", "knowledge");
15495
+ const designDir = join10(bundleDir, ".jioogen", "custom", "design");
15496
+ await mkdir8(stackDir, { recursive: true });
15497
+ await mkdir8(knowledgeDir, { recursive: true });
15498
+ await mkdir8(designDir, { recursive: true });
15499
+ const exampleFile = join10(stackDir, "STACK.md.example");
15500
+ try {
15501
+ await stat7(exampleFile);
15502
+ } catch {
15503
+ const template = [
15504
+ "# Custom Stack & Architecture Preferences",
15505
+ "",
15506
+ "Tulis preferensi teknologi pilihan Anda di sini (ubah nama file menjadi STACK.md).",
15507
+ "Perintah `jioogen task next` akan otomatis menyuntikkan isi file ini ke AI executor.",
15508
+ "",
15509
+ "Contoh:",
15510
+ "- UI / Styling: Tailwind CSS, shadcn/ui",
15511
+ "- Database / ORM: PostgreSQL + Drizzle ORM",
15512
+ "- Testing Runner: Vitest (bukan Jest)",
15513
+ ""
15514
+ ].join("\n");
15515
+ await writeFile8(exampleFile, template, "utf8").catch(() => {
15516
+ });
15517
+ }
15518
+ }
14135
15519
  async function verifyProjectAccess(client, projectId) {
14136
15520
  try {
14137
15521
  await client.getJson(projectPath(projectId, "/execution"));
@@ -14148,6 +15532,31 @@ function assertBundleRelative(path) {
14148
15532
  throw new Error(`Path harus relatif terhadap bundle: ${path}`);
14149
15533
  }
14150
15534
  }
15535
+ function printCompletionGaps(completion) {
15536
+ const lines = ["Task DAG selesai, tetapi per-feature masih ada gap:"];
15537
+ const entries = Object.entries(completion.features).filter(([, unit]) => unit.status !== "complete").sort(([left], [right]) => left.localeCompare(right));
15538
+ if (entries.length === 0) lines.push("- (tidak ada unit feature yang dideklarasikan)");
15539
+ for (const [id, unit] of entries) {
15540
+ lines.push(`- ${id}: ${unit.status} (${unit.doneTasks}/${unit.totalTasks} task selesai)`);
15541
+ }
15542
+ return lines.join("\n");
15543
+ }
15544
+ function printSeedReBreakdown() {
15545
+ console.log("");
15546
+ console.log("Gap di atas tidak ditutup oleh DAG task yang ada \u2014 ini bukan 'selesai',");
15547
+ console.log("melainkan coverage feature yang belum lengkap.");
15548
+ console.log("Buat follow-up task untuk pekerjaan yang belum ter-cover lewat re-breakdown");
15549
+ console.log("dengan mode seed (mis. `jioogen link <projectId> --mode seed` atau sejenisnya),");
15550
+ console.log(
15551
+ "lalu kerjakan task baru itu untuk menutup gap. Task follow-up TIDAK dibuat otomatis."
15552
+ );
15553
+ }
15554
+ function printSeedGapTrigger(completion, next) {
15555
+ if (next !== null || completion.projectComplete) return;
15556
+ console.log("");
15557
+ console.log(printCompletionGaps(completion));
15558
+ printSeedReBreakdown();
15559
+ }
14151
15560
  function printExecution(data, asJson) {
14152
15561
  if (asJson) {
14153
15562
  console.log(JSON.stringify(data, null, 2));
@@ -14226,9 +15635,86 @@ async function authoringRemoveCommand(options) {
14226
15635
  }
14227
15636
  console.log(`Authoring contract dihapus dari ${dir}.`);
14228
15637
  }
15638
+ async function runCommand(options) {
15639
+ const { bundleDir, projectId } = await resolveLocalBundle(options);
15640
+ const link = await findProjectLink(bundleDir);
15641
+ if (link === null) throw new Error("Belum ada project link. Jalankan `jioogen link` dulu.");
15642
+ if (options.stop === true) {
15643
+ await writeAutoMode(bundleDir, false);
15644
+ console.log(`Auto-mode DINONAKTIFKAN untuk project ${projectId}.`);
15645
+ console.log("Agent akan kembali ke mode satu task per giliran (human-in-the-loop).");
15646
+ return;
15647
+ }
15648
+ const currentlyOn = await readAutoMode(bundleDir);
15649
+ if (options.auto !== true && options.dryRun !== true && options.until === void 0 && options.maxTasks === void 0) {
15650
+ console.log(`Project ${projectId} \u2014 auto-mode: ${currentlyOn ? "AKTIF" : "nonaktif"}.`);
15651
+ console.log("Aktifkan: `jioogen run --auto` (tanya konfirmasi di awal).");
15652
+ console.log("Matikan: `jioogen run --stop`.");
15653
+ console.log("Rencana saja: `jioogen run --auto --dry-run`.");
15654
+ return;
15655
+ }
15656
+ const maxTasks = Math.max(1, Math.min(50, options.maxTasks ?? 5));
15657
+ const definitions = await loadTasks(bundleDir);
15658
+ const existing = await readState(bundleDir);
15659
+ const tasks = existing?.tasks ?? [];
15660
+ const todo = definitions.filter((d) => {
15661
+ const s = tasks.find((t) => t.id === d.id)?.status;
15662
+ return s !== "done";
15663
+ });
15664
+ const target = options.until ?? "all";
15665
+ const plan = target === "all" ? todo.slice(0, maxTasks) : todo.filter((d) => d.id === target).slice(0, maxTasks);
15666
+ console.log(`Project ${projectId} \u2014 auto-mode`);
15667
+ console.log(
15668
+ `Mode: ${options.strictCheckpoints === true ? "strict (berhenti di setiap transisi layer)" : "normal (transisi layer = soft stop)"}`
15669
+ );
15670
+ console.log(`Batas: ${maxTasks} task per run`);
15671
+ console.log(`Daftar task yang akan dijalankan (${plan.length}):`);
15672
+ for (const t of plan) console.log(`- ${t.id} (${t.layer ?? "?"}, phase ${t.phase}) ${t.title}`);
15673
+ if (plan.length === 0) {
15674
+ console.log("Tidak ada task yang tersisa. Auto-mode tidak diperlukan.");
15675
+ return;
15676
+ }
15677
+ if (options.dryRun === true) {
15678
+ console.log("\n(dry-run: tidak ada perubahan state)");
15679
+ return;
15680
+ }
15681
+ process.stdout.write("\nAktifkan auto-mode? (lanjut / batal): ");
15682
+ const answer = await readLine();
15683
+ if (answer.trim().toLowerCase() !== "lanjut") {
15684
+ console.log("Dibatalkan. Auto-mode tidak diaktifkan.");
15685
+ return;
15686
+ }
15687
+ await writeAutoMode(bundleDir, true);
15688
+ console.log("\nAuto-mode AKTIF. Aturan yang berlaku untuk agent:");
15689
+ console.log("- Jalankan task berurutan via `task next` \u2192 kerjakan \u2192 `task complete` \u2192 lanjut.");
15690
+ console.log(
15691
+ "- AUTO-CONTINUE (tanpa konfirmasi) pada: transisi layer & kenaikan phase (soft stop, dicatat di sidecar)."
15692
+ );
15693
+ console.log(
15694
+ "- HARD STOP (wajib berhenti) pada: task fail, verifikasi gagal, task checkpoint:true, task sensitif (data/akses/integrasi/rahasia/deploy/infra), max-tasks tercapai, bundle blocked, atau user `jioogen run --stop`."
15695
+ );
15696
+ console.log("- Setiap task tetap dapat commit git kecil (rollback point).");
15697
+ console.log("- Jangan edit PRD.md/specs/ (hard rule tetap).");
15698
+ console.log("\nUntuk mematikan: `jioogen run --stop` atau Ctrl+C (graceful).");
15699
+ console.log("Monitoring: `jioogen status` / `jioogen monitor`.");
15700
+ }
15701
+ async function readLine() {
15702
+ return new Promise((resolve7) => {
15703
+ const chunks = [];
15704
+ process.stdin.resume();
15705
+ process.stdin.on("data", (chunk) => {
15706
+ chunks.push(Buffer.from(chunk));
15707
+ if (Buffer.concat(chunks).toString("utf8").includes("\n")) {
15708
+ process.stdin.pause();
15709
+ resolve7(Buffer.concat(chunks).toString("utf8"));
15710
+ }
15711
+ });
15712
+ process.stdin.on("end", () => resolve7(Buffer.concat(chunks).toString("utf8")));
15713
+ });
15714
+ }
14229
15715
 
14230
15716
  // src/index.ts
14231
- var VERSION = "0.2.10";
15717
+ var VERSION = "0.2.12";
14232
15718
  function parseTaskModeOption(value) {
14233
15719
  if (value === void 0) return void 0;
14234
15720
  const parsed = TaskModeSchema.safeParse(value);
@@ -14237,6 +15723,11 @@ function parseTaskModeOption(value) {
14237
15723
  }
14238
15724
  return parsed.data;
14239
15725
  }
15726
+ function parseUiQualityOption(value) {
15727
+ if (value === void 0) return void 0;
15728
+ if (UI_QUALITY_MODES.includes(value)) return value;
15729
+ throw new UsageError(`--ui-quality harus salah satu: ${UI_QUALITY_MODES.join(", ")}`);
15730
+ }
14240
15731
  var USAGE = `jioogen \u2014 CLI JiooGen (task selection lokal, server read-only)
14241
15732
 
14242
15733
  Usage:
@@ -14244,31 +15735,43 @@ Usage:
14244
15735
  jioogen login --email <email> (--password <pass> | --password-stdin)
14245
15736
  jioogen logout
14246
15737
  jioogen whoami
15738
+ jioogen unlink [--dir <dir>]
15739
+ jioogen execution status [--dir <dir>] [--json]
15740
+ jioogen execution disable [--dir <dir>]
14247
15741
  jioogen projects
14248
- jioogen pull <projectId> [--dir <dir>] [--force] [--no-skills] [--mode <mode>]
14249
- jioogen link <projectId> [--dir <dir>] [--no-skills] [--mode <mode>]
14250
- jioogen skills install [--dir <dir>] [--no-skills]
15742
+ jioogen pull <projectId> [--dir <dir>] [--force] [--no-skills] [--mode <mode>] [--ui-quality <auto|on|off>]
15743
+ jioogen link <projectId> [--dir <dir>] [--no-skills] [--mode <mode>] [--ui-quality <auto|on|off>]
15744
+ jioogen skills install [--dir <dir>] [--no-skills] [--ui-quality <auto|on|off>]
14251
15745
  jioogen skills list [--dir <dir>] [--json]
14252
15746
  jioogen skills add <baseline|ui-quality|backend-rules|all> [--dir <dir>]
14253
15747
  jioogen skills update [--dir <dir>]
14254
15748
  jioogen skills remove <baseline|ui-quality|backend-rules> [--dir <dir>]
15749
+ jioogen skills restore <pack|all> [--dir <dir>]
15750
+ jioogen skills disable <name> [--dir <dir>]
15751
+ jioogen skills enable <name> [--dir <dir>]
14255
15752
  jioogen authoring install [--dir <dir>]
14256
15753
  jioogen authoring status [--dir <dir>] [--json]
14257
15754
  jioogen authoring remove [--dir <dir>]
14258
15755
  jioogen check [--dir <dir>] [--json]
14259
15756
  jioogen doctor [--fix] [--dir <dir>] [--json]
15757
+ jioogen drift [--dir <dir>] [--json] [--strict] [--acknowledge] [--prd] [--specs] [--tasks] [--note <text>]
15758
+ jioogen contract update-baseline [--dir <dir>]
15759
+ jioogen baseline list [--dir <dir>] [--json]
14260
15760
  jioogen resume [--dir <dir>] [--json]
15761
+ jioogen run [--auto] [--until <ref|all>] [--max-tasks N] [--strict-checkpoints] [--dry-run]
15762
+ jioogen run --stop
14261
15763
  jioogen review (--approve | --request-changes <teks> | --stop) [--ref <TASK-XXX>] [--json]
14262
15764
  jioogen handoff [--project <id>] [--json]
14263
- jioogen task next [--json]
14264
- jioogen task start <ref>
14265
- jioogen task complete <ref> [--note <text>] [--force]
14266
- jioogen task adopt <ref> [--note <text>] [--visual <catatan>] [--force]
15765
+ jioogen task next [--json] [--lenient]
15766
+ jioogen task start <ref> [--lenient]
15767
+ jioogen task complete <ref> [--note <text>] [--lenient] [--force]
15768
+ jioogen task adopt <ref> [--note <text>] [--visual <catatan>] [--lenient] [--force]
14267
15769
  jioogen task verify <ref> [--dir <dir>] [--json]
14268
15770
  jioogen task expand <ref> [--write]
14269
15771
  jioogen task fail <ref> [reason...] [--note <text>]
14270
15772
  jioogen task reset <ref> [reason...] [--note <text>]
14271
15773
  jioogen status [--remote] [--json]
15774
+ jioogen reconcile [--dry-run] [--lenient] [--dir <dir>] [--json]
14272
15775
  jioogen sync [--files a.md,b.md] [--json]
14273
15776
  jioogen monitor [--json]
14274
15777
 
@@ -14287,6 +15790,7 @@ async function main() {
14287
15790
  let raw = {};
14288
15791
  let positionals = [];
14289
15792
  let taskMode;
15793
+ let uiQuality;
14290
15794
  try {
14291
15795
  const parsed = parseArgs({
14292
15796
  args: process.argv.slice(2),
@@ -14301,8 +15805,10 @@ async function main() {
14301
15805
  dir: { type: "string" },
14302
15806
  remote: { type: "boolean" },
14303
15807
  force: { type: "boolean" },
15808
+ lenient: { type: "boolean" },
14304
15809
  "no-skills": { type: "boolean" },
14305
15810
  mode: { type: "string" },
15811
+ "ui-quality": { type: "string" },
14306
15812
  "no-sync": { type: "boolean" },
14307
15813
  files: { type: "string" },
14308
15814
  note: { type: "string" },
@@ -14314,6 +15820,18 @@ async function main() {
14314
15820
  json: { type: "boolean" },
14315
15821
  write: { type: "boolean" },
14316
15822
  visual: { type: "string" },
15823
+ auto: { type: "boolean" },
15824
+ "max-tasks": { type: "string" },
15825
+ until: { type: "string" },
15826
+ "strict-checkpoints": { type: "boolean" },
15827
+ strict: { type: "boolean" },
15828
+ acknowledge: { type: "boolean" },
15829
+ pruned: { type: "boolean" },
15830
+ prd: { type: "boolean" },
15831
+ specs: { type: "boolean" },
15832
+ tasks: { type: "boolean" },
15833
+ "dry-run": { type: "boolean" },
15834
+ resume: { type: "boolean" },
14317
15835
  help: { type: "boolean", short: "h" },
14318
15836
  version: { type: "boolean", short: "v" }
14319
15837
  }
@@ -14321,6 +15839,7 @@ async function main() {
14321
15839
  raw = parsed.values;
14322
15840
  positionals = parsed.positionals;
14323
15841
  taskMode = parseTaskModeOption(text(raw.mode));
15842
+ uiQuality = parseUiQualityOption(text(raw["ui-quality"]));
14324
15843
  } catch (error) {
14325
15844
  console.error(`Error: ${error instanceof Error ? error.message : String(error)}
14326
15845
  `);
@@ -14338,6 +15857,7 @@ async function main() {
14338
15857
  dir: text(raw.dir),
14339
15858
  remote: flag(raw.remote),
14340
15859
  force: flag(raw.force),
15860
+ lenient: flag(raw.lenient),
14341
15861
  noSkills: flag(raw["no-skills"]),
14342
15862
  noSync: flag(raw["no-sync"]),
14343
15863
  files: text(raw.files),
@@ -14350,7 +15870,20 @@ async function main() {
14350
15870
  json: flag(raw.json),
14351
15871
  write: flag(raw.write),
14352
15872
  visual: text(raw.visual),
14353
- taskMode
15873
+ auto: flag(raw.auto),
15874
+ maxTasks: raw["max-tasks"] === void 0 ? void 0 : Number(raw["max-tasks"]),
15875
+ until: text(raw.until),
15876
+ strictCheckpoints: flag(raw["strict-checkpoints"]),
15877
+ strict: flag(raw.strict),
15878
+ acknowledge: flag(raw.acknowledge),
15879
+ pruned: flag(raw.pruned),
15880
+ prd: flag(raw.prd),
15881
+ specs: flag(raw.specs),
15882
+ tasks: flag(raw.tasks),
15883
+ dryRun: flag(raw["dry-run"]),
15884
+ resume: flag(raw.resume),
15885
+ taskMode,
15886
+ uiQuality
14354
15887
  };
14355
15888
  if (flag(raw.version)) {
14356
15889
  console.log(`jioogen ${VERSION}`);
@@ -14388,6 +15921,21 @@ async function dispatch(command, rest, options) {
14388
15921
  case "logout":
14389
15922
  await logoutCommand();
14390
15923
  return;
15924
+ case "unlink":
15925
+ await unlinkCommand(options);
15926
+ return;
15927
+ case "execution": {
15928
+ const sub = rest[0];
15929
+ if (sub === "status") {
15930
+ await executionStatusCommand(options);
15931
+ return;
15932
+ }
15933
+ if (sub === "disable") {
15934
+ await executionDisableCommand(options);
15935
+ return;
15936
+ }
15937
+ throw new UsageError("Subcommand execution: status | disable");
15938
+ }
14391
15939
  case "whoami":
14392
15940
  await whoamiCommand(options);
14393
15941
  return;
@@ -14418,6 +15966,15 @@ async function dispatch(command, rest, options) {
14418
15966
  case "doctor":
14419
15967
  await doctorCommand(options);
14420
15968
  return;
15969
+ case "drift":
15970
+ await driftCommand(options);
15971
+ return;
15972
+ case "baseline":
15973
+ await baselineListCommand(options);
15974
+ return;
15975
+ case "contract":
15976
+ await dispatchContract(rest, options);
15977
+ return;
14421
15978
  case "resume":
14422
15979
  await resumeCommand(options);
14423
15980
  return;
@@ -14433,6 +15990,12 @@ async function dispatch(command, rest, options) {
14433
15990
  case "status":
14434
15991
  await statusCommand(options);
14435
15992
  return;
15993
+ case "reconcile":
15994
+ await reconcileCommand(options);
15995
+ return;
15996
+ case "run":
15997
+ await runCommand(options);
15998
+ return;
14436
15999
  case "sync":
14437
16000
  await syncCommand(options);
14438
16001
  return;
@@ -14472,8 +16035,34 @@ async function dispatchSkills(rest, options) {
14472
16035
  await skillsRemoveCommand(pack, options);
14473
16036
  return;
14474
16037
  }
16038
+ case "restore": {
16039
+ const pack = rest[1];
16040
+ if (pack === void 0) {
16041
+ throw new UsageError("`jioogen skills restore` butuh <pack|all>.");
16042
+ }
16043
+ await skillsRestoreCommand(pack, options);
16044
+ return;
16045
+ }
16046
+ case "disable": {
16047
+ const name = rest[1];
16048
+ if (name === void 0) {
16049
+ throw new UsageError("`jioogen skills disable` butuh <name>.");
16050
+ }
16051
+ await skillsDisableCommand(name, options);
16052
+ return;
16053
+ }
16054
+ case "enable": {
16055
+ const name = rest[1];
16056
+ if (name === void 0) {
16057
+ throw new UsageError("`jioogen skills enable` butuh <name>.");
16058
+ }
16059
+ await skillsEnableCommand(name, options);
16060
+ return;
16061
+ }
14475
16062
  default:
14476
- throw new UsageError("Subcommand skills: install | list | add | update | remove");
16063
+ throw new UsageError(
16064
+ "Subcommand skills: install | list | add | update | remove | restore | disable | enable"
16065
+ );
14477
16066
  }
14478
16067
  }
14479
16068
  async function dispatchAuthoring(rest, options) {
@@ -14493,6 +16082,18 @@ async function dispatchAuthoring(rest, options) {
14493
16082
  throw new UsageError("Subcommand authoring: install | status | remove");
14494
16083
  }
14495
16084
  }
16085
+ async function dispatchContract(rest, options) {
16086
+ const subcommand = rest[0];
16087
+ switch (subcommand) {
16088
+ case "update-baseline":
16089
+ await contractUpdateBaselineCommand(options);
16090
+ return;
16091
+ default:
16092
+ throw new UsageError(
16093
+ "Subcommand contract: update-baseline. Contoh: `jioogen contract update-baseline`"
16094
+ );
16095
+ }
16096
+ }
14496
16097
  async function dispatchTask(rest, options) {
14497
16098
  const subcommand = rest[0];
14498
16099
  const ref = rest[1];