jioogen 0.2.12 → 0.2.13

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 stat8;
366
+ var stat9;
367
367
  try {
368
- stat8 = self.fs.statSync(resolvedPath);
368
+ stat9 = 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 (stat8 && stat8.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
376
+ if (stat9 && stat9.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 stat8 = self.fs.statSync(path);
386
- if (stat8.isDirectory()) {
385
+ var stat9 = self.fs.statSync(path);
386
+ if (stat9.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, stat8) {
420
- if (exist && stat8 && stat8.isDirectory()) {
419
+ self.fs.stat(path, function(err, stat9) {
420
+ if (exist && stat9 && stat9.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 stat8;
472
+ let stat9;
473
473
  try {
474
- stat8 = self.fs.lstatSync(cur);
474
+ stat9 = self.fs.lstatSync(cur);
475
475
  } catch (e) {
476
476
  break;
477
477
  }
478
- if (stat8.isSymbolicLink()) throw Errors.FILE_IN_THE_WAY(`"${cur}"`);
478
+ if (stat9.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 stat8 = self.fs.statSync(path2);
505
+ const stat9 = self.fs.statSync(path2);
506
506
  if (!pattern || pattern.test(path2)) {
507
- files.push(pth.normalize(path2) + (stat8.isDirectory() ? self.sep : ""));
507
+ files.push(pth.normalize(path2) + (stat9.isDirectory() ? self.sep : ""));
508
508
  }
509
- if (stat8.isDirectory() && recursive) {
509
+ if (stat9.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, stat8) {
556
+ self.fs.stat(file, function(err3, stat9) {
557
557
  if (err3) return done(err3);
558
- if (!stat8) {
558
+ if (!stat9) {
559
559
  if (!--pending) done();
560
560
  return;
561
561
  }
562
- results.push(pth.normalize(file) + (stat8.isDirectory() ? self.sep : ""));
563
- if (!stat8.isDirectory()) {
562
+ results.push(pth.normalize(file) + (stat9.isDirectory() ? self.sep : ""));
563
+ if (!stat9.isDirectory()) {
564
564
  if (!--pending) done();
565
565
  return;
566
566
  }
@@ -2124,8 +2124,8 @@ var require_adm_zip = __commonJS({
2124
2124
  return null;
2125
2125
  }
2126
2126
  function fixPath(zipPath) {
2127
- const { join: join11, normalize: normalize2, sep: sep2 } = pth.posix;
2128
- return join11(pth.isAbsolute(zipPath) ? "/" : ".", normalize2(sep2 + zipPath.split("\\").join(sep2) + sep2));
2127
+ const { join: join13, normalize: normalize2, sep: sep2 } = pth.posix;
2128
+ return join13(pth.isAbsolute(zipPath) ? "/" : ".", normalize2(sep2 + zipPath.split("\\").join(sep2) + sep2));
2129
2129
  }
2130
2130
  function filenameFilter(filterfn) {
2131
2131
  if (filterfn instanceof RegExp) {
@@ -8935,11 +8935,18 @@ function normalize(value) {
8935
8935
  function taskId(task) {
8936
8936
  return /TASK-\d{3,}/.exec(task.path)?.[0] ?? "TASK-001";
8937
8937
  }
8938
+ var CAP_PLACEHOLDER = /^CAP-X+$/;
8939
+ function isCapPlaceholder(id) {
8940
+ return CAP_PLACEHOLDER.test(id.toUpperCase());
8941
+ }
8942
+ function realCapTokens(text2) {
8943
+ return (text2.match(/\bCAP-[A-Z0-9-]+\b/g) ?? []).filter((token) => !isCapPlaceholder(token));
8944
+ }
8938
8945
  function taskOwnedCaps(tasks) {
8939
8946
  const owned = /* @__PURE__ */ new Set();
8940
8947
  for (const task of tasks) {
8941
8948
  const cap = parseTaskContext(task.content, taskId(task)).cap;
8942
- for (const token of cap?.match(/\bCAP-[A-Z0-9-]+\b/g) ?? []) {
8949
+ for (const token of realCapTokens(cap ?? "")) {
8943
8950
  owned.add(token.toUpperCase());
8944
8951
  }
8945
8952
  }
@@ -9179,7 +9186,7 @@ ${taskTargets(task)}`
9179
9186
  );
9180
9187
  }
9181
9188
  }
9182
- const capMentioned = input.capabilityRequired === true || /\bCAP-[A-Z0-9-]+\b/.test(specText) || tasks.some((task) => /^\s*cap:\s*CAP-[A-Z0-9-]+/im.test(task.content));
9189
+ const capMentioned = input.capabilityRequired === true || realCapTokens(specText).length > 0 || taskOwnedCaps(tasks).size > 0;
9183
9190
  const specIndex = specs.find((file) => file.path === BUNDLE_PATHS.SPECS_INDEX);
9184
9191
  const capModel = specIndex === void 0 ? "" : section2(specIndex.content, "## Capability Model");
9185
9192
  if (capMentioned && capModel.trim().length === 0) {
@@ -9207,6 +9214,7 @@ ${taskTargets(task)}`
9207
9214
  if (row.every((cell) => cell.length === 0 || /^:?-{2,}:?$/.test(cell))) continue;
9208
9215
  const cap = (row[capIndex] ?? "").toUpperCase();
9209
9216
  if (!/^CAP-[A-Z0-9-]+$/.test(cap)) continue;
9217
+ if (isCapPlaceholder(cap)) continue;
9210
9218
  const required = /^(?:yes|true|required|wajib)$/i.test(row[requiredIndex] ?? "");
9211
9219
  if (!required) {
9212
9220
  if ((row[signalIndex] ?? "").trim().length === 0) {
@@ -10035,6 +10043,18 @@ var ApiClient = class {
10035
10043
  const response = await this.request(path);
10036
10044
  return new Uint8Array(await response.arrayBuffer());
10037
10045
  }
10046
+ async getWorkspaceArtifacts(projectId) {
10047
+ return this.getJson(projectPath(projectId, "/artifacts"));
10048
+ }
10049
+ async getPrdConfirmation(projectId) {
10050
+ return this.getJson(projectPath(projectId, "/prd-confirmation"));
10051
+ }
10052
+ async revokePrdConfirmation(projectId, reason) {
10053
+ return this.postJson(projectPath(projectId, "/prd-confirmation"), {
10054
+ action: "revoke-confirmation",
10055
+ reason
10056
+ });
10057
+ }
10038
10058
  async request(path, options = {}) {
10039
10059
  const { json, ...init } = options;
10040
10060
  const headers = new Headers(init.headers);
@@ -10054,9 +10074,14 @@ var ApiClient = class {
10054
10074
  };
10055
10075
 
10056
10076
  // src/commands.ts
10077
+ import { spawn as spawn2 } from "node:child_process";
10078
+ import { mkdir as mkdir10, readdir as readdir8, readFile as readFile12, stat as stat8, writeFile as writeFile10 } from "node:fs/promises";
10079
+ import { join as join12, resolve as resolve6 } from "node:path";
10080
+
10081
+ // src/align.ts
10057
10082
  import { spawn } from "node:child_process";
10058
- import { mkdir as mkdir8, readdir as readdir7, readFile as readFile10, stat as stat7, writeFile as writeFile8 } from "node:fs/promises";
10059
- import { join as join10, resolve as resolve6 } from "node:path";
10083
+ import { mkdir as mkdir5, readFile as readFile7, rm as rm4, stat as stat4, writeFile as writeFile5 } from "node:fs/promises";
10084
+ import { join as join7 } from "node:path";
10060
10085
 
10061
10086
  // src/authoring.ts
10062
10087
  import { existsSync } from "node:fs";
@@ -10075,6 +10100,9 @@ function cliPackageRoot() {
10075
10100
  return resolve(dirname(fileURLToPath(import.meta.url)), "..");
10076
10101
  }
10077
10102
  var BUNDLED_PACK_DIR = join(cliPackageRoot(), "authoring-pack");
10103
+ function bundledAuthoringPackDir() {
10104
+ return BUNDLED_PACK_DIR;
10105
+ }
10078
10106
  async function readBundledManifest() {
10079
10107
  const raw = await readFile(join(BUNDLED_PACK_DIR, "manifest.json"), "utf8");
10080
10108
  const parsed = JSON.parse(raw);
@@ -10119,8 +10147,8 @@ async function containsExecutionMarker(dir) {
10119
10147
  }
10120
10148
  return false;
10121
10149
  }
10122
- async function buildOpencodeConfig(target) {
10123
- const agentDir = join(target, "agent");
10150
+ async function buildAuthoringOpencodeConfig(packDir) {
10151
+ const agentDir = join(packDir, "agent");
10124
10152
  const instructions = [];
10125
10153
  try {
10126
10154
  const entries = await readdir(agentDir);
@@ -10129,7 +10157,7 @@ async function buildOpencodeConfig(target) {
10129
10157
  }
10130
10158
  } catch {
10131
10159
  }
10132
- const skillsRoot = join(target, "skills");
10160
+ const skillsRoot = join(packDir, "skills");
10133
10161
  const skillPaths = [];
10134
10162
  try {
10135
10163
  const entries = await readdir(skillsRoot, { withFileTypes: true });
@@ -10166,7 +10194,7 @@ async function installAuthoringContract(dir) {
10166
10194
  await mkdir(target, { recursive: true });
10167
10195
  await cp(BUNDLED_PACK_DIR, target, { recursive: true, force: true });
10168
10196
  const opencodePath = join(target, "opencode.json");
10169
- const opencodeConfig = await buildOpencodeConfig(target);
10197
+ const opencodeConfig = await buildAuthoringOpencodeConfig(target);
10170
10198
  await writeFile(opencodePath, `${JSON.stringify(opencodeConfig, null, 2)}
10171
10199
  `, "utf8");
10172
10200
  const marker = {
@@ -10370,252 +10398,248 @@ function formatBundleCheck(check) {
10370
10398
  return lines.join("\n");
10371
10399
  }
10372
10400
 
10373
- // src/config.ts
10374
- import { chmod, mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
10375
- import { homedir } from "node:os";
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";
10383
- var CONFIG_DIR_ENV = "JIOOGEN_CONFIG_DIR";
10384
- var LEGACY_CONFIG_DIR_ENV = "JIOOCODE_CONFIG_DIR";
10385
- var CREDENTIALS_FILE = "credentials.json";
10386
- var PROJECT_DIR = ".jioogen";
10387
- var LEGACY_PROJECT_DIR = ".jioocode";
10388
- var PROJECT_FILE = "project.json";
10389
- function envValue(name) {
10390
- const value = process.env[name]?.trim();
10391
- return value !== void 0 && value.length > 0 ? value : void 0;
10401
+ // src/contract.ts
10402
+ import { createHash } from "node:crypto";
10403
+ import { mkdir as mkdir2, readdir as readdir3, readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
10404
+ import { dirname as dirname2, join as join3, relative as relative2 } from "node:path";
10405
+ var CONTRACT_LEDGER_PATH = join3(".jioogen", "contract.json");
10406
+ var APPROVALS_PATH = join3(".jioogen", "approvals.json");
10407
+ var LOCAL_IGNORED_DIRS = /* @__PURE__ */ new Set([".execution", ".jioogen", ".git", "node_modules"]);
10408
+ function sha256(bytes) {
10409
+ return createHash("sha256").update(bytes).digest("hex");
10410
+ }
10411
+ async function walkMarkdown(root, directory) {
10412
+ const found = [];
10413
+ async function walk2(current) {
10414
+ let entries;
10415
+ try {
10416
+ entries = await readdir3(current, { withFileTypes: true });
10417
+ } catch {
10418
+ return;
10419
+ }
10420
+ for (const entry of entries) {
10421
+ if (entry.isDirectory()) {
10422
+ if (LOCAL_IGNORED_DIRS.has(entry.name)) continue;
10423
+ await walk2(join3(current, entry.name));
10424
+ continue;
10425
+ }
10426
+ if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
10427
+ found.push(relative2(root, join3(current, entry.name)).replace(/\\/g, "/"));
10428
+ }
10429
+ }
10430
+ await walk2(join3(root, directory));
10431
+ return found.sort();
10392
10432
  }
10393
- function configDirOverride() {
10394
- return envValue(CONFIG_DIR_ENV) ?? envValue(LEGACY_CONFIG_DIR_ENV);
10433
+ function fingerprint(files, matches) {
10434
+ const entries = Object.entries(files).filter(([path]) => matches(path)).sort(([left], [right]) => left.localeCompare(right));
10435
+ if (entries.length === 0) return null;
10436
+ return sha256(entries.map(([path, hash]) => `${path}:${hash}`).join("\n"));
10395
10437
  }
10396
- function configDir() {
10397
- const override = configDirOverride();
10398
- return override !== void 0 ? resolve2(override) : join3(homedir(), ".config", "jioogen");
10438
+ async function snapshotContract(bundleDir) {
10439
+ const paths = /* @__PURE__ */ new Set();
10440
+ for (const name of ["PRD.md", "traceability.md"]) {
10441
+ try {
10442
+ const content = await readFile3(join3(bundleDir, name));
10443
+ if (content.byteLength > 0) paths.add(name);
10444
+ } catch {
10445
+ }
10446
+ }
10447
+ for (const directory of ["specs", "tasks"]) {
10448
+ for (const path of await walkMarkdown(bundleDir, directory)) paths.add(path);
10449
+ }
10450
+ const files = {};
10451
+ for (const path of [...paths].sort()) {
10452
+ try {
10453
+ files[path] = sha256(await readFile3(join3(bundleDir, path)));
10454
+ } catch {
10455
+ }
10456
+ }
10457
+ const tasksMatch = (path) => path.startsWith("tasks/") || path === "traceability.md";
10458
+ return {
10459
+ prd: files["PRD.md"] ?? null,
10460
+ specs: fingerprint(files, (path) => path.startsWith("specs/")),
10461
+ tasks: fingerprint(files, tasksMatch),
10462
+ files
10463
+ };
10399
10464
  }
10400
- function legacyConfigDir() {
10401
- return join3(homedir(), ".config", "jioocode");
10465
+ function hasContractArtifacts(snapshot) {
10466
+ return snapshot.prd !== null || snapshot.specs !== null;
10402
10467
  }
10403
- function credentialsPath() {
10404
- return join3(configDir(), CREDENTIALS_FILE);
10468
+ function freshDerivation(snapshot, now = /* @__PURE__ */ new Date()) {
10469
+ const at = now.toISOString();
10470
+ const prdHash = snapshot.prd;
10471
+ return {
10472
+ specs: prdHash !== null && snapshot.specs !== null ? { prdHash, recordedAt: at } : null,
10473
+ tasks: prdHash !== null && snapshot.tasks !== null ? {
10474
+ prdHash,
10475
+ ...snapshot.specs === null ? {} : { specsFingerprint: snapshot.specs },
10476
+ recordedAt: at
10477
+ } : null
10478
+ };
10405
10479
  }
10406
- function isRecord(value) {
10407
- return typeof value === "object" && value !== null;
10480
+ function computeStaleness(derivation, snapshot) {
10481
+ const specsStale = snapshot.specs !== null && snapshot.prd !== null && derivation.specs !== null && derivation.specs.prdHash !== snapshot.prd;
10482
+ const prdMoved = snapshot.prd !== null && derivation.tasks !== null && derivation.tasks.prdHash !== snapshot.prd;
10483
+ const specsMoved = snapshot.specs !== null && derivation.tasks?.specsFingerprint != null && derivation.tasks.specsFingerprint !== snapshot.specs;
10484
+ const tasksStale = snapshot.tasks !== null && derivation.tasks !== null && (prdMoved || specsMoved);
10485
+ return { specsStale, tasksStale, stale: specsStale || tasksStale };
10408
10486
  }
10409
- function parseCredentials(value) {
10410
- if (!isRecord(value)) return null;
10411
- const { apiUrl, cookie, savedAt } = value;
10412
- if (typeof apiUrl !== "string" || apiUrl.length === 0) return null;
10413
- if (typeof cookie !== "string" || cookie.length === 0) return null;
10487
+ function changedSince(current, previous) {
10488
+ const prd = previous === null ? current.prd !== null : current.prd !== previous.prd;
10489
+ const specs = previous === null ? current.specs !== null : current.specs !== previous.specs;
10490
+ const tasks = previous === null ? current.tasks !== null : current.tasks !== previous.tasks;
10491
+ return { prd, specs, tasks, any: prd || specs || tasks };
10492
+ }
10493
+ function serverAsSnapshot(server) {
10414
10494
  return {
10415
- apiUrl,
10416
- cookie,
10417
- savedAt: typeof savedAt === "string" ? savedAt : (/* @__PURE__ */ new Date(0)).toISOString()
10495
+ prd: server.prd,
10496
+ specs: server.specs,
10497
+ tasks: server.tasks,
10498
+ files: {}
10418
10499
  };
10419
10500
  }
10420
- async function readCredentialsFile(path) {
10501
+ function objectValue(value) {
10502
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
10503
+ }
10504
+ function parseStage(value) {
10505
+ const record = objectValue(value);
10506
+ if (record === null || typeof record.prdHash !== "string" || record.prdHash.length === 0) {
10507
+ return null;
10508
+ }
10509
+ return {
10510
+ prdHash: record.prdHash,
10511
+ ...typeof record.specsFingerprint === "string" ? { specsFingerprint: record.specsFingerprint } : {},
10512
+ recordedAt: typeof record.recordedAt === "string" ? record.recordedAt : ""
10513
+ };
10514
+ }
10515
+ function parseDerivation(value) {
10516
+ const record = objectValue(value);
10517
+ if (record === null) return null;
10518
+ return { specs: parseStage(record.specs), tasks: parseStage(record.tasks) };
10519
+ }
10520
+ async function readContractLedger(bundleDir) {
10421
10521
  let raw;
10422
10522
  try {
10423
- raw = await readFile3(path, "utf8");
10424
- } catch (error) {
10425
- if (isMissingFile(error)) return null;
10426
- throw error;
10523
+ raw = await readFile3(join3(bundleDir, CONTRACT_LEDGER_PATH), "utf8");
10524
+ } catch {
10525
+ return null;
10427
10526
  }
10527
+ let parsed;
10428
10528
  try {
10429
- return parseCredentials(JSON.parse(raw));
10529
+ parsed = JSON.parse(raw);
10430
10530
  } catch {
10431
10531
  return null;
10432
10532
  }
10433
- }
10434
- async function readCredentials() {
10435
- const primary = await readCredentialsFile(credentialsPath());
10436
- if (primary !== null) return primary;
10437
- if (configDirOverride() !== void 0) return null;
10438
- const legacyPath = join3(legacyConfigDir(), CREDENTIALS_FILE);
10439
- if (legacyPath === credentialsPath()) return null;
10440
- return readCredentialsFile(legacyPath);
10441
- }
10442
- async function writeCredentials(credentials) {
10443
- const directory = configDir();
10444
- await mkdir2(directory, { recursive: true, mode: 448 });
10445
- const target = credentialsPath();
10446
- await writeFile2(target, `${JSON.stringify(credentials, null, 2)}
10447
- `, {
10448
- encoding: "utf8",
10449
- mode: 384
10533
+ const record = objectValue(parsed);
10534
+ if (record === null || record.schemaVersion !== 1) return null;
10535
+ const local = objectValue(record.local);
10536
+ if (local === null) return null;
10537
+ const files = objectValue(local.files) ?? {};
10538
+ const normalizeSnapshot = (value) => ({
10539
+ prd: typeof value.prd === "string" ? value.prd : null,
10540
+ specs: typeof value.specs === "string" ? value.specs : null,
10541
+ tasks: typeof value.tasks === "string" ? value.tasks : null,
10542
+ files: Object.fromEntries(
10543
+ Object.entries(files).filter(
10544
+ (entry) => typeof entry[1] === "string"
10545
+ )
10546
+ )
10450
10547
  });
10451
- await chmod(target, 384);
10452
- }
10453
- async function clearCredentials() {
10454
- const removed = await removeCredentialsFile(credentialsPath());
10455
- const legacyPath = join3(legacyConfigDir(), CREDENTIALS_FILE);
10456
- if (legacyPath === credentialsPath()) return removed;
10457
- const removedLegacy = await removeCredentialsFile(legacyPath);
10458
- return removed || removedLegacy;
10459
- }
10460
- async function removeCredentialsFile(path) {
10461
- try {
10462
- await rm2(path);
10463
- return true;
10464
- } catch (error) {
10465
- if (isMissingFile(error)) return false;
10466
- throw error;
10467
- }
10468
- }
10469
- function parseProjectLink(value, bundleDir) {
10470
- if (!isRecord(value)) return null;
10471
- const { projectId, apiUrl } = value;
10472
- if (typeof projectId !== "string" || projectId.length === 0) return null;
10473
- if (typeof apiUrl !== "string" || apiUrl.length === 0) return null;
10474
- const execution = isRecord(value.execution) ? value.execution : {};
10548
+ const serverRecord = objectValue(record.server);
10549
+ const server = serverRecord === null ? null : {
10550
+ prd: typeof serverRecord.prd === "string" ? serverRecord.prd : null,
10551
+ specs: typeof serverRecord.specs === "string" ? serverRecord.specs : null,
10552
+ tasks: typeof serverRecord.tasks === "string" ? serverRecord.tasks : null,
10553
+ derivation: parseDerivation(serverRecord.derivation)
10554
+ };
10475
10555
  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
- }
10556
+ schemaVersion: 1,
10557
+ at: typeof record.at === "string" ? record.at : "",
10558
+ local: normalizeSnapshot(local),
10559
+ server,
10560
+ derivation: parseDerivation(record.derivation) ?? { specs: null, tasks: null }
10485
10561
  };
10486
10562
  }
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
- });
10563
+ async function writeContractLedger(bundleDir, ledger) {
10564
+ const target = join3(bundleDir, CONTRACT_LEDGER_PATH);
10565
+ await mkdir2(dirname2(target), { recursive: true });
10566
+ await writeFile2(target, `${JSON.stringify(ledger, null, 2)}
10567
+ `, "utf8");
10514
10568
  }
10515
- function parseTaskMode(value) {
10516
- if (value === void 0) return DEFAULT_TASK_MODE;
10517
- const parsed = TaskModeSchema.safeParse(value);
10518
- if (!parsed.success) {
10519
- throw new Error(`Project link taskMode tidak valid: ${String(value)}`);
10520
- }
10521
- return parsed.data;
10569
+ function buildContractLedger(local, server, derivation, now = /* @__PURE__ */ new Date()) {
10570
+ return {
10571
+ schemaVersion: 1,
10572
+ at: now.toISOString(),
10573
+ local,
10574
+ server,
10575
+ derivation: derivation ?? server?.derivation ?? freshDerivation(local, now)
10576
+ };
10522
10577
  }
10523
- async function readProjectLink(bundleDir) {
10524
- for (const directoryName of [PROJECT_DIR, LEGACY_PROJECT_DIR]) {
10525
- const candidate = join3(bundleDir, directoryName, PROJECT_FILE);
10526
- let raw = null;
10527
- try {
10528
- raw = await readFile3(candidate, "utf8");
10529
- } catch (error) {
10530
- if (!isMissingFile(error)) throw error;
10531
- }
10532
- if (raw === null) continue;
10533
- let parsed;
10534
- try {
10535
- parsed = JSON.parse(raw);
10536
- } catch {
10537
- throw new Error(`Project link is not valid JSON: ${candidate}`);
10538
- }
10539
- const link = parseProjectLink(parsed, bundleDir);
10540
- if (link === null) throw new Error(`Project link is invalid: ${candidate}`);
10541
- return link;
10578
+ async function readApproval(bundleDir) {
10579
+ let raw;
10580
+ try {
10581
+ raw = await readFile3(join3(bundleDir, APPROVALS_PATH), "utf8");
10582
+ } catch {
10583
+ return null;
10542
10584
  }
10543
- return null;
10544
- }
10545
- async function findProjectLink(startDir) {
10546
- let directory = resolve2(startDir);
10547
- for (; ; ) {
10548
- const link = await readProjectLink(directory);
10549
- if (link !== null) return link;
10550
- const parent = dirname2(directory);
10551
- if (parent === directory) return null;
10552
- directory = parent;
10585
+ let parsed;
10586
+ try {
10587
+ parsed = JSON.parse(raw);
10588
+ } catch {
10589
+ return null;
10553
10590
  }
10591
+ const record = objectValue(parsed);
10592
+ if (record === null || record.schemaVersion !== 1) return null;
10593
+ const prd = objectValue(record.prd);
10594
+ return {
10595
+ schemaVersion: 1,
10596
+ prd: prd !== null && typeof prd.hash === "string" ? {
10597
+ hash: prd.hash,
10598
+ at: typeof prd.at === "string" ? prd.at : "",
10599
+ ...typeof prd.note === "string" ? { note: prd.note } : {}
10600
+ } : null
10601
+ };
10554
10602
  }
10555
- async function writeProjectLink(bundleDir, link) {
10556
- const directory = join3(resolve2(bundleDir), PROJECT_DIR);
10557
- await mkdir2(directory, { recursive: true });
10558
- await writeFile2(
10559
- join3(directory, PROJECT_FILE),
10560
- `${JSON.stringify(
10561
- {
10562
- projectId: link.projectId,
10563
- apiUrl: link.apiUrl,
10564
- taskMode: link.taskMode ?? DEFAULT_TASK_MODE,
10565
- execution: {
10566
- uiQuality: link.execution?.uiQuality ?? DEFAULT_UI_QUALITY,
10567
- autoMode: link.execution?.autoMode ?? false
10568
- }
10569
- },
10570
- null,
10571
- 2
10572
- )}
10573
- `,
10574
- "utf8"
10575
- );
10603
+ async function writeApproval(bundleDir, record) {
10604
+ const target = join3(bundleDir, APPROVALS_PATH);
10605
+ await mkdir2(dirname2(target), { recursive: true });
10606
+ await writeFile2(target, `${JSON.stringify(record, null, 2)}
10607
+ `, "utf8");
10576
10608
  }
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
- }
10609
+ async function appendApprovalNote(bundleDir, input) {
10610
+ const target = join3(bundleDir, ".jioogen", "custom", "knowledge", "approved-patches.md");
10611
+ await mkdir2(dirname2(target), { recursive: true });
10612
+ let existing = "";
10613
+ try {
10614
+ existing = await readFile3(target, "utf8");
10615
+ } catch {
10616
+ existing = "# Approved local patches\n";
10587
10617
  }
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
- }
10594
- async function readTaskMode(bundleDir) {
10595
- const link = await readProjectLink(resolve2(bundleDir));
10596
- return link?.taskMode ?? DEFAULT_TASK_MODE;
10597
- }
10598
- function isMissingFile(error) {
10599
- return isRecord(error) && error.code === "ENOENT";
10618
+ const lines = [
10619
+ existing.trimEnd(),
10620
+ "",
10621
+ `## ${input.at} \u2014 PRD lokal disetujui untuk sinkron`,
10622
+ "",
10623
+ `- PRD.md: \`${input.prdHash}\``,
10624
+ ...input.note === void 0 || input.note.length === 0 ? [] : [`- Catatan: ${input.note}`],
10625
+ ""
10626
+ ];
10627
+ await writeFile2(target, `${lines.join("\n")}`, "utf8");
10600
10628
  }
10601
10629
 
10602
- // src/doctor.ts
10603
- import { readdir as readdir6, readFile as readFile8, rm as rm6, stat as stat5 } from "node:fs/promises";
10604
- import { join as join8 } from "node:path";
10605
-
10606
10630
  // src/drift.ts
10607
- import { createHash } from "node:crypto";
10608
- import { mkdir as mkdir4, readdir as readdir4, readFile as readFile6, rm as rm4, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
10631
+ import { createHash as createHash2 } from "node:crypto";
10632
+ import { mkdir as mkdir4, readdir as readdir5, readFile as readFile6, rm as rm3, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
10609
10633
  import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6 } from "node:path";
10610
10634
 
10611
10635
  // src/tasks.ts
10612
10636
  import { readdirSync, readFileSync } from "node:fs";
10613
- import { readdir as readdir3, readFile as readFile5, stat as stat2 } from "node:fs/promises";
10637
+ import { readdir as readdir4, readFile as readFile5, stat as stat2 } from "node:fs/promises";
10614
10638
  import { isAbsolute, join as join5 } from "node:path";
10615
10639
 
10616
10640
  // src/sidecar.ts
10617
10641
  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";
10642
+ import { mkdir as mkdir3, open, readFile as readFile4, rename, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
10619
10643
  import { dirname as dirname3, join as join4 } from "node:path";
10620
10644
  var LOCK_RETRY_MS = 25;
10621
10645
  var LOCK_TIMEOUT_MS = 3e3;
@@ -10656,7 +10680,7 @@ async function withStateLock(bundleDir, fn) {
10656
10680
  } finally {
10657
10681
  await handle.close().catch(() => {
10658
10682
  });
10659
- await rm3(target, { force: true }).catch(() => {
10683
+ await rm2(target, { force: true }).catch(() => {
10660
10684
  });
10661
10685
  }
10662
10686
  }
@@ -10665,7 +10689,7 @@ async function readState(bundleDir) {
10665
10689
  try {
10666
10690
  raw = await readFile4(sidecarPath(bundleDir), "utf8");
10667
10691
  } catch (error) {
10668
- if (isMissingFile2(error)) return null;
10692
+ if (isMissingFile(error)) return null;
10669
10693
  throw error;
10670
10694
  }
10671
10695
  let payload;
@@ -10837,7 +10861,7 @@ async function writeState(bundleDir, state) {
10837
10861
  `, "utf8");
10838
10862
  await rename(temp, target);
10839
10863
  } catch (error) {
10840
- await rm3(temp, { force: true }).catch(() => {
10864
+ await rm2(temp, { force: true }).catch(() => {
10841
10865
  });
10842
10866
  throw error;
10843
10867
  }
@@ -10896,7 +10920,7 @@ function completionDefinitions(definitions) {
10896
10920
  ...definition.layer !== void 0 ? { layer: definition.layer } : {}
10897
10921
  }));
10898
10922
  }
10899
- function isMissingFile2(error) {
10923
+ function isMissingFile(error) {
10900
10924
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
10901
10925
  }
10902
10926
  function isLockBusy(error) {
@@ -10906,10 +10930,10 @@ async function removeStaleLock(target) {
10906
10930
  try {
10907
10931
  const info = await stat(target);
10908
10932
  if (Date.now() - info.mtimeMs < LOCK_STALE_MS) return false;
10909
- await rm3(target, { force: true });
10933
+ await rm2(target, { force: true });
10910
10934
  return true;
10911
10935
  } catch (error) {
10912
- if (isMissingFile2(error)) return true;
10936
+ if (isMissingFile(error)) return true;
10913
10937
  throw error;
10914
10938
  }
10915
10939
  }
@@ -10983,9 +11007,9 @@ async function loadTasks(bundleDir) {
10983
11007
  const tasksDir = join5(bundleDir, "tasks");
10984
11008
  let entries;
10985
11009
  try {
10986
- entries = await readdir3(tasksDir, { withFileTypes: true });
11010
+ entries = await readdir4(tasksDir, { withFileTypes: true });
10987
11011
  } catch (error) {
10988
- if (isMissingFile3(error)) throw new Error(`Direktori tasks/ tidak ditemukan di ${bundleDir}`);
11012
+ if (isMissingFile2(error)) throw new Error(`Direktori tasks/ tidak ditemukan di ${bundleDir}`);
10989
11013
  throw error;
10990
11014
  }
10991
11015
  const names = entries.filter(
@@ -11003,7 +11027,7 @@ async function loadTasks(bundleDir) {
11003
11027
  try {
11004
11028
  content = await readFile5(singlePath, "utf8");
11005
11029
  } catch (error) {
11006
- if (isMissingFile3(error)) throw new Error(`Tidak ada berkas task di ${tasksDir}`);
11030
+ if (isMissingFile2(error)) throw new Error(`Tidak ada berkas task di ${tasksDir}`);
11007
11031
  throw error;
11008
11032
  }
11009
11033
  tasks.push(...parseSingleFile(content));
@@ -11424,11 +11448,13 @@ function buildCustomKnowledgeBlock(bundleDir) {
11424
11448
  const lines = [
11425
11449
  CUSTOM_KNOWLEDGE_HEADER,
11426
11450
  ...files.map((file) => `- ${file}`),
11427
- "Baca file-file di atas sebagai konteks tambahan user sebelum coding."
11451
+ "Baca file-file di atas sebagai konteks tambahan user sebelum coding.",
11452
+ "Setiap pertanyaan ke user pakai bahasa manusia yang mudah: kalimat pendek, ya/tidak atau pilihan A/B, tanpa jargon teknis.",
11453
+ "Bila user menyetujui patch kontrak, jalankan `jioogen approve --note <alasan>` lalu ubah PRD.md; setelah itu `jioogen align` otomatis menurunkan specs dan tasks, memvalidasi, dan menyelaraskan web. Jangan edit specs/tasks manual dan jangan `jioogen pull --force`."
11428
11454
  ];
11429
11455
  return lines.join("\n");
11430
11456
  }
11431
- function isMissingFile3(error) {
11457
+ function isMissingFile2(error) {
11432
11458
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
11433
11459
  }
11434
11460
 
@@ -11541,7 +11567,7 @@ async function writeBaseline(bundleDir, baseline) {
11541
11567
  `, "utf8");
11542
11568
  }
11543
11569
  async function clearBaseline(bundleDir) {
11544
- await rm4(baselinePath(bundleDir), { force: true });
11570
+ await rm3(baselinePath(bundleDir), { force: true });
11545
11571
  }
11546
11572
  async function captureTaskBaseline(bundleDir, definition, now = /* @__PURE__ */ new Date()) {
11547
11573
  const baseline = await readBaseline(bundleDir) ?? {
@@ -11591,7 +11617,7 @@ async function detectDrift(bundleDir, definitions, state, options = {}) {
11591
11617
  findings.push({
11592
11618
  code: "BUNDLE_DRIFT",
11593
11619
  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.",
11620
+ message: "PRD.md/specs/tasks berubah di disk setelah baseline dibuat. Kalau disengaja, jalankan `jioogen align` (patch lokal disetujui) atau `jioogen drift --acknowledge`; kalau tidak, kembalikan file itu.",
11595
11621
  files: []
11596
11622
  });
11597
11623
  }
@@ -11670,8 +11696,8 @@ async function targetHashes(bundleDir, patterns) {
11670
11696
  }
11671
11697
  const hashes = {};
11672
11698
  for (const file of [...files].sort()) {
11673
- const fingerprint = await fingerprintRelative(bundleDir, file);
11674
- if (fingerprint !== null) hashes[file] = fingerprint;
11699
+ const fingerprint2 = await fingerprintRelative(bundleDir, file);
11700
+ if (fingerprint2 !== null) hashes[file] = fingerprint2;
11675
11701
  }
11676
11702
  return { hashes, truncated };
11677
11703
  }
@@ -11736,11 +11762,11 @@ function globToRegExp(pattern) {
11736
11762
  async function walk(bundleDir, start, limit) {
11737
11763
  const files = [];
11738
11764
  let truncated = false;
11739
- const visit = async (relative2) => {
11765
+ const visit = async (relative3) => {
11740
11766
  if (truncated) return;
11741
11767
  let entries;
11742
11768
  try {
11743
- entries = await readdir4(relative2.length === 0 ? bundleDir : join6(bundleDir, relative2), {
11769
+ entries = await readdir5(relative3.length === 0 ? bundleDir : join6(bundleDir, relative3), {
11744
11770
  withFileTypes: true
11745
11771
  });
11746
11772
  } catch {
@@ -11748,7 +11774,7 @@ async function walk(bundleDir, start, limit) {
11748
11774
  }
11749
11775
  entries.sort((left, right) => left.name.localeCompare(right.name));
11750
11776
  for (const entry of entries) {
11751
- const child = relative2.length === 0 ? entry.name : `${relative2}/${entry.name}`;
11777
+ const child = relative3.length === 0 ? entry.name : `${relative3}/${entry.name}`;
11752
11778
  if (entry.isDirectory()) {
11753
11779
  if (IGNORED_DIRS.has(entry.name)) continue;
11754
11780
  if (child === "tasks/.execution") continue;
@@ -11765,67 +11791,730 @@ async function walk(bundleDir, start, limit) {
11765
11791
  await visit(start);
11766
11792
  return { files, truncated };
11767
11793
  }
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)}`;
11794
+ async function fingerprintRelative(bundleDir, relative3) {
11795
+ const info = await statMaybe(join6(bundleDir, relative3));
11796
+ if (info === null || !info.isFile()) return null;
11797
+ return `${info.size}:${Math.trunc(info.mtimeMs)}`;
11798
+ }
11799
+ async function hashRelative(bundleDir, relative3) {
11800
+ const info = await statMaybe(join6(bundleDir, relative3));
11801
+ if (info === null || !info.isFile()) return null;
11802
+ if (info.size > MAX_BUNDLE_FILE_BYTES) return `size:${info.size}`;
11803
+ try {
11804
+ const bytes = await readFile6(join6(bundleDir, relative3));
11805
+ return createHash2("sha256").update(bytes).digest("hex");
11806
+ } catch {
11807
+ return null;
11808
+ }
11809
+ }
11810
+ async function statMaybe(path) {
11811
+ try {
11812
+ return await stat3(path);
11813
+ } catch {
11814
+ return null;
11815
+ }
11816
+ }
11817
+ function diffHashes(before, after) {
11818
+ const changed = /* @__PURE__ */ new Set();
11819
+ for (const [path, hash] of Object.entries(before)) {
11820
+ if (after[path] !== hash) changed.add(path);
11821
+ }
11822
+ for (const path of Object.keys(after)) {
11823
+ if (!(path in before)) changed.add(path);
11824
+ }
11825
+ return [...changed].sort();
11826
+ }
11827
+ async function bundleHashOf(bundleDir) {
11828
+ const files = [];
11829
+ for (const name of ["PRD.md", "traceability.md"]) {
11830
+ const info = await statMaybe(join6(bundleDir, name));
11831
+ if (info?.isFile()) files.push(name);
11832
+ }
11833
+ for (const directory of ["specs", "tasks"]) {
11834
+ const walked = await walk(bundleDir, directory, MAX_TARGET_FILES);
11835
+ for (const file of walked.files) {
11836
+ if (file.startsWith("tasks/.execution/")) continue;
11837
+ if (IGNORED_TOP_FILES.has(file)) continue;
11838
+ if (!file.toLowerCase().endsWith(".md")) continue;
11839
+ files.push(file);
11840
+ }
11841
+ }
11842
+ const lines = [];
11843
+ for (const file of files.sort()) {
11844
+ const hash = await hashRelative(bundleDir, file);
11845
+ if (hash !== null) lines.push(`${file}\0${hash}`);
11846
+ }
11847
+ return createHash2("sha256").update(lines.join("\n")).digest("hex");
11848
+ }
11849
+
11850
+ // src/align.ts
11851
+ function serverStateFromWorkspace(state) {
11852
+ const files = {};
11853
+ for (const artifact of state.artifacts) files[artifact.filePath] = artifact.sha256Hash;
11854
+ return {
11855
+ prd: state.derivation.prdHash ?? files["PRD.md"] ?? null,
11856
+ specs: fingerprint(files, (path) => path.startsWith("specs/")),
11857
+ tasks: fingerprint(files, (path) => path.startsWith("tasks/") || path === "traceability.md"),
11858
+ derivation: parseDerivation(state.derivation)
11859
+ };
11860
+ }
11861
+ async function fetchServerState(deps) {
11862
+ if (deps.client === void 0 || deps.projectId === void 0) return null;
11863
+ try {
11864
+ return serverStateFromWorkspace(await deps.client.getWorkspaceArtifacts(deps.projectId));
11865
+ } catch {
11866
+ return null;
11867
+ }
11868
+ }
11869
+ async function mtime(bundleDir, relative3) {
11870
+ try {
11871
+ return (await stat4(join7(bundleDir, relative3))).mtimeMs;
11872
+ } catch {
11873
+ return 0;
11874
+ }
11875
+ }
11876
+ async function mtimeDerivation(bundleDir, local) {
11877
+ if (local.prd === null) return freshDerivation(local);
11878
+ const prd = await mtime(bundleDir, "PRD.md");
11879
+ let specs = 0;
11880
+ let tasks = await mtime(bundleDir, "traceability.md");
11881
+ for (const path of Object.keys(local.files)) {
11882
+ const value = await mtime(bundleDir, path);
11883
+ if (path.startsWith("specs/")) specs = Math.max(specs, value);
11884
+ if (path.startsWith("tasks/")) tasks = Math.max(tasks, value);
11885
+ }
11886
+ const at = (/* @__PURE__ */ new Date()).toISOString();
11887
+ const staleMark = `mtime-stale-${at}`;
11888
+ return {
11889
+ specs: local.specs === null ? null : { prdHash: prd > specs ? staleMark : local.prd, recordedAt: at },
11890
+ tasks: local.tasks === null ? null : {
11891
+ prdHash: prd > tasks ? staleMark : local.prd,
11892
+ ...local.specs === null ? {} : { specsFingerprint: specs > tasks ? staleMark : local.specs },
11893
+ recordedAt: at
11894
+ }
11895
+ };
11896
+ }
11897
+ async function loadLedger(bundleDir, local, server) {
11898
+ const existing = await readContractLedger(bundleDir);
11899
+ if (existing !== null) {
11900
+ return { ...existing, local };
11901
+ }
11902
+ const derivation = server?.derivation ?? await mtimeDerivation(bundleDir, local);
11903
+ return buildContractLedger(local, server, derivation);
11904
+ }
11905
+ function issuesForStage(check, stage) {
11906
+ return check.issues.filter((issue2) => issue2.owner === stage).map((issue2) => `${issue2.code}: ${issue2.where} \u2014 ${issue2.message}`);
11907
+ }
11908
+ function planAlignment(local, ledger, server, check) {
11909
+ const localChanges = changedSince(local, ledger.local);
11910
+ const previousServer = ledger.server === null ? null : serverAsSnapshot(ledger.server);
11911
+ const serverChanges = server === null || previousServer === null ? { prd: false, specs: false, tasks: false, any: false } : changedSince(serverAsSnapshot(server), previousServer);
11912
+ if (localChanges.prd && serverChanges.prd && local.prd !== server?.prd) {
11913
+ return {
11914
+ kind: "conflict",
11915
+ message: "PRD berubah di lokal dan di web sekaligus. Pilih satu versi (lokal atau web) sebelum menyelaraskan."
11916
+ };
11917
+ }
11918
+ if (localChanges.any && serverChanges.any) {
11919
+ return {
11920
+ kind: "conflict",
11921
+ message: "Ada perubahan lokal dan perubahan web pada artefak kontrak. Selesaikan konflik versi dulu agar tidak ada yang tertimpa."
11922
+ };
11923
+ }
11924
+ const staleness = computeStaleness(ledger.derivation, local);
11925
+ if (staleness.specsStale) {
11926
+ return {
11927
+ kind: "author",
11928
+ stage: "specs",
11929
+ reason: "PRD berubah; specs masih dari versi PRD lama."
11930
+ };
11931
+ }
11932
+ if (staleness.tasksStale) {
11933
+ return {
11934
+ kind: "author",
11935
+ stage: "tasks",
11936
+ reason: "Specs/PRD berubah; tasks masih dari versi lama."
11937
+ };
11938
+ }
11939
+ if (serverChanges.any) {
11940
+ return { kind: "pull", reason: "Web punya perubahan kontrak yang belum ada di lokal." };
11941
+ }
11942
+ if (!check.ok) {
11943
+ const owners = new Set(check.issues.map((issue2) => issue2.owner));
11944
+ const repairable = owners.size > 0 && [...owners].every((owner) => owner === "specs" || owner === "tasks");
11945
+ if (repairable) {
11946
+ const stage = owners.has("tasks") ? "tasks" : "specs";
11947
+ if ((stage === "tasks" ? local.tasks : local.specs) !== null) {
11948
+ return {
11949
+ kind: "author",
11950
+ stage,
11951
+ reason: `Gate gagal pada artefak ${stage}; perbaiki turunannya.`
11952
+ };
11953
+ }
11954
+ }
11955
+ return { kind: "gate", check };
11956
+ }
11957
+ const pushChanges = server === null ? localChanges : changedSince(local, serverAsSnapshot(server));
11958
+ if (pushChanges.any) {
11959
+ return {
11960
+ kind: "push",
11961
+ stages: pushChanges,
11962
+ reason: "Kontrak lokal berbeda dari web dan sudah lolos gate; selaraskan ke web."
11963
+ };
11964
+ }
11965
+ return { kind: "clean" };
11966
+ }
11967
+ async function readContractFiles(bundleDir, snapshot, stages) {
11968
+ const files = [];
11969
+ for (const path of Object.keys(snapshot.files).sort()) {
11970
+ const isPrd = path === "PRD.md";
11971
+ const isSpecs = path.startsWith("specs/");
11972
+ const isTasks = path.startsWith("tasks/") || path === "traceability.md";
11973
+ if (isPrd && !stages.prd) continue;
11974
+ if (isSpecs && !stages.specs) continue;
11975
+ if (isTasks && !stages.tasks) continue;
11976
+ files.push({ path, content: await readFile7(join7(bundleDir, path), "utf8") });
11977
+ }
11978
+ try {
11979
+ const state = await readFile7(join7(bundleDir, EXECUTION_SIDECAR_PATH), "utf8");
11980
+ files.push({ path: EXECUTION_SIDECAR_PATH, content: state });
11981
+ } catch {
11982
+ }
11983
+ return files;
11984
+ }
11985
+ async function pushContract(deps, bundleDir, snapshot, stages, server) {
11986
+ if (deps.client === void 0 || deps.projectId === void 0) {
11987
+ return { ok: false, error: "Project belum terhubung ke API; sinkronisasi web dilewati." };
11988
+ }
11989
+ const approval = await readApproval(bundleDir);
11990
+ if (stages.prd && server !== null && server.prd !== snapshot.prd) {
11991
+ const confirmation = await deps.client.getPrdConfirmation(deps.projectId).catch(() => null);
11992
+ if (confirmation?.confirmation.confirmed === true) {
11993
+ if (approval?.prd?.hash !== snapshot.prd) {
11994
+ return {
11995
+ ok: false,
11996
+ needsApproval: true,
11997
+ error: "PRD lokal berbeda dari PRD yang dikonfirmasi di web."
11998
+ };
11999
+ }
12000
+ await deps.client.revokePrdConfirmation(
12001
+ deps.projectId,
12002
+ "PRD lokal disetujui user untuk diselaraskan."
12003
+ );
12004
+ }
12005
+ }
12006
+ const files = await readContractFiles(bundleDir, snapshot, stages);
12007
+ let result;
12008
+ try {
12009
+ result = await deps.client.postJson(projectPath(deps.projectId, "/artifacts"), {
12010
+ files
12011
+ });
12012
+ } catch (error) {
12013
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
12014
+ }
12015
+ const rejected = result.rejected ?? [];
12016
+ const prdRejected = rejected.find((entry) => entry.path === "PRD.md");
12017
+ if (prdRejected !== void 0) {
12018
+ return {
12019
+ ok: false,
12020
+ needsApproval: prdRejected.code === "PRD_CONFIRMED",
12021
+ error: prdRejected.reason
12022
+ };
12023
+ }
12024
+ const blocked = rejected.filter((entry) => entry.code !== "PRD_CONFIRMED");
12025
+ if (blocked.length > 0) {
12026
+ return {
12027
+ ok: false,
12028
+ error: blocked.map((entry) => `${entry.path}: ${entry.reason}`).join(" | ")
12029
+ };
12030
+ }
12031
+ return { ok: true };
12032
+ }
12033
+ async function pullContract(deps, bundleDir) {
12034
+ if (deps.client === void 0 || deps.projectId === void 0) {
12035
+ return "Project belum terhubung ke API; tidak bisa menarik versi web.";
12036
+ }
12037
+ try {
12038
+ const listing = await deps.client.getWorkspaceArtifacts(deps.projectId);
12039
+ const wanted = listing.files.filter(
12040
+ (path) => path === "PRD.md" || path === "traceability.md" || path.startsWith("specs/") || path.startsWith("tasks/")
12041
+ );
12042
+ const contents = /* @__PURE__ */ new Map();
12043
+ for (const path of wanted) {
12044
+ if (path.includes("..") || path.startsWith("/")) continue;
12045
+ const response = await deps.client.getJson(
12046
+ projectPath(deps.projectId, `/artifacts?path=${encodeURIComponent(path)}`)
12047
+ );
12048
+ contents.set(path, response.artifact.content);
12049
+ }
12050
+ const local = await snapshotContract(bundleDir);
12051
+ for (const path of Object.keys(local.files)) {
12052
+ if (!contents.has(path)) await rm4(join7(bundleDir, path), { force: true });
12053
+ }
12054
+ for (const [path, content] of contents) {
12055
+ const target = join7(bundleDir, path);
12056
+ await mkdir5(join7(target, ".."), { recursive: true });
12057
+ await writeFile5(target, content, "utf8");
12058
+ }
12059
+ await clearBaseline(bundleDir).catch(() => {
12060
+ });
12061
+ return null;
12062
+ } catch (error) {
12063
+ return error instanceof Error ? error.message : String(error);
12064
+ }
12065
+ }
12066
+ function authoringPrompt(stage, issues) {
12067
+ const target = stage === "specs" ? "specs/" : "tasks/";
12068
+ const forbidden = stage === "specs" ? "PRD.md dan tasks/" : "PRD.md dan specs/";
12069
+ const lines = [
12070
+ `Stage authoring lokal: ${stage}.`,
12071
+ `Baca PRD.md${stage === "tasks" ? " dan specs/" : ""}, lalu tulis ulang ${target} agar selaras dengan kontrak terbaru.`,
12072
+ `Jangan mengubah ${forbidden}.`,
12073
+ "Gunakan skill authoring yang tersedia, jalankan self-check, dan pastikan hanya file di target yang ditulis."
12074
+ ];
12075
+ if (issues.length > 0) {
12076
+ lines.push(
12077
+ "",
12078
+ "Temuan gate yang harus ditutup:",
12079
+ ...issues.slice(0, 40).map((issue2) => `- ${issue2}`)
12080
+ );
12081
+ }
12082
+ return lines.join("\n");
12083
+ }
12084
+ function authoringTimeoutMs() {
12085
+ const raw = process.env.JIOOGEN_ALIGN_TIMEOUT_MS;
12086
+ const value = raw === void 0 ? Number.NaN : Number(raw);
12087
+ return Number.isFinite(value) && value > 0 ? value : 30 * 60 * 1e3;
12088
+ }
12089
+ async function runLocalAuthoring(stage, bundleDir, issues) {
12090
+ const configDir2 = join7(bundleDir, ".jioogen", "align");
12091
+ const configPath = join7(configDir2, "opencode.json");
12092
+ await mkdir5(configDir2, { recursive: true });
12093
+ const config = await buildAuthoringOpencodeConfig(bundledAuthoringPackDir());
12094
+ await writeFile5(configPath, `${JSON.stringify(config, null, 2)}
12095
+ `, "utf8");
12096
+ const bin = process.env.OPENCODE_BIN?.trim() || "opencode";
12097
+ const args = [
12098
+ "run",
12099
+ "--agent",
12100
+ "build",
12101
+ "--format",
12102
+ "json",
12103
+ "--dir",
12104
+ bundleDir,
12105
+ authoringPrompt(stage, issues)
12106
+ ];
12107
+ return new Promise((resolve7) => {
12108
+ const child = spawn(bin, args, {
12109
+ cwd: bundleDir,
12110
+ env: {
12111
+ ...process.env,
12112
+ OPENCODE_CONFIG: configPath,
12113
+ OPENCODE_DISABLE_CLAUDE_CODE: "1"
12114
+ },
12115
+ stdio: ["ignore", "ignore", "pipe"]
12116
+ });
12117
+ let stderr = "";
12118
+ let settled = false;
12119
+ const finish = (result) => {
12120
+ if (settled) return;
12121
+ settled = true;
12122
+ clearTimeout(timer);
12123
+ resolve7(result);
12124
+ };
12125
+ const timer = setTimeout(() => {
12126
+ child.kill("SIGTERM");
12127
+ setTimeout(() => child.kill("SIGKILL"), 5e3).unref();
12128
+ finish({ ok: false, error: `Authoring ${stage} melewati batas waktu.` });
12129
+ }, authoringTimeoutMs());
12130
+ timer.unref();
12131
+ child.stderr.on("data", (chunk) => {
12132
+ stderr = `${stderr}${chunk.toString()}`.slice(-4e3);
12133
+ });
12134
+ child.on("error", (error) => finish({ ok: false, error: error.message }));
12135
+ child.on("close", (code) => {
12136
+ finish(
12137
+ code === 0 ? { ok: true } : {
12138
+ ok: false,
12139
+ error: `Authoring ${stage} gagal (exit ${code ?? "?"}). ${stderr.trim()}`
12140
+ }
12141
+ );
12142
+ });
12143
+ });
12144
+ }
12145
+ async function alignBundle(bundleDir, deps = {}) {
12146
+ const applied = [];
12147
+ let local = await snapshotContract(bundleDir);
12148
+ let server = await fetchServerState(deps);
12149
+ let ledger = await loadLedger(bundleDir, local, server);
12150
+ let check = await inspectBundle(bundleDir);
12151
+ const runAuthoring = deps.runAuthoring ?? runLocalAuthoring;
12152
+ const attempted = /* @__PURE__ */ new Set();
12153
+ for (let step = 0; step < 6; step += 1) {
12154
+ const plan = planAlignment(local, ledger, server, check);
12155
+ if (plan.kind === "clean") {
12156
+ await writeContractLedger(bundleDir, {
12157
+ ...ledger,
12158
+ local,
12159
+ server,
12160
+ at: (/* @__PURE__ */ new Date()).toISOString()
12161
+ });
12162
+ return { ok: true, applied, check, ledger };
12163
+ }
12164
+ if (plan.kind === "gate") {
12165
+ return { ok: false, applied, blocked: "Bundle belum lolos gate.", check, ledger };
12166
+ }
12167
+ if (plan.kind === "conflict") {
12168
+ return { ok: false, applied, blocked: plan.message, check, ledger };
12169
+ }
12170
+ if (plan.kind === "approve") {
12171
+ return { ok: false, applied, blocked: plan.reason, check, ledger };
12172
+ }
12173
+ if (plan.kind === "author") {
12174
+ if (attempted.has(plan.stage)) {
12175
+ return {
12176
+ ok: false,
12177
+ applied,
12178
+ blocked: `Gate masih gagal setelah authoring ${plan.stage}.`,
12179
+ check,
12180
+ ledger
12181
+ };
12182
+ }
12183
+ attempted.add(plan.stage);
12184
+ const result = await runAuthoring(plan.stage, bundleDir, issuesForStage(check, plan.stage));
12185
+ if (!result.ok) {
12186
+ return {
12187
+ ok: false,
12188
+ applied,
12189
+ blocked: result.error ?? `Authoring ${plan.stage} gagal.`,
12190
+ check,
12191
+ ledger
12192
+ };
12193
+ }
12194
+ applied.push(`author:${plan.stage}`);
12195
+ local = await snapshotContract(bundleDir);
12196
+ const at = (/* @__PURE__ */ new Date()).toISOString();
12197
+ ledger = {
12198
+ ...ledger,
12199
+ local,
12200
+ derivation: plan.stage === "specs" ? {
12201
+ ...ledger.derivation,
12202
+ specs: local.prd === null ? null : { prdHash: local.prd, recordedAt: at }
12203
+ } : {
12204
+ ...ledger.derivation,
12205
+ tasks: local.prd === null || local.tasks === null ? null : {
12206
+ prdHash: local.prd,
12207
+ ...local.specs === null ? {} : { specsFingerprint: local.specs },
12208
+ recordedAt: at
12209
+ }
12210
+ }
12211
+ };
12212
+ await writeContractLedger(bundleDir, ledger);
12213
+ check = await inspectBundle(bundleDir);
12214
+ continue;
12215
+ }
12216
+ if (plan.kind === "pull") {
12217
+ const error = await pullContract(deps, bundleDir);
12218
+ if (error !== null) {
12219
+ return { ok: false, applied, blocked: error, check, ledger };
12220
+ }
12221
+ applied.push("pull");
12222
+ local = await snapshotContract(bundleDir);
12223
+ server = await fetchServerState(deps);
12224
+ ledger = await loadLedger(bundleDir, local, server);
12225
+ await writeContractLedger(bundleDir, ledger);
12226
+ check = await inspectBundle(bundleDir);
12227
+ continue;
12228
+ }
12229
+ if (plan.kind === "push") {
12230
+ const approval = await readApproval(bundleDir);
12231
+ if (plan.stages.prd && server !== null && server.prd !== local.prd && approval?.prd?.hash !== local.prd) {
12232
+ return {
12233
+ ok: false,
12234
+ applied,
12235
+ blocked: "PRD lokal berubah. Boleh saya kirim versi lokal ke web? (ya/tidak)",
12236
+ check,
12237
+ ledger
12238
+ };
12239
+ }
12240
+ const result = await pushContract(deps, bundleDir, local, plan.stages, server);
12241
+ if (!result.ok) {
12242
+ return {
12243
+ ok: false,
12244
+ applied,
12245
+ blocked: result.needsApproval === true ? "PRD lokal berubah. Boleh saya kirim versi lokal ke web? (ya/tidak)" : result.error ?? "Sinkronisasi web gagal.",
12246
+ check,
12247
+ ledger
12248
+ };
12249
+ }
12250
+ applied.push("push");
12251
+ server = await fetchServerState(deps);
12252
+ ledger = { ...ledger, local, server, at: (/* @__PURE__ */ new Date()).toISOString() };
12253
+ }
12254
+ }
12255
+ return {
12256
+ ok: false,
12257
+ applied,
12258
+ blocked: "Penyelarasan tidak selesai dalam batas langkah.",
12259
+ check,
12260
+ ledger
12261
+ };
12262
+ }
12263
+ function formatAlign(result) {
12264
+ const lines = [];
12265
+ if (result.ok) {
12266
+ lines.push("\u2714 Kontrak selaras.");
12267
+ } else {
12268
+ lines.push(`\u2716 Kontrak belum selaras: ${result.blocked ?? "tidak diketahui"}`);
12269
+ }
12270
+ if (result.applied.length > 0) lines.push(` Tindakan: ${result.applied.join(", ")}`);
12271
+ if (result.check.issueCount > 0) {
12272
+ lines.push(` Gate: ${result.check.issueCount} isu.`);
12273
+ for (const issue2 of result.check.issues.slice(0, 8)) {
12274
+ lines.push(` - ${issue2.code} ${issue2.where}: ${issue2.message}`);
12275
+ }
12276
+ }
12277
+ return lines.join("\n");
12278
+ }
12279
+
12280
+ // src/config.ts
12281
+ import { chmod, mkdir as mkdir6, readFile as readFile8, rm as rm5, writeFile as writeFile6 } from "node:fs/promises";
12282
+ import { homedir } from "node:os";
12283
+ import { dirname as dirname5, join as join8, resolve as resolve2 } from "node:path";
12284
+
12285
+ // src/types.ts
12286
+ var UI_QUALITY_MODES = ["auto", "on", "off"];
12287
+
12288
+ // src/config.ts
12289
+ var DEFAULT_UI_QUALITY = "auto";
12290
+ var CONFIG_DIR_ENV = "JIOOGEN_CONFIG_DIR";
12291
+ var LEGACY_CONFIG_DIR_ENV = "JIOOCODE_CONFIG_DIR";
12292
+ var CREDENTIALS_FILE = "credentials.json";
12293
+ var PROJECT_DIR = ".jioogen";
12294
+ var LEGACY_PROJECT_DIR = ".jioocode";
12295
+ var PROJECT_FILE = "project.json";
12296
+ function envValue(name) {
12297
+ const value = process.env[name]?.trim();
12298
+ return value !== void 0 && value.length > 0 ? value : void 0;
12299
+ }
12300
+ function configDirOverride() {
12301
+ return envValue(CONFIG_DIR_ENV) ?? envValue(LEGACY_CONFIG_DIR_ENV);
12302
+ }
12303
+ function configDir() {
12304
+ const override = configDirOverride();
12305
+ return override !== void 0 ? resolve2(override) : join8(homedir(), ".config", "jioogen");
12306
+ }
12307
+ function legacyConfigDir() {
12308
+ return join8(homedir(), ".config", "jioocode");
12309
+ }
12310
+ function credentialsPath() {
12311
+ return join8(configDir(), CREDENTIALS_FILE);
12312
+ }
12313
+ function isRecord(value) {
12314
+ return typeof value === "object" && value !== null;
12315
+ }
12316
+ function parseCredentials(value) {
12317
+ if (!isRecord(value)) return null;
12318
+ const { apiUrl, cookie, savedAt } = value;
12319
+ if (typeof apiUrl !== "string" || apiUrl.length === 0) return null;
12320
+ if (typeof cookie !== "string" || cookie.length === 0) return null;
12321
+ return {
12322
+ apiUrl,
12323
+ cookie,
12324
+ savedAt: typeof savedAt === "string" ? savedAt : (/* @__PURE__ */ new Date(0)).toISOString()
12325
+ };
12326
+ }
12327
+ async function readCredentialsFile(path) {
12328
+ let raw;
12329
+ try {
12330
+ raw = await readFile8(path, "utf8");
12331
+ } catch (error) {
12332
+ if (isMissingFile3(error)) return null;
12333
+ throw error;
12334
+ }
12335
+ try {
12336
+ return parseCredentials(JSON.parse(raw));
12337
+ } catch {
12338
+ return null;
12339
+ }
12340
+ }
12341
+ async function readCredentials() {
12342
+ const primary = await readCredentialsFile(credentialsPath());
12343
+ if (primary !== null) return primary;
12344
+ if (configDirOverride() !== void 0) return null;
12345
+ const legacyPath = join8(legacyConfigDir(), CREDENTIALS_FILE);
12346
+ if (legacyPath === credentialsPath()) return null;
12347
+ return readCredentialsFile(legacyPath);
12348
+ }
12349
+ async function writeCredentials(credentials) {
12350
+ const directory = configDir();
12351
+ await mkdir6(directory, { recursive: true, mode: 448 });
12352
+ const target = credentialsPath();
12353
+ await writeFile6(target, `${JSON.stringify(credentials, null, 2)}
12354
+ `, {
12355
+ encoding: "utf8",
12356
+ mode: 384
12357
+ });
12358
+ await chmod(target, 384);
12359
+ }
12360
+ async function clearCredentials() {
12361
+ const removed = await removeCredentialsFile(credentialsPath());
12362
+ const legacyPath = join8(legacyConfigDir(), CREDENTIALS_FILE);
12363
+ if (legacyPath === credentialsPath()) return removed;
12364
+ const removedLegacy = await removeCredentialsFile(legacyPath);
12365
+ return removed || removedLegacy;
11772
12366
  }
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}`;
12367
+ async function removeCredentialsFile(path) {
11777
12368
  try {
11778
- const bytes = await readFile6(join6(bundleDir, relative2));
11779
- return createHash("sha256").update(bytes).digest("hex");
11780
- } catch {
11781
- return null;
12369
+ await rm5(path);
12370
+ return true;
12371
+ } catch (error) {
12372
+ if (isMissingFile3(error)) return false;
12373
+ throw error;
11782
12374
  }
11783
12375
  }
11784
- async function statMaybe(path) {
11785
- try {
11786
- return await stat3(path);
11787
- } catch {
11788
- return null;
12376
+ function parseProjectLink(value, bundleDir) {
12377
+ if (!isRecord(value)) return null;
12378
+ const { projectId, apiUrl } = value;
12379
+ if (typeof projectId !== "string" || projectId.length === 0) return null;
12380
+ if (typeof apiUrl !== "string" || apiUrl.length === 0) return null;
12381
+ const execution = isRecord(value.execution) ? value.execution : {};
12382
+ return {
12383
+ projectId,
12384
+ apiUrl,
12385
+ bundleDir,
12386
+ taskMode: parseTaskMode(value.taskMode),
12387
+ execution: {
12388
+ // Legacy links may store the flag at the top level; prefer the nested form.
12389
+ uiQuality: parseUiQuality(execution.uiQuality ?? value.uiQuality),
12390
+ autoMode: parseAutoMode(execution.autoMode ?? value.autoMode)
12391
+ }
12392
+ };
12393
+ }
12394
+ function parseUiQuality(value) {
12395
+ if (value === void 0) return DEFAULT_UI_QUALITY;
12396
+ if (typeof value === "string" && UI_QUALITY_MODES.includes(value)) {
12397
+ return value;
11789
12398
  }
12399
+ throw new Error(`Project link execution.uiQuality tidak valid: ${String(value)}`);
11790
12400
  }
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);
12401
+ function parseAutoMode(value) {
12402
+ if (value === void 0 || value === null) return false;
12403
+ if (typeof value === "boolean") return value;
12404
+ if (value === "true" || value === "1" || value === "yes") return true;
12405
+ if (value === "false" || value === "0" || value === "no") return false;
12406
+ throw new Error(`Project link execution.autoMode tidak valid: ${String(value)}`);
12407
+ }
12408
+ async function readAutoMode(bundleDir) {
12409
+ const link = await readProjectLink(resolve2(bundleDir));
12410
+ return link?.execution.autoMode ?? false;
12411
+ }
12412
+ async function writeAutoMode(bundleDir, enabled) {
12413
+ const link = await readProjectLink(resolve2(bundleDir));
12414
+ if (link === null) throw new Error("Belum ada project link. Jalankan `jioogen link` dulu.");
12415
+ await writeProjectLink(resolve2(bundleDir), {
12416
+ projectId: link.projectId,
12417
+ apiUrl: link.apiUrl,
12418
+ taskMode: link.taskMode,
12419
+ execution: { uiQuality: link.execution.uiQuality, autoMode: enabled }
12420
+ });
12421
+ }
12422
+ function parseTaskMode(value) {
12423
+ if (value === void 0) return DEFAULT_TASK_MODE;
12424
+ const parsed = TaskModeSchema.safeParse(value);
12425
+ if (!parsed.success) {
12426
+ throw new Error(`Project link taskMode tidak valid: ${String(value)}`);
11795
12427
  }
11796
- for (const path of Object.keys(after)) {
11797
- if (!(path in before)) changed.add(path);
12428
+ return parsed.data;
12429
+ }
12430
+ async function readProjectLink(bundleDir) {
12431
+ for (const directoryName of [PROJECT_DIR, LEGACY_PROJECT_DIR]) {
12432
+ const candidate = join8(bundleDir, directoryName, PROJECT_FILE);
12433
+ let raw = null;
12434
+ try {
12435
+ raw = await readFile8(candidate, "utf8");
12436
+ } catch (error) {
12437
+ if (!isMissingFile3(error)) throw error;
12438
+ }
12439
+ if (raw === null) continue;
12440
+ let parsed;
12441
+ try {
12442
+ parsed = JSON.parse(raw);
12443
+ } catch {
12444
+ throw new Error(`Project link is not valid JSON: ${candidate}`);
12445
+ }
12446
+ const link = parseProjectLink(parsed, bundleDir);
12447
+ if (link === null) throw new Error(`Project link is invalid: ${candidate}`);
12448
+ return link;
11798
12449
  }
11799
- return [...changed].sort();
12450
+ return null;
11800
12451
  }
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);
12452
+ async function findProjectLink(startDir) {
12453
+ let directory = resolve2(startDir);
12454
+ for (; ; ) {
12455
+ const link = await readProjectLink(directory);
12456
+ if (link !== null) return link;
12457
+ const parent = dirname5(directory);
12458
+ if (parent === directory) return null;
12459
+ directory = parent;
11806
12460
  }
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);
12461
+ }
12462
+ async function writeProjectLink(bundleDir, link) {
12463
+ const directory = join8(resolve2(bundleDir), PROJECT_DIR);
12464
+ await mkdir6(directory, { recursive: true });
12465
+ await writeFile6(
12466
+ join8(directory, PROJECT_FILE),
12467
+ `${JSON.stringify(
12468
+ {
12469
+ projectId: link.projectId,
12470
+ apiUrl: link.apiUrl,
12471
+ taskMode: link.taskMode ?? DEFAULT_TASK_MODE,
12472
+ execution: {
12473
+ uiQuality: link.execution?.uiQuality ?? DEFAULT_UI_QUALITY,
12474
+ autoMode: link.execution?.autoMode ?? false
12475
+ }
12476
+ },
12477
+ null,
12478
+ 2
12479
+ )}
12480
+ `,
12481
+ "utf8"
12482
+ );
12483
+ }
12484
+ async function removeProjectLink(bundleDir) {
12485
+ let removedKey = false;
12486
+ for (const directoryName of [PROJECT_DIR, LEGACY_PROJECT_DIR]) {
12487
+ const candidate = join8(resolve2(bundleDir), directoryName, PROJECT_FILE);
12488
+ try {
12489
+ await rm5(candidate);
12490
+ removedKey = true;
12491
+ } catch (error) {
12492
+ if (!isMissingFile3(error)) throw error;
11814
12493
  }
11815
12494
  }
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");
12495
+ return removedKey;
12496
+ }
12497
+ async function readUiQuality(bundleDir) {
12498
+ const link = await readProjectLink(resolve2(bundleDir));
12499
+ return link?.execution.uiQuality ?? DEFAULT_UI_QUALITY;
12500
+ }
12501
+ async function readTaskMode(bundleDir) {
12502
+ const link = await readProjectLink(resolve2(bundleDir));
12503
+ return link?.taskMode ?? DEFAULT_TASK_MODE;
12504
+ }
12505
+ function isMissingFile3(error) {
12506
+ return isRecord(error) && error.code === "ENOENT";
11822
12507
  }
11823
12508
 
12509
+ // src/doctor.ts
12510
+ import { readdir as readdir7, readFile as readFile10, rm as rm7, stat as stat6 } from "node:fs/promises";
12511
+ import { join as join10 } from "node:path";
12512
+
11824
12513
  // src/skills.ts
11825
- import { createHash as createHash2 } from "node:crypto";
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";
12514
+ import { createHash as createHash3 } from "node:crypto";
12515
+ import { cp as cp2, mkdir as mkdir7, readdir as readdir6, readFile as readFile9, rename as rename2, rm as rm6, stat as stat5, writeFile as writeFile7 } from "node:fs/promises";
11827
12516
  import { homedir as homedir2 } from "node:os";
11828
- import { dirname as dirname5, join as join7, resolve as resolve3 } from "node:path";
12517
+ import { dirname as dirname6, join as join9, resolve as resolve3 } from "node:path";
11829
12518
  import { fileURLToPath as fileURLToPath2 } from "node:url";
11830
12519
  var EXECUTION_SKILL_NAME = "jioogen-execution";
11831
12520
  var AGENT_SKILL_DIRS = [
@@ -11899,6 +12588,13 @@ var JIOOGEN_AGENTS_MD = `${MARKER}
11899
12588
  mengizinkanmu menambah task, \`executor\` hanya menjalankan task yang sudah ada \u2014
11900
12589
  CLI menolak task baru di disk. Jangan menaikkan mode sendiri.
11901
12590
 
12591
+ ## 0c. Cara bertanya ke user (selalu)
12592
+ - Setiap pertanyaan ke user pakai **bahasa manusia sehari-hari**: pendek, jelas,
12593
+ dan mudah dijawab. Utamakan "ya/tidak" atau pilihan "A / B".
12594
+ - Jangan pakai istilah teknis, path file, kode, nama gate, atau jargon CLI saat
12595
+ bertanya. Cukup satu kalimat tentang dampaknya bagi produk.
12596
+ - Contoh: "Saya mau mengubah PRD, lalu specs, lalu tasks. Boleh? (ya/tidak)".
12597
+
11902
12598
  ## 1. Prioritas mutlak (keras)
11903
12599
  - **Task aktif menang** atas ide, refactor, perbaikan, atau fitur lain.
11904
12600
  - **Satu task per giliran.** Dilarang mengerjakan lebih dari satu task sekaligus.
@@ -11938,9 +12634,20 @@ tangan) sebelum task dijalankan, jangan pura-pura mengerjakannya:
11938
12634
  - Verifikasi hasilnya lalu \`npx jioogen task adopt <ref> --note "<alat>"\` (task UI:
11939
12635
  tambahkan \`--visual "<catatan>"\`). Command itu menjalankan \`verificationCommand\`
11940
12636
  dan mencatat \`source: user\` + bukti adopsi di sidecar.
11941
- - Kalau hasil alat itu menyimpang dari \`specs/\`/\`CONTRACT-XXX\`, STOP: revisi
11942
- kontrak lewat workspace web, jangan mengadopsi diam-diam.
11943
- - Jangan edit \`PRD.md\`/\`specs/\` lokal; \`BUNDLE_DRIFT\` akan muncul.
12637
+ - Mode authoring lokal: bila user menyetujui patch kontrak di chat lokal, catat
12638
+ persetujuan dengan \`npx jioogen approve --note "<alasan>"\` (menulis
12639
+ \`.jioogen/approvals.json\` + \`.jioogen/custom/knowledge/approved-patches.md\`),
12640
+ lalu ubah \`PRD.md\`. Setelah itu jalankan \`npx jioogen align\`: JiooGen otomatis
12641
+ menurunkan \`specs/\` \u2192 \`tasks/\`, memvalidasi gate, dan menyelaraskan ke web.
12642
+ \`npx jioogen task next\` juga menyelaraskan otomatis sebelum memilih task.
12643
+ Jangan menyuruh user balik ke web dan jangan edit \`specs/\`/\`tasks/\` manual.
12644
+ - Sebelum mode authoring lokal, agent WAJIB bertanya dengan bahasa manusia:
12645
+ "Saya mau mengubah PRD, lalu specs, lalu tasks di lokal. Boleh? (ya/tidak)".
12646
+ Lanjut HANYA bila user menjawab "ya". Tanpa "ya", jangan ubah apa pun.
12647
+ Jangan pakai istilah teknis saat bertanya, dan ingatkan bahwa setelah patch
12648
+ ada, jangan menjalankan \`jioogen pull --force\`.
12649
+ - Di luar mode authoring lokal itu, jangan edit \`PRD.md\`/\`specs/\` lokal;
12650
+ \`BUNDLE_DRIFT\` akan muncul. Jangan mengadopsi penyimpangan diam-diam.
11944
12651
  - Port dev server jangan ditebak: JiooGen/app lain bisa sudah memakainya. Pakai port
11945
12652
  bebas (mis. \`PORT=3001\`), catat di note; jangan ubah kontrak/spec demi port.
11946
12653
 
@@ -12086,9 +12793,20 @@ atau ditulis tangan \u2014 sebelum task dijalankan, jangan pura-pura mengerjakan
12086
12793
  - Verifikasi hasilnya lalu \`npx jioogen task adopt <ref> --note "<alat>"\` (task UI:
12087
12794
  tambahkan \`--visual "<catatan>"\`). Command itu menjalankan \`verificationCommand\`
12088
12795
  dan mencatat \`source: user\` + bukti adopsi di sidecar.
12089
- - Kalau hasil alat itu menyimpang dari \`specs/\`/\`CONTRACT-XXX\`, STOP: revisi
12090
- kontrak lewat workspace web, jangan mengadopsi diam-diam.
12091
- - Jangan edit \`PRD.md\`/\`specs/\` lokal; \`BUNDLE_DRIFT\` akan muncul.
12796
+ - Mode authoring lokal: bila user menyetujui patch kontrak di chat lokal, catat
12797
+ persetujuan dengan \`npx jioogen approve --note "<alasan>"\` (menulis
12798
+ \`.jioogen/approvals.json\` + \`.jioogen/custom/knowledge/approved-patches.md\`),
12799
+ lalu ubah \`PRD.md\`. Setelah itu jalankan \`npx jioogen align\`: JiooGen otomatis
12800
+ menurunkan \`specs/\` \u2192 \`tasks/\`, memvalidasi gate, dan menyelaraskan ke web.
12801
+ \`npx jioogen task next\` juga menyelaraskan otomatis sebelum memilih task.
12802
+ Jangan menyuruh user balik ke web dan jangan edit \`specs/\`/\`tasks/\` manual.
12803
+ - Sebelum mode authoring lokal, agent WAJIB bertanya dengan bahasa manusia:
12804
+ "Saya mau mengubah PRD, lalu specs, lalu tasks di lokal. Boleh? (ya/tidak)".
12805
+ Lanjut HANYA bila user menjawab "ya". Tanpa "ya", jangan ubah apa pun.
12806
+ Jangan pakai istilah teknis saat bertanya, dan ingatkan bahwa setelah patch
12807
+ ada, jangan menjalankan \`jioogen pull --force\`.
12808
+ - Di luar mode authoring lokal itu, jangan edit \`PRD.md\`/\`specs/\` lokal;
12809
+ \`BUNDLE_DRIFT\` akan muncul. Jangan mengadopsi penyimpangan diam-diam.
12092
12810
  - **Port dev server jangan ditebak.** JiooGen/monitor atau app lain bisa sudah
12093
12811
  memakai port default; pakai port bebas (mis. \`PORT=3001\`), catat di note, dan
12094
12812
  jangan mengubah kontrak/spec demi port.
@@ -12231,18 +12949,18 @@ Gap non-material \u2192 tafsir paling sempit + catat asumsi di note, lanjut. Gap
12231
12949
  Jangan menebak scope baru.
12232
12950
  `;
12233
12951
  async function ensureCustomScaffold(root) {
12234
- const base = join7(root, ".jioogen", "custom");
12952
+ const base = join9(root, ".jioogen", "custom");
12235
12953
  for (const dir of CUSTOM_SCAFFOLD_DIRS) {
12236
- await mkdir5(join7(base, dir), { recursive: true });
12954
+ await mkdir7(join9(base, dir), { recursive: true });
12237
12955
  }
12238
- const readme = join7(root, CUSTOM_SCAFFOLD_README_PATH);
12956
+ const readme = join9(root, CUSTOM_SCAFFOLD_README_PATH);
12239
12957
  if (await readFileSafe(readme) !== void 0) return [];
12240
- await writeFile5(readme, CUSTOM_SCAFFOLD_README, "utf8");
12958
+ await writeFile7(readme, CUSTOM_SCAFFOLD_README, "utf8");
12241
12959
  return [CUSTOM_SCAFFOLD_README_PATH];
12242
12960
  }
12243
12961
  async function readFileSafe(path) {
12244
12962
  try {
12245
- return await readFile7(path, "utf8");
12963
+ return await readFile9(path, "utf8");
12246
12964
  } catch {
12247
12965
  return void 0;
12248
12966
  }
@@ -12255,7 +12973,7 @@ function isMissingFile4(error) {
12255
12973
  }
12256
12974
  async function isFile(path) {
12257
12975
  try {
12258
- return (await stat4(path)).isFile();
12976
+ return (await stat5(path)).isFile();
12259
12977
  } catch (error) {
12260
12978
  if (isMissingFile4(error)) return false;
12261
12979
  throw error;
@@ -12263,7 +12981,7 @@ async function isFile(path) {
12263
12981
  }
12264
12982
  async function isDirectory(path) {
12265
12983
  try {
12266
- return (await stat4(path)).isDirectory();
12984
+ return (await stat5(path)).isDirectory();
12267
12985
  } catch (error) {
12268
12986
  if (isMissingFile4(error)) return false;
12269
12987
  throw error;
@@ -12277,11 +12995,11 @@ function isProductKind(value) {
12277
12995
  }
12278
12996
  function parseSkillEntry(value) {
12279
12997
  if (!isRecord2(value)) return null;
12280
- const { name, source, sha256 } = value;
12998
+ const { name, source, sha256: sha2562 } = value;
12281
12999
  if (typeof name !== "string" || name.length === 0) return null;
12282
13000
  if (typeof source !== "string" || source.length === 0) return null;
12283
- if (typeof sha256 !== "string" || sha256.length === 0) return null;
12284
- return { name, source, sha256 };
13001
+ if (typeof sha2562 !== "string" || sha2562.length === 0) return null;
13002
+ return { name, source, sha256: sha2562 };
12285
13003
  }
12286
13004
  function parsePack(value) {
12287
13005
  if (!isRecord2(value)) return null;
@@ -12331,10 +13049,10 @@ function parseHarnessManifest(value) {
12331
13049
  };
12332
13050
  }
12333
13051
  async function readHarnessManifest(bundleDir) {
12334
- const path = join7(resolve3(bundleDir), HARNESS_MANIFEST_PATH);
13052
+ const path = join9(resolve3(bundleDir), HARNESS_MANIFEST_PATH);
12335
13053
  let raw;
12336
13054
  try {
12337
- raw = await readFile7(path, "utf8");
13055
+ raw = await readFile9(path, "utf8");
12338
13056
  } catch (error) {
12339
13057
  if (isMissingFile4(error)) return null;
12340
13058
  throw error;
@@ -12346,24 +13064,24 @@ async function readHarnessManifest(bundleDir) {
12346
13064
  }
12347
13065
  }
12348
13066
  async function writeHarnessManifest(bundleDir, manifest) {
12349
- const path = join7(resolve3(bundleDir), HARNESS_MANIFEST_PATH);
12350
- await mkdir5(dirname5(path), { recursive: true });
12351
- await writeFile5(path, `${JSON.stringify(manifest, null, 2)}
13067
+ const path = join9(resolve3(bundleDir), HARNESS_MANIFEST_PATH);
13068
+ await mkdir7(dirname6(path), { recursive: true });
13069
+ await writeFile7(path, `${JSON.stringify(manifest, null, 2)}
12352
13070
  `, "utf8");
12353
13071
  return path;
12354
13072
  }
12355
13073
  async function detectProductKind(bundleDir) {
12356
- const tasksDir = join7(resolve3(bundleDir), "tasks");
13074
+ const tasksDir = join9(resolve3(bundleDir), "tasks");
12357
13075
  let entries;
12358
13076
  try {
12359
- entries = await readdir5(tasksDir, { withFileTypes: true });
13077
+ entries = await readdir6(tasksDir, { withFileTypes: true });
12360
13078
  } catch (error) {
12361
13079
  if (isMissingFile4(error)) return "non-ui";
12362
13080
  throw error;
12363
13081
  }
12364
13082
  for (const entry of entries) {
12365
13083
  if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
12366
- const content = await readFileSafe(join7(tasksDir, entry.name));
13084
+ const content = await readFileSafe(join9(tasksDir, entry.name));
12367
13085
  if (content !== void 0 && FRONTEND_MOCK_LAYER_RE.test(content)) return "ui";
12368
13086
  }
12369
13087
  return "non-ui";
@@ -12379,37 +13097,37 @@ function packsForProduct(productKind, uiQuality = "auto") {
12379
13097
  return packs;
12380
13098
  }
12381
13099
  function cliPackageRoot2() {
12382
- return resolve3(dirname5(fileURLToPath2(import.meta.url)), "..");
13100
+ return resolve3(dirname6(fileURLToPath2(import.meta.url)), "..");
12383
13101
  }
12384
13102
  function skillSourceCandidates(pack, name) {
12385
13103
  const candidates = [];
12386
13104
  const override = process.env.JIOOGEN_SKILLS_DIR?.trim();
12387
- if (override !== void 0 && override.length > 0) candidates.push(join7(override, name));
12388
- candidates.push(join7(configDir(), "skill-cache", name));
12389
- candidates.push(join7(cliPackageRoot2(), "skills-pack", pack, name));
13105
+ if (override !== void 0 && override.length > 0) candidates.push(join9(override, name));
13106
+ candidates.push(join9(configDir(), "skill-cache", name));
13107
+ candidates.push(join9(cliPackageRoot2(), "skills-pack", pack, name));
12390
13108
  const home = homedir2();
12391
- candidates.push(join7(home, ".agents", "skills", name));
12392
- candidates.push(join7(home, ".config", "opencode", "skills", name));
12393
- candidates.push(join7(home, ".claude", "skills", name));
13109
+ candidates.push(join9(home, ".agents", "skills", name));
13110
+ candidates.push(join9(home, ".config", "opencode", "skills", name));
13111
+ candidates.push(join9(home, ".claude", "skills", name));
12394
13112
  return candidates;
12395
13113
  }
12396
13114
  async function resolveSkillSource(pack, name) {
12397
13115
  for (const candidate of skillSourceCandidates(pack, name)) {
12398
- if (await isDirectory(candidate) && await isFile(join7(candidate, "SKILL.md"))) {
13116
+ if (await isDirectory(candidate) && await isFile(join9(candidate, "SKILL.md"))) {
12399
13117
  return candidate;
12400
13118
  }
12401
13119
  }
12402
13120
  return null;
12403
13121
  }
12404
13122
  async function collectRelativeFiles(root, prefix) {
12405
- const entries = await readdir5(join7(root, prefix), { withFileTypes: true });
13123
+ const entries = await readdir6(join9(root, prefix), { withFileTypes: true });
12406
13124
  const files = [];
12407
13125
  for (const entry of entries) {
12408
- const relative2 = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`;
13126
+ const relative3 = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`;
12409
13127
  if (entry.isDirectory()) {
12410
- files.push(...await collectRelativeFiles(root, relative2));
13128
+ files.push(...await collectRelativeFiles(root, relative3));
12411
13129
  } else if (entry.isFile()) {
12412
- files.push(relative2);
13130
+ files.push(relative3);
12413
13131
  }
12414
13132
  }
12415
13133
  return files;
@@ -12417,18 +13135,18 @@ async function collectRelativeFiles(root, prefix) {
12417
13135
  async function hashSkillDirectory(directory) {
12418
13136
  const root = resolve3(directory);
12419
13137
  const files = (await collectRelativeFiles(root, "")).sort();
12420
- const hash = createHash2("sha256");
12421
- for (const relative2 of files) {
12422
- hash.update(relative2);
13138
+ const hash = createHash3("sha256");
13139
+ for (const relative3 of files) {
13140
+ hash.update(relative3);
12423
13141
  hash.update("\0");
12424
- hash.update(await readFile7(join7(root, ...relative2.split("/"))));
13142
+ hash.update(await readFile9(join9(root, ...relative3.split("/"))));
12425
13143
  hash.update("\0");
12426
13144
  }
12427
13145
  return hash.digest("hex");
12428
13146
  }
12429
13147
  async function replaceDirectory(source, target) {
12430
- await rm5(target, { recursive: true, force: true });
12431
- await mkdir5(dirname5(target), { recursive: true });
13148
+ await rm6(target, { recursive: true, force: true });
13149
+ await mkdir7(dirname6(target), { recursive: true });
12432
13150
  await cp2(source, target, { recursive: true });
12433
13151
  }
12434
13152
  function packNamesInCanonicalOrder(names) {
@@ -12444,19 +13162,19 @@ async function provisionPack(root, pack, prior, written, preserved) {
12444
13162
  missing.push(name);
12445
13163
  continue;
12446
13164
  }
12447
- const sha256 = await hashSkillDirectory(source);
13165
+ const sha2562 = await hashSkillDirectory(source);
12448
13166
  const previous = prior?.skills.find((entry) => entry.name === name);
12449
13167
  let owned = previous !== void 0;
12450
13168
  for (const dir of AGENT_SKILL_DIRS) {
12451
- const targetDir = join7(root, dir, name);
12452
- const skillMd = join7(targetDir, "SKILL.md");
13169
+ const targetDir = join9(root, dir, name);
13170
+ const skillMd = join9(targetDir, "SKILL.md");
12453
13171
  if (await isFile(skillMd)) {
12454
13172
  const targetHash = await hashSkillDirectory(targetDir);
12455
13173
  if (previous === void 0) {
12456
13174
  preserved.push(`${dir}/${name}/SKILL.md`);
12457
13175
  continue;
12458
13176
  }
12459
- if (targetHash === sha256) {
13177
+ if (targetHash === sha2562) {
12460
13178
  owned = true;
12461
13179
  continue;
12462
13180
  }
@@ -12469,7 +13187,7 @@ async function provisionPack(root, pack, prior, written, preserved) {
12469
13187
  written.push(`${dir}/${name}/SKILL.md`);
12470
13188
  owned = true;
12471
13189
  }
12472
- if (owned) skills.push({ name, source: `${pack}/${name}`, sha256 });
13190
+ if (owned) skills.push({ name, source: `${pack}/${name}`, sha256: sha2562 });
12473
13191
  }
12474
13192
  return { name: pack, skills, missing };
12475
13193
  }
@@ -12480,36 +13198,36 @@ async function provisionCustomSkills(root, prior) {
12480
13198
  const conflicts = [];
12481
13199
  const removed = [];
12482
13200
  const sources = /* @__PURE__ */ new Set();
12483
- const base = join7(root, CUSTOM_SKILLS_DIR);
13201
+ const base = join9(root, CUSTOM_SKILLS_DIR);
12484
13202
  const reserved = /* @__PURE__ */ new Set([EXECUTION_SKILL_NAME, ...Object.values(SKILL_PACKS).flat()]);
12485
13203
  let entries = [];
12486
13204
  try {
12487
- entries = await readdir5(base, { withFileTypes: true });
13205
+ entries = await readdir6(base, { withFileTypes: true });
12488
13206
  } catch (error) {
12489
13207
  if (!isMissingFile4(error)) throw error;
12490
13208
  }
12491
13209
  const names = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
12492
13210
  for (const name of names) {
12493
- const source = join7(base, name);
12494
- if (!await isFile(join7(source, "SKILL.md"))) continue;
13211
+ const source = join9(base, name);
13212
+ if (!await isFile(join9(source, "SKILL.md"))) continue;
12495
13213
  sources.add(name);
12496
13214
  if (reserved.has(name)) {
12497
13215
  conflicts.push(name);
12498
13216
  continue;
12499
13217
  }
12500
- const sha256 = await hashSkillDirectory(source);
13218
+ const sha2562 = await hashSkillDirectory(source);
12501
13219
  const previous = prior.find((entry) => entry.name === name);
12502
13220
  let owned = previous !== void 0;
12503
13221
  for (const dir of AGENT_SKILL_DIRS) {
12504
- const targetDir = join7(root, dir, name);
12505
- const skillMd = join7(targetDir, "SKILL.md");
13222
+ const targetDir = join9(root, dir, name);
13223
+ const skillMd = join9(targetDir, "SKILL.md");
12506
13224
  if (await isFile(skillMd)) {
12507
13225
  const targetHash = await hashSkillDirectory(targetDir);
12508
13226
  if (previous === void 0) {
12509
13227
  preserved.push(`${dir}/${name}/SKILL.md`);
12510
13228
  continue;
12511
13229
  }
12512
- if (targetHash === sha256) {
13230
+ if (targetHash === sha2562) {
12513
13231
  owned = true;
12514
13232
  continue;
12515
13233
  }
@@ -12527,7 +13245,7 @@ async function provisionCustomSkills(root, prior) {
12527
13245
  owned = true;
12528
13246
  }
12529
13247
  if (owned) {
12530
- custom2.push({ name, source: `custom/${name}`, sha256 });
13248
+ custom2.push({ name, source: `custom/${name}`, sha256: sha2562 });
12531
13249
  } else if (previous !== void 0) {
12532
13250
  custom2.push(previous);
12533
13251
  }
@@ -12536,15 +13254,15 @@ async function provisionCustomSkills(root, prior) {
12536
13254
  if (sources.has(entry.name) && !reserved.has(entry.name)) continue;
12537
13255
  if (reserved.has(entry.name)) continue;
12538
13256
  for (const dir of AGENT_SKILL_DIRS) {
12539
- const targetDir = join7(root, dir, entry.name);
12540
- const skillMd = join7(targetDir, "SKILL.md");
13257
+ const targetDir = join9(root, dir, entry.name);
13258
+ const skillMd = join9(targetDir, "SKILL.md");
12541
13259
  if (!await isFile(skillMd)) continue;
12542
13260
  const targetHash = await hashSkillDirectory(targetDir);
12543
13261
  if (targetHash !== entry.sha256) {
12544
13262
  preserved.push(`${dir}/${entry.name}/SKILL.md`);
12545
13263
  continue;
12546
13264
  }
12547
- await rm5(targetDir, { recursive: true, force: true });
13265
+ await rm6(targetDir, { recursive: true, force: true });
12548
13266
  removed.push(`${dir}/${entry.name}/SKILL.md`);
12549
13267
  }
12550
13268
  }
@@ -12588,10 +13306,10 @@ async function provisionSkillPacks(bundleDir, packNames, productKind) {
12588
13306
  };
12589
13307
  }
12590
13308
  async function ensureBundleGitignore(root) {
12591
- const path = join7(resolve3(root), ".gitignore");
13309
+ const path = join9(resolve3(root), ".gitignore");
12592
13310
  const existing = await readFileSafe(path);
12593
13311
  if (existing === void 0) {
12594
- await writeFile5(path, GITIGNORE_BLOCK, "utf8");
13312
+ await writeFile7(path, GITIGNORE_BLOCK, "utf8");
12595
13313
  return ".gitignore";
12596
13314
  }
12597
13315
  const start = existing.indexOf(GITIGNORE_START);
@@ -12599,7 +13317,7 @@ async function ensureBundleGitignore(root) {
12599
13317
  const next = start >= 0 && end > start ? `${existing.slice(0, start)}${GITIGNORE_BLOCK}${existing.slice(end + GITIGNORE_END.length).replace(/^\n/, "")}` : `${existing.replace(/\n*$/, "\n")}
12600
13318
  ${GITIGNORE_BLOCK}`;
12601
13319
  if (next === existing) return null;
12602
- await writeFile5(path, next, "utf8");
13320
+ await writeFile7(path, next, "utf8");
12603
13321
  return ".gitignore";
12604
13322
  }
12605
13323
  async function installAgentSkills(bundleDir, options = {}) {
@@ -12607,21 +13325,21 @@ async function installAgentSkills(bundleDir, options = {}) {
12607
13325
  const written = [];
12608
13326
  const preserved = [];
12609
13327
  const productKind = options.productKind ?? await detectProductKind(root);
12610
- const harnessPath = join7(root, HARNESS_MANIFEST_PATH);
12611
- const agentsPath = join7(root, "AGENTS.md");
13328
+ const harnessPath = join9(root, HARNESS_MANIFEST_PATH);
13329
+ const agentsPath = join9(root, "AGENTS.md");
12612
13330
  const existing = await readFileSafe(agentsPath);
12613
13331
  if (existing === void 0 || existing.includes(MARKER_PREFIX)) {
12614
- await writeFile5(agentsPath, JIOOGEN_AGENTS_MD, "utf8");
13332
+ await writeFile7(agentsPath, JIOOGEN_AGENTS_MD, "utf8");
12615
13333
  written.push("AGENTS.md");
12616
13334
  } else {
12617
13335
  preserved.push("AGENTS.md");
12618
13336
  }
12619
13337
  for (const dir of AGENT_SKILL_DIRS) {
12620
- const relative2 = `${dir}/${EXECUTION_SKILL_NAME}/SKILL.md`;
12621
- const target = join7(root, relative2);
12622
- await mkdir5(dirname5(target), { recursive: true });
12623
- await writeFile5(target, JIOOGEN_EXECUTION_SKILL, "utf8");
12624
- written.push(relative2);
13338
+ const relative3 = `${dir}/${EXECUTION_SKILL_NAME}/SKILL.md`;
13339
+ const target = join9(root, relative3);
13340
+ await mkdir7(dirname6(target), { recursive: true });
13341
+ await writeFile7(target, JIOOGEN_EXECUTION_SKILL, "utf8");
13342
+ written.push(relative3);
12625
13343
  }
12626
13344
  const gitignore = await ensureBundleGitignore(root);
12627
13345
  if (gitignore !== null) written.push(gitignore);
@@ -12688,22 +13406,22 @@ async function removeExecutionContract(bundleDir) {
12688
13406
  const root = resolve3(bundleDir);
12689
13407
  const removed = [];
12690
13408
  const preserved = [];
12691
- const agentsPath = join7(root, "AGENTS.md");
13409
+ const agentsPath = join9(root, "AGENTS.md");
12692
13410
  const existingAgents = await readFileSafe(agentsPath);
12693
13411
  if (existingAgents !== void 0) {
12694
13412
  if (existingAgents.includes(MARKER_PREFIX)) {
12695
- await rm5(agentsPath, { force: true });
13413
+ await rm6(agentsPath, { force: true });
12696
13414
  removed.push("AGENTS.md");
12697
13415
  } else {
12698
13416
  preserved.push("AGENTS.md");
12699
13417
  }
12700
13418
  }
12701
13419
  for (const dir of AGENT_SKILL_DIRS) {
12702
- const target = join7(root, dir, EXECUTION_SKILL_NAME);
13420
+ const target = join9(root, dir, EXECUTION_SKILL_NAME);
12703
13421
  try {
12704
- const info = await stat4(target);
13422
+ const info = await stat5(target);
12705
13423
  if (info.isDirectory()) {
12706
- await rm5(target, { recursive: true, force: true });
13424
+ await rm6(target, { recursive: true, force: true });
12707
13425
  removed.push(`${dir}/${EXECUTION_SKILL_NAME}`);
12708
13426
  }
12709
13427
  } catch (error) {
@@ -12722,15 +13440,15 @@ async function removeSkillPack(bundleDir, pack) {
12722
13440
  if (entry !== void 0) {
12723
13441
  for (const skill of entry.skills) {
12724
13442
  for (const dir of AGENT_SKILL_DIRS) {
12725
- const targetDir = join7(root, dir, skill.name);
12726
- const skillMd = join7(targetDir, "SKILL.md");
13443
+ const targetDir = join9(root, dir, skill.name);
13444
+ const skillMd = join9(targetDir, "SKILL.md");
12727
13445
  if (!await isFile(skillMd)) continue;
12728
13446
  const targetHash = await hashSkillDirectory(targetDir);
12729
13447
  if (targetHash !== skill.sha256) {
12730
13448
  preserved.push(`${dir}/${skill.name}/SKILL.md`);
12731
13449
  continue;
12732
13450
  }
12733
- await rm5(targetDir, { recursive: true, force: true });
13451
+ await rm6(targetDir, { recursive: true, force: true });
12734
13452
  removed.push(`${dir}/${skill.name}/SKILL.md`);
12735
13453
  }
12736
13454
  }
@@ -12764,13 +13482,13 @@ async function restoreSkillPack(bundleDir, packArgument) {
12764
13482
  missing.push(name);
12765
13483
  continue;
12766
13484
  }
12767
- const sha256 = await hashSkillDirectory(source);
13485
+ const sha2562 = await hashSkillDirectory(source);
12768
13486
  for (const dir of AGENT_SKILL_DIRS) {
12769
- const targetDir = join7(root, dir, name);
13487
+ const targetDir = join9(root, dir, name);
12770
13488
  await replaceDirectory(source, targetDir);
12771
13489
  restored.push(`${dir}/${name}`);
12772
13490
  }
12773
- skills.push({ name, source: `${pack}/${name}`, sha256 });
13491
+ skills.push({ name, source: `${pack}/${name}`, sha256: sha2562 });
12774
13492
  }
12775
13493
  const manifestEntry = { name: pack, skills, missing: packMissing };
12776
13494
  const index = updatedPacks.findIndex((candidate) => candidate.name === pack);
@@ -12792,10 +13510,10 @@ async function disableSkill(bundleDir, name) {
12792
13510
  const root = resolve3(bundleDir);
12793
13511
  const disabled = [];
12794
13512
  for (const dir of AGENT_SKILL_DIRS) {
12795
- const targetDir = join7(root, dir, name);
13513
+ const targetDir = join9(root, dir, name);
12796
13514
  const disabledDir = `${targetDir}.disabled`;
12797
13515
  if (!await isDirectory(targetDir)) continue;
12798
- if (await isDirectory(disabledDir)) await rm5(disabledDir, { recursive: true, force: true });
13516
+ if (await isDirectory(disabledDir)) await rm6(disabledDir, { recursive: true, force: true });
12799
13517
  await rename2(targetDir, disabledDir);
12800
13518
  disabled.push(`${dir}/${name}`);
12801
13519
  }
@@ -12805,10 +13523,10 @@ async function enableSkill(bundleDir, name) {
12805
13523
  const root = resolve3(bundleDir);
12806
13524
  const enabled = [];
12807
13525
  for (const dir of AGENT_SKILL_DIRS) {
12808
- const targetDir = join7(root, dir, name);
13526
+ const targetDir = join9(root, dir, name);
12809
13527
  const disabledDir = `${targetDir}.disabled`;
12810
13528
  if (!await isDirectory(disabledDir)) continue;
12811
- if (await isDirectory(targetDir)) await rm5(disabledDir, { recursive: true, force: true });
13529
+ if (await isDirectory(targetDir)) await rm6(disabledDir, { recursive: true, force: true });
12812
13530
  else {
12813
13531
  await rename2(disabledDir, targetDir);
12814
13532
  enabled.push(`${dir}/${name}`);
@@ -12972,21 +13690,21 @@ async function checkProject(deps, credentials, projectId) {
12972
13690
  }
12973
13691
  async function isFile2(path) {
12974
13692
  try {
12975
- return (await stat5(path)).isFile();
13693
+ return (await stat6(path)).isFile();
12976
13694
  } catch {
12977
13695
  return false;
12978
13696
  }
12979
13697
  }
12980
13698
  async function isDirectory2(path) {
12981
13699
  try {
12982
- return (await stat5(path)).isDirectory();
13700
+ return (await stat6(path)).isDirectory();
12983
13701
  } catch {
12984
13702
  return false;
12985
13703
  }
12986
13704
  }
12987
13705
  async function listMarkdownFiles(directory) {
12988
13706
  try {
12989
- const entries = await readdir6(directory, { withFileTypes: true });
13707
+ const entries = await readdir7(directory, { withFileTypes: true });
12990
13708
  return entries.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".md")).map((entry) => entry.name);
12991
13709
  } catch {
12992
13710
  return [];
@@ -12994,17 +13712,17 @@ async function listMarkdownFiles(directory) {
12994
13712
  }
12995
13713
  async function checkBundle(bundleDir) {
12996
13714
  const missing = [];
12997
- if (!await isFile2(join8(bundleDir, "PRD.md"))) missing.push("PRD.md");
12998
- const specsDir = join8(bundleDir, "specs");
13715
+ if (!await isFile2(join10(bundleDir, "PRD.md"))) missing.push("PRD.md");
13716
+ const specsDir = join10(bundleDir, "specs");
12999
13717
  if (!await isDirectory2(specsDir)) {
13000
13718
  missing.push("specs/");
13001
13719
  } else {
13002
13720
  const markdown = await listMarkdownFiles(specsDir);
13003
- const readme = await readFile8(join8(specsDir, "SPECS.md"), "utf8").catch(() => "");
13721
+ const readme = await readFile10(join10(specsDir, "SPECS.md"), "utf8").catch(() => "");
13004
13722
  const hasContent = markdown.some((name) => name.toLowerCase() !== "specs.md") || specReadmeIsContent(readme);
13005
13723
  if (!hasContent) missing.push("specs/*.md (konten)");
13006
13724
  }
13007
- const tasksDir = join8(bundleDir, "tasks");
13725
+ const tasksDir = join10(bundleDir, "tasks");
13008
13726
  if (!await isDirectory2(tasksDir)) {
13009
13727
  missing.push("tasks/");
13010
13728
  } else {
@@ -13052,6 +13770,36 @@ async function checkSidecar(bundleDir) {
13052
13770
  }
13053
13771
  async function checkDrift(bundleDir) {
13054
13772
  try {
13773
+ const local = await snapshotContract(bundleDir);
13774
+ const hasContract = hasContractArtifacts(local);
13775
+ const ledger = hasContract ? await readContractLedger(bundleDir) : null;
13776
+ if (hasContract && ledger !== null) {
13777
+ const stale = computeStaleness(ledger.derivation, local);
13778
+ if (stale.specsStale) {
13779
+ return makeCheck(
13780
+ "drift",
13781
+ "warn",
13782
+ "PRD berubah: specs masih dari versi PRD lama. Jalankan `jioogen align`."
13783
+ );
13784
+ }
13785
+ if (stale.tasksStale) {
13786
+ return makeCheck(
13787
+ "drift",
13788
+ "warn",
13789
+ "Specs/PRD berubah: tasks masih dari versi lama. Jalankan `jioogen align`."
13790
+ );
13791
+ }
13792
+ }
13793
+ if (hasContract && ledger === null) {
13794
+ const contractCheck = await inspectBundle(bundleDir);
13795
+ if (!contractCheck.ok) {
13796
+ return makeCheck(
13797
+ "drift",
13798
+ "warn",
13799
+ "Baseline kontrak belum ada dan gate bundle gagal; jalankan `jioogen align` agar PRD, specs, dan tasks diselaraskan."
13800
+ );
13801
+ }
13802
+ }
13055
13803
  const state = await readState(bundleDir);
13056
13804
  if (state === null) {
13057
13805
  return makeCheck("drift", "pass", "Belum ada sidecar; drift belum bisa dibandingkan.");
@@ -13067,10 +13815,10 @@ async function checkDrift(bundleDir) {
13067
13815
  }
13068
13816
  }
13069
13817
  async function checkRecovery(bundleDir) {
13070
- const path = join8(bundleDir, "tasks/.execution/recovery.json");
13818
+ const path = join10(bundleDir, "tasks/.execution/recovery.json");
13071
13819
  let raw;
13072
13820
  try {
13073
- raw = await readFile8(path, "utf8");
13821
+ raw = await readFile10(path, "utf8");
13074
13822
  } catch (error) {
13075
13823
  if (isMissingFile5(error)) {
13076
13824
  return makeCheck("recovery", "pass", "Belum ada recovery journal.");
@@ -13101,7 +13849,7 @@ async function checkLock(bundleDir) {
13101
13849
  const target = lockPath(bundleDir);
13102
13850
  let info;
13103
13851
  try {
13104
- info = await stat5(target);
13852
+ info = await stat6(target);
13105
13853
  } catch (error) {
13106
13854
  if (isMissingFile5(error)) {
13107
13855
  return makeCheck("lock", "pass", "Tidak ada lock; sidecar bebas ditulis.");
@@ -13127,7 +13875,7 @@ async function checkLock(bundleDir) {
13127
13875
  async function checkAgents(bundleDir) {
13128
13876
  let content;
13129
13877
  try {
13130
- content = await readFile8(join8(bundleDir, "AGENTS.md"), "utf8");
13878
+ content = await readFile10(join10(bundleDir, "AGENTS.md"), "utf8");
13131
13879
  } catch (error) {
13132
13880
  if (isMissingFile5(error)) {
13133
13881
  return makeCheck(
@@ -13157,7 +13905,7 @@ async function checkAgents(bundleDir) {
13157
13905
  async function checkExecutionSkill(bundleDir) {
13158
13906
  const missing = [];
13159
13907
  for (const dir of AGENT_SKILL_DIRS) {
13160
- const target = join8(bundleDir, dir, EXECUTION_SKILL_NAME, "SKILL.md");
13908
+ const target = join10(bundleDir, dir, EXECUTION_SKILL_NAME, "SKILL.md");
13161
13909
  if (!await isFile2(target)) missing.push(dir);
13162
13910
  }
13163
13911
  if (missing.length > 0) {
@@ -13205,8 +13953,8 @@ async function checkSkillPacks(bundleDir) {
13205
13953
  for (const skill of pack.skills) {
13206
13954
  let matched = false;
13207
13955
  for (const dir of AGENT_SKILL_DIRS) {
13208
- const target = join8(bundleDir, dir, skill.name);
13209
- if (!await isFile2(join8(target, "SKILL.md"))) continue;
13956
+ const target = join10(bundleDir, dir, skill.name);
13957
+ if (!await isFile2(join10(target, "SKILL.md"))) continue;
13210
13958
  try {
13211
13959
  if (await hashSkillDirectory(target) === skill.sha256) {
13212
13960
  matched = true;
@@ -13235,44 +13983,65 @@ async function checkSkillPacks(bundleDir) {
13235
13983
  var CAP_ID_RE = /\bCAP-[A-Z0-9-]+\b/g;
13236
13984
  var CAP_PLACEHOLDER_RE = /^CAP-X+$/;
13237
13985
  var TASK_CAP_RE = /^\s*cap:\s*(CAP-[A-Z0-9-]+)/im;
13986
+ function capabilityModelNotRequired(content) {
13987
+ const notRequired = /* @__PURE__ */ new Set();
13988
+ const start = content.search(/^##\s+Capability Model\s*$/im);
13989
+ if (start === -1) return notRequired;
13990
+ const section3 = content.slice(start);
13991
+ const next = section3.slice(1).search(/^##\s+/m);
13992
+ const body = next === -1 ? section3 : section3.slice(0, next + 1);
13993
+ for (const line of body.split("\n")) {
13994
+ const trimmed = line.trim();
13995
+ if (!trimmed.startsWith("|")) continue;
13996
+ const cells = trimmed.replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
13997
+ const cap = (cells[0] ?? "").toUpperCase();
13998
+ if (!/^CAP-[A-Z0-9-]+$/.test(cap) || CAP_PLACEHOLDER_RE.test(cap)) continue;
13999
+ if (!/^(?:yes|true|required|wajib)$/i.test(cells[1] ?? "")) notRequired.add(cap);
14000
+ }
14001
+ return notRequired;
14002
+ }
13238
14003
  async function collectMarkdownFiles2(root, prefix = "") {
13239
- const dir = join8(root, prefix);
14004
+ const dir = join10(root, prefix);
13240
14005
  let entries;
13241
14006
  try {
13242
- entries = await readdir6(dir, { withFileTypes: true });
14007
+ entries = await readdir7(dir, { withFileTypes: true });
13243
14008
  } catch {
13244
14009
  return [];
13245
14010
  }
13246
14011
  const files = [];
13247
14012
  for (const entry of entries) {
13248
- const relative2 = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`;
13249
- if (entry.isDirectory()) files.push(...await collectMarkdownFiles2(root, relative2));
13250
- else if (entry.isFile() && entry.name.endsWith(".md")) files.push(relative2);
14013
+ const relative3 = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`;
14014
+ if (entry.isDirectory()) files.push(...await collectMarkdownFiles2(root, relative3));
14015
+ else if (entry.isFile() && entry.name.endsWith(".md")) files.push(relative3);
13251
14016
  }
13252
14017
  return files;
13253
14018
  }
13254
14019
  async function checkCapabilityCoverage(bundleDir) {
13255
14020
  const taskCaps = /* @__PURE__ */ new Map();
13256
- for (const relative2 of await collectMarkdownFiles2(bundleDir, "tasks")) {
13257
- if (relative2 === BUNDLE_PATHS.TASKS_INDEX) continue;
13258
- const content = await readFile8(join8(bundleDir, relative2), "utf8");
14021
+ for (const relative3 of await collectMarkdownFiles2(bundleDir, "tasks")) {
14022
+ if (relative3 === BUNDLE_PATHS.TASKS_INDEX) continue;
14023
+ const content = await readFile10(join10(bundleDir, relative3), "utf8");
13259
14024
  const cap = TASK_CAP_RE.exec(content)?.[1]?.toUpperCase();
13260
14025
  if (cap === void 0) continue;
13261
- taskCaps.set(cap, relative2);
14026
+ taskCaps.set(cap, relative3);
13262
14027
  }
13263
14028
  const specCaps = /* @__PURE__ */ new Set();
13264
- for (const relative2 of await collectMarkdownFiles2(bundleDir, "specs")) {
13265
- const content = await readFile8(join8(bundleDir, relative2), "utf8");
14029
+ const notRequiredCaps = /* @__PURE__ */ new Set();
14030
+ for (const relative3 of await collectMarkdownFiles2(bundleDir, "specs")) {
14031
+ const content = await readFile10(join10(bundleDir, relative3), "utf8");
13266
14032
  for (const match of content.matchAll(CAP_ID_RE)) {
13267
14033
  const id = match[0].toUpperCase();
13268
14034
  if (CAP_PLACEHOLDER_RE.test(id)) continue;
13269
14035
  specCaps.add(id);
13270
14036
  }
14037
+ for (const cap of capabilityModelNotRequired(content)) notRequiredCaps.add(cap);
13271
14038
  }
13272
14039
  if (taskCaps.size === 0 && specCaps.size === 0) {
13273
14040
  return makeCheck("capability-coverage", "pass", "Tidak ada CAP-* (bundle legacy).");
13274
14041
  }
13275
- const missingTask = [...specCaps].filter((cap) => !taskCaps.has(cap));
14042
+ const missingTask = [...specCaps].filter(
14043
+ (cap) => !taskCaps.has(cap) && !notRequiredCaps.has(cap)
14044
+ );
13276
14045
  const missingSpec = [...taskCaps.keys()].filter((cap) => !specCaps.has(cap));
13277
14046
  const issues = [];
13278
14047
  if (missingTask.length > 0) {
@@ -13310,18 +14079,18 @@ async function checkDuplicates(bundleDir) {
13310
14079
  }
13311
14080
  const dirsByName = /* @__PURE__ */ new Map();
13312
14081
  for (const dir of AGENT_SKILL_DIRS) {
13313
- const root = join8(bundleDir, dir);
14082
+ const root = join10(bundleDir, dir);
13314
14083
  if (!await isDirectory2(root)) continue;
13315
14084
  let entries;
13316
14085
  try {
13317
- entries = await readdir6(root, { withFileTypes: true });
14086
+ entries = await readdir7(root, { withFileTypes: true });
13318
14087
  } catch {
13319
14088
  continue;
13320
14089
  }
13321
14090
  for (const entry of entries) {
13322
14091
  if (!entry.isDirectory()) continue;
13323
14092
  if (managed.has(entry.name)) continue;
13324
- if (!await isFile2(join8(root, entry.name, "SKILL.md"))) continue;
14093
+ if (!await isFile2(join10(root, entry.name, "SKILL.md"))) continue;
13325
14094
  const owners = dirsByName.get(entry.name) ?? [];
13326
14095
  owners.push(dir);
13327
14096
  dirsByName.set(entry.name, owners);
@@ -13341,7 +14110,7 @@ async function checkDuplicates(bundleDir) {
13341
14110
  async function checkHarness(bundleDir) {
13342
14111
  const detected = [];
13343
14112
  for (const dir of AGENT_SKILL_DIRS) {
13344
- if (await isDirectory2(join8(bundleDir, dir))) detected.push(dir);
14113
+ if (await isDirectory2(join10(bundleDir, dir))) detected.push(dir);
13345
14114
  }
13346
14115
  if (detected.length === 0) {
13347
14116
  return makeCheck("harness", "pass", "Tidak ada direktori harness terdeteksi.");
@@ -13395,7 +14164,7 @@ async function applyFixes(options, deps, checks) {
13395
14164
  let changed = false;
13396
14165
  if (checks.some((check) => check.id === "lock" && check.fixable === true)) {
13397
14166
  try {
13398
- await rm6(lockPath(options.bundleDir), { force: true });
14167
+ await rm7(lockPath(options.bundleDir), { force: true });
13399
14168
  changed = true;
13400
14169
  } catch {
13401
14170
  }
@@ -13438,8 +14207,8 @@ function formatTable(headers, rows) {
13438
14207
 
13439
14208
  // src/recovery.ts
13440
14209
  import { randomUUID as randomUUID2 } from "node:crypto";
13441
- import { mkdir as mkdir6, readFile as readFile9, rename as rename3, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
13442
- import { dirname as dirname6, join as join9 } from "node:path";
14210
+ import { mkdir as mkdir8, readFile as readFile11, rename as rename3, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
14211
+ import { dirname as dirname7, join as join11 } from "node:path";
13443
14212
  var RECOVERY_PATH = "tasks/.execution/recovery.json";
13444
14213
  var RECOVERY_BUDGET = { maxAttempts: 3 };
13445
14214
  var RECOVERY_BASE_ATTEMPTS = 3;
@@ -13451,7 +14220,7 @@ function recoveryBudget(input) {
13451
14220
  return Math.min(budget, RECOVERY_MAX_ATTEMPTS);
13452
14221
  }
13453
14222
  function recoveryPath(bundleDir) {
13454
- return join9(bundleDir, RECOVERY_PATH);
14223
+ return join11(bundleDir, RECOVERY_PATH);
13455
14224
  }
13456
14225
  function emptyJournal() {
13457
14226
  return { schemaVersion: 1, tasks: {} };
@@ -13466,7 +14235,7 @@ function isJournal(value) {
13466
14235
  async function readRecovery(bundleDir) {
13467
14236
  let raw;
13468
14237
  try {
13469
- raw = await readFile9(recoveryPath(bundleDir), "utf8");
14238
+ raw = await readFile11(recoveryPath(bundleDir), "utf8");
13470
14239
  } catch {
13471
14240
  return emptyJournal();
13472
14241
  }
@@ -13491,14 +14260,14 @@ function classifyFailure(input) {
13491
14260
  }
13492
14261
  async function writeRecovery(bundleDir, journal) {
13493
14262
  const target = recoveryPath(bundleDir);
13494
- await mkdir6(dirname6(target), { recursive: true });
14263
+ await mkdir8(dirname7(target), { recursive: true });
13495
14264
  const temp = `${target}.${process.pid}.${randomUUID2()}.tmp`;
13496
14265
  try {
13497
- await writeFile6(temp, `${JSON.stringify(journal, null, 2)}
14266
+ await writeFile8(temp, `${JSON.stringify(journal, null, 2)}
13498
14267
  `, "utf8");
13499
14268
  await rename3(temp, target);
13500
14269
  } catch (error) {
13501
- await rm7(temp, { force: true }).catch(() => {
14270
+ await rm8(temp, { force: true }).catch(() => {
13502
14271
  });
13503
14272
  throw error;
13504
14273
  }
@@ -13581,7 +14350,7 @@ function describeRecovery(entry) {
13581
14350
  }
13582
14351
 
13583
14352
  // src/session.ts
13584
- import { rm as rm8, stat as stat6 } from "node:fs/promises";
14353
+ import { rm as rm9, stat as stat7 } from "node:fs/promises";
13585
14354
  import { resolve as resolve4 } from "node:path";
13586
14355
  var LOCK_STALE_MS3 = 1e4;
13587
14356
  var CHANGE_REQUEST_PREFIX = "Perubahan diminta:";
@@ -13734,13 +14503,13 @@ async function removeStaleLock2(bundleDir) {
13734
14503
  const target = lockPath(bundleDir);
13735
14504
  let info;
13736
14505
  try {
13737
- info = await stat6(target);
14506
+ info = await stat7(target);
13738
14507
  } catch (error) {
13739
14508
  if (isMissingFile6(error)) return;
13740
14509
  throw error;
13741
14510
  }
13742
14511
  if (Date.now() - info.mtimeMs <= LOCK_STALE_MS3) return;
13743
- await rm8(target, { force: true });
14512
+ await rm9(target, { force: true });
13744
14513
  }
13745
14514
  function envFirst(primary, legacy) {
13746
14515
  const value = process.env[primary]?.trim();
@@ -13754,8 +14523,8 @@ function isMissingFile6(error) {
13754
14523
 
13755
14524
  // src/zip.ts
13756
14525
  var import_adm_zip = __toESM(require_adm_zip(), 1);
13757
- import { mkdir as mkdir7, writeFile as writeFile7 } from "node:fs/promises";
13758
- import { dirname as dirname7, resolve as resolve5, sep } from "node:path";
14526
+ import { mkdir as mkdir9, writeFile as writeFile9 } from "node:fs/promises";
14527
+ import { dirname as dirname8, resolve as resolve5, sep } from "node:path";
13759
14528
  var IGNORED_PREFIXES = [
13760
14529
  ".git/",
13761
14530
  "node_modules/",
@@ -13776,9 +14545,9 @@ var TOOL_CALL_LEAK_RE = /\r?\n[A-Za-z0-9_-]+">\s*\/[^\n]*(?=\r?\n|$)/g;
13776
14545
  function sanitizeMarkdown(content) {
13777
14546
  return content.replace(TOOL_CALL_LEAK_RE, "").replace(/\n{3,}/g, "\n\n");
13778
14547
  }
13779
- function isIgnoredBundlePath(relative2) {
13780
- if (IGNORED_FILES.has(relative2)) return true;
13781
- return IGNORED_PREFIXES.some((prefix) => relative2.startsWith(prefix));
14548
+ function isIgnoredBundlePath(relative3) {
14549
+ if (IGNORED_FILES.has(relative3)) return true;
14550
+ return IGNORED_PREFIXES.some((prefix) => relative3.startsWith(prefix));
13782
14551
  }
13783
14552
  async function extractBundle(bytes, targetDir) {
13784
14553
  const root = resolve5(targetDir);
@@ -13786,21 +14555,21 @@ async function extractBundle(bytes, targetDir) {
13786
14555
  const written = [];
13787
14556
  for (const entry of zip.getEntries()) {
13788
14557
  if (entry.isDirectory) continue;
13789
- const relative2 = entry.entryName.replace(/\\/g, "/").replace(/^\/+/, "");
13790
- const segments = relative2.split("/");
14558
+ const relative3 = entry.entryName.replace(/\\/g, "/").replace(/^\/+/, "");
14559
+ const segments = relative3.split("/");
13791
14560
  if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
13792
14561
  throw new Error(`Path bundle tidak aman: ${entry.entryName}`);
13793
14562
  }
13794
- if (isIgnoredBundlePath(relative2)) continue;
13795
- const destination = resolve5(root, relative2);
14563
+ if (isIgnoredBundlePath(relative3)) continue;
14564
+ const destination = resolve5(root, relative3);
13796
14565
  if (!destination.startsWith(`${root}${sep}`)) {
13797
14566
  throw new Error(`Path bundle keluar dari direktori target: ${entry.entryName}`);
13798
14567
  }
13799
- await mkdir7(dirname7(destination), { recursive: true });
14568
+ await mkdir9(dirname8(destination), { recursive: true });
13800
14569
  const raw = entry.getData();
13801
- const data = relative2.endsWith(".md") ? Buffer.from(sanitizeMarkdown(raw.toString("utf8")), "utf8") : raw;
13802
- await writeFile7(destination, data);
13803
- written.push(relative2);
14570
+ const data = relative3.endsWith(".md") ? Buffer.from(sanitizeMarkdown(raw.toString("utf8")), "utf8") : raw;
14571
+ await writeFile9(destination, data);
14572
+ written.push(relative3);
13804
14573
  }
13805
14574
  return written;
13806
14575
  }
@@ -13958,6 +14727,16 @@ async function pullCommand(projectId, options) {
13958
14727
  const written = await extractBundle(bytes, target);
13959
14728
  await clearBaseline(target).catch(() => {
13960
14729
  });
14730
+ const localContract = await snapshotContract(target);
14731
+ const serverContract = await client.getWorkspaceArtifacts(projectId).then(serverStateFromWorkspace).catch(() => null);
14732
+ await writeContractLedger(
14733
+ target,
14734
+ buildContractLedger(
14735
+ localContract,
14736
+ serverContract,
14737
+ serverContract?.derivation ?? freshDerivation(localContract)
14738
+ )
14739
+ );
13961
14740
  const uiQuality = options.uiQuality ?? await readUiQuality(target);
13962
14741
  const skills = await installAgentSkills(target, {
13963
14742
  noSkills: skillsDisabled(options),
@@ -13999,7 +14778,17 @@ async function linkCommand(projectId, options) {
13999
14778
  noSkills: skillsDisabled(options),
14000
14779
  uiQuality
14001
14780
  });
14002
- const linkedFile = join10(target, ".jioogen", "project.json");
14781
+ const localContract = await snapshotContract(target);
14782
+ const serverContract = await client.getWorkspaceArtifacts(projectId).then(serverStateFromWorkspace).catch(() => null);
14783
+ await writeContractLedger(
14784
+ target,
14785
+ buildContractLedger(
14786
+ localContract,
14787
+ serverContract,
14788
+ serverContract?.derivation ?? freshDerivation(localContract)
14789
+ )
14790
+ );
14791
+ const linkedFile = join12(target, ".jioogen", "project.json");
14003
14792
  if (options.json === true) {
14004
14793
  console.log(JSON.stringify({ projectId, target, apiUrl, linkedFile, skills }, null, 2));
14005
14794
  return;
@@ -14173,16 +14962,85 @@ function printSkillPacks(packs, missing, custom2 = [], conflicts = []) {
14173
14962
  );
14174
14963
  }
14175
14964
  }
14965
+ async function alignCommand(options) {
14966
+ const local = await resolveLocalBundle(options);
14967
+ let client;
14968
+ const noSync = options.noSync === true || process.env.JIOOGEN_NO_SYNC === "1";
14969
+ if (!noSync) {
14970
+ try {
14971
+ const api = await resolveApi({ api: options.api ?? local.linkedApiUrl });
14972
+ client = api.client;
14973
+ } catch {
14974
+ client = void 0;
14975
+ }
14976
+ }
14977
+ const autoDisabled = process.env.JIOOGEN_AUTO_ALIGN === "0";
14978
+ const result = await alignBundle(local.bundleDir, {
14979
+ ...client === void 0 ? {} : { client },
14980
+ projectId: local.projectId,
14981
+ ...autoDisabled ? {
14982
+ runAuthoring: async () => ({
14983
+ ok: false,
14984
+ error: "Authoring otomatis dimatikan (JIOOGEN_AUTO_ALIGN=0)."
14985
+ })
14986
+ } : {}
14987
+ });
14988
+ if (options.json === true) {
14989
+ console.log(JSON.stringify(result, null, 2));
14990
+ } else {
14991
+ console.log(formatAlign(result));
14992
+ }
14993
+ if (!result.ok) process.exitCode = 1;
14994
+ }
14995
+ async function approveCommand(options) {
14996
+ const { bundleDir } = await resolveLocalBundle(options);
14997
+ const local = await snapshotContract(bundleDir);
14998
+ if (local.prd === null) {
14999
+ throw new UsageError("PRD.md belum ada; tidak ada yang bisa disetujui.");
15000
+ }
15001
+ const at = (/* @__PURE__ */ new Date()).toISOString();
15002
+ await writeApproval(bundleDir, {
15003
+ schemaVersion: 1,
15004
+ prd: {
15005
+ hash: local.prd,
15006
+ at,
15007
+ ...options.note === void 0 ? {} : { note: options.note }
15008
+ }
15009
+ });
15010
+ await appendApprovalNote(bundleDir, {
15011
+ at,
15012
+ prdHash: local.prd,
15013
+ ...options.note === void 0 ? {} : { note: options.note }
15014
+ });
15015
+ if (options.json === true) {
15016
+ console.log(JSON.stringify({ bundleDir, prd: local.prd, at }, null, 2));
15017
+ return;
15018
+ }
15019
+ console.log("PRD lokal disetujui. Versi ini boleh diselaraskan ke web.");
15020
+ console.log("Jalankan `jioogen align` atau `jioogen task next` untuk melanjutkan.");
15021
+ }
14176
15022
  async function checkCommand(options) {
14177
15023
  const link = await findProjectLink(options.dir ?? process.cwd());
14178
15024
  const bundleDir = resolve6(link?.bundleDir ?? options.dir ?? process.cwd());
14179
15025
  const result = await inspectBundle(bundleDir);
15026
+ const local = await snapshotContract(bundleDir);
15027
+ const ledger = hasContractArtifacts(local) ? await readContractLedger(bundleDir) : null;
15028
+ const staleness = ledger === null ? { specsStale: false, tasksStale: false, stale: false } : computeStaleness(ledger.derivation, local);
14180
15029
  if (options.json === true) {
14181
- console.log(JSON.stringify(result, null, 2));
15030
+ console.log(
15031
+ JSON.stringify({ ...result, contract: { ledger: ledger !== null, ...staleness } }, null, 2)
15032
+ );
14182
15033
  } else {
14183
15034
  console.log(formatBundleCheck(result));
15035
+ if (ledger === null && hasContractArtifacts(local)) {
15036
+ console.log("Kontrak: baseline belum ada; jalankan `jioogen align` untuk menyelaraskan.");
15037
+ } else if (staleness.specsStale) {
15038
+ console.log("Kontrak: specs masih dari versi PRD lama. Jalankan `jioogen align`.");
15039
+ } else if (staleness.tasksStale) {
15040
+ console.log("Kontrak: tasks masih dari versi specs/PRD lama. Jalankan `jioogen align`.");
15041
+ }
14184
15042
  }
14185
- if (!result.ok) process.exitCode = 1;
15043
+ if (!result.ok || staleness.stale) process.exitCode = 1;
14186
15044
  }
14187
15045
  async function doctorCommand(options) {
14188
15046
  const link = await findProjectLink(options.dir ?? process.cwd());
@@ -14299,7 +15157,47 @@ async function handoffCommand(options) {
14299
15157
  for (const rule of payload.checkpointRules) console.log(`- ${rule}`);
14300
15158
  }
14301
15159
  }
15160
+ async function alignBeforeTask(options) {
15161
+ const local = await resolveLocalBundle(options);
15162
+ const contract = await snapshotContract(local.bundleDir);
15163
+ if (!hasContractArtifacts(contract)) return true;
15164
+ const ledger = await readContractLedger(local.bundleDir);
15165
+ const check = await inspectBundle(local.bundleDir);
15166
+ const stale = ledger === null ? true : computeStaleness(ledger.derivation, contract).stale;
15167
+ if (ledger !== null && check.ok && !stale) return true;
15168
+ if (options.json !== true) console.log("Kontrak belum selaras; menyelaraskan otomatis...");
15169
+ let client;
15170
+ const noSync = options.noSync === true || process.env.JIOOGEN_NO_SYNC === "1";
15171
+ if (!noSync) {
15172
+ try {
15173
+ const api = await resolveApi({ api: options.api ?? local.linkedApiUrl });
15174
+ client = api.client;
15175
+ } catch {
15176
+ client = void 0;
15177
+ }
15178
+ }
15179
+ const result = await alignBundle(local.bundleDir, {
15180
+ ...client === void 0 ? {} : { client },
15181
+ projectId: local.projectId
15182
+ });
15183
+ if (options.json === true) {
15184
+ console.log(
15185
+ JSON.stringify(
15186
+ { aligned: result.ok, blocked: result.blocked, applied: result.applied },
15187
+ null,
15188
+ 2
15189
+ )
15190
+ );
15191
+ } else {
15192
+ console.log(formatAlign(result));
15193
+ if (!result.ok) console.log("Task tidak dipilih sampai kontrak selaras.");
15194
+ }
15195
+ if (result.ok) return true;
15196
+ process.exitCode = 1;
15197
+ return false;
15198
+ }
14302
15199
  async function taskNextCommand(options) {
15200
+ if (!await alignBeforeTask(options)) return;
14303
15201
  const { projectId, bundleDir, definitions, written, next } = await withLocalState(
14304
15202
  options,
14305
15203
  async (local) => {
@@ -14440,10 +15338,10 @@ ${items.map((item, index) => `- [ ] ${prefix}-${String(index + 1).padStart(2, "0
14440
15338
  return;
14441
15339
  }
14442
15340
  if (authored.length > 0) {
14443
- const path2 = join10(local.bundleDir, "tasks", definition.file);
14444
- const current = await readFile10(path2, "utf8");
15341
+ const path2 = join12(local.bundleDir, "tasks", definition.file);
15342
+ const current = await readFile12(path2, "utf8");
14445
15343
  const stripped = current.replace(/\n##\s+Subtasks\b[\s\S]*?(?=\n##\s|$)/i, "").replace(/\n{3,}/g, "\n\n");
14446
- await writeFile8(path2, `${stripped.trimEnd()}
15344
+ await writeFile10(path2, `${stripped.trimEnd()}
14447
15345
 
14448
15346
  ${section3}`, "utf8");
14449
15347
  console.log(
@@ -14451,10 +15349,10 @@ ${section3}`, "utf8");
14451
15349
  );
14452
15350
  return;
14453
15351
  }
14454
- const dir = join10(local.bundleDir, ".jioogen", "breakdown");
14455
- const path = join10(dir, `${definition.id}.md`);
14456
- await mkdir8(dir, { recursive: true });
14457
- await writeFile8(
15352
+ const dir = join12(local.bundleDir, ".jioogen", "breakdown");
15353
+ const path = join12(dir, `${definition.id}.md`);
15354
+ await mkdir10(dir, { recursive: true });
15355
+ await writeFile10(
14458
15356
  path,
14459
15357
  `# Breakdown ${definition.id} \u2014 ${definition.title}
14460
15358
 
@@ -14661,7 +15559,7 @@ async function stampVerification(context, definitions, ref, proof, visualSummary
14661
15559
  async function resolveFallbackVerificationCommand(bundleDir, failedCommand) {
14662
15560
  let pkgRaw;
14663
15561
  try {
14664
- pkgRaw = await readFile10(join10(bundleDir, "package.json"), "utf8");
15562
+ pkgRaw = await readFile12(join12(bundleDir, "package.json"), "utf8");
14665
15563
  } catch {
14666
15564
  return null;
14667
15565
  }
@@ -14861,7 +15759,7 @@ function verifyTimeoutMs() {
14861
15759
  }
14862
15760
  function runVerification(command, cwd, timeoutMs) {
14863
15761
  return new Promise((resolve7) => {
14864
- const child = spawn("sh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
15762
+ const child = spawn2("sh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
14865
15763
  let stdout = "";
14866
15764
  let stderr = "";
14867
15765
  let timedOut = false;
@@ -14996,6 +15894,11 @@ async function statusCommand(options) {
14996
15894
  async function contractUpdateBaselineCommand(options) {
14997
15895
  const { bundleDir } = await resolveLocalBundle(options);
14998
15896
  const newBundleHash = await updateContractBaseline(bundleDir);
15897
+ const localContract = await snapshotContract(bundleDir);
15898
+ await writeContractLedger(
15899
+ bundleDir,
15900
+ buildContractLedger(localContract, null, freshDerivation(localContract))
15901
+ );
14999
15902
  console.log(`Baseline kontrak diupdate. Hash baru: ${newBundleHash}`);
15000
15903
  console.log(`File terverifikasi: PRD.md, traceability.md, specs/, tasks/`);
15001
15904
  console.log(`Perubahan lokal disetujui sebagai baseline baru.`);
@@ -15023,9 +15926,22 @@ async function driftCommand(options) {
15023
15926
  }
15024
15927
  const definitions = await loadTasks(bundleDir);
15025
15928
  const state = await readState(bundleDir);
15929
+ const localContract = await snapshotContract(bundleDir);
15930
+ const hasContract = hasContractArtifacts(localContract);
15931
+ const contractLedger = hasContract ? await readContractLedger(bundleDir) : null;
15932
+ const contractStale = contractLedger === null ? null : computeStaleness(contractLedger.derivation, localContract);
15933
+ const contractIssue = !hasContract ? null : contractLedger === null ? "Baseline kontrak belum ada; jalankan `jioogen align` atau `jioogen pull` untuk membuatnya." : contractStale?.specsStale === true ? "PRD berubah: specs masih dari versi PRD lama. Jalankan `jioogen align`." : contractStale?.tasksStale === true ? "Specs/PRD berubah: tasks masih dari versi lama. Jalankan `jioogen align`." : null;
15026
15934
  if (state === null) {
15027
15935
  if (options.json === true) {
15028
- console.log(JSON.stringify({ bundleDir, findings: [] }, null, 2));
15936
+ console.log(
15937
+ JSON.stringify({ bundleDir, findings: [], contract: { issue: contractIssue } }, null, 2)
15938
+ );
15939
+ if (options.strict === true && contractIssue !== null) process.exitCode = 1;
15940
+ return;
15941
+ }
15942
+ if (contractIssue !== null) {
15943
+ console.log(`Drift check ${bundleDir}: ${contractIssue}`);
15944
+ if (options.strict === true) process.exitCode = 1;
15029
15945
  return;
15030
15946
  }
15031
15947
  console.log(`Project bundle ${bundleDir}: belum ada sidecar; drift belum bisa dibandingkan.`);
@@ -15034,14 +15950,21 @@ async function driftCommand(options) {
15034
15950
  }
15035
15951
  const findings = await detectDrift(bundleDir, definitions, state);
15036
15952
  if (options.json === true) {
15037
- console.log(JSON.stringify({ bundleDir, findings }, null, 2));
15953
+ console.log(
15954
+ JSON.stringify({ bundleDir, findings, contract: { issue: contractIssue } }, null, 2)
15955
+ );
15956
+ if (options.strict === true && (contractIssue !== null || findings.some((finding) => finding.severity === "warn"))) {
15957
+ process.exitCode = 1;
15958
+ }
15038
15959
  if (options.strict === true && findings.some((finding) => finding.severity === "warn")) {
15039
15960
  process.exitCode = 1;
15040
15961
  }
15041
15962
  return;
15042
15963
  }
15964
+ if (contractIssue !== null) console.log(`\u26A0 ${contractIssue}`);
15043
15965
  if (findings.length === 0) {
15044
15966
  console.log(`Drift check ${bundleDir}: tidak ada perubahan di luar harness.`);
15967
+ if (options.strict === true && contractIssue !== null) process.exitCode = 1;
15045
15968
  return;
15046
15969
  }
15047
15970
  for (const finding of findings) {
@@ -15055,21 +15978,21 @@ async function driftCommand(options) {
15055
15978
  "- Perubahan tidak disengaja pada PRD.md/specs/tasks: `git checkout -- PRD.md specs tasks`"
15056
15979
  );
15057
15980
  console.log(
15058
- "- Perubahan kontrak disengaja: revisi via workspace web (https://gen.jioo.site), lalu `jioogen pull --force`."
15981
+ "- Perubahan kontrak disengaja: `jioogen align` (patch lokal disetujui) atau revisi via web lalu `jioogen pull`."
15059
15982
  );
15060
15983
  console.log(
15061
15984
  "- Perubahan di scope task: `jioogen task adopt <ref>` (setelah verifikasi) atau `jioogen task reset <ref>`."
15062
15985
  );
15063
15986
  }
15064
- if (options.strict === true && hasWarn) process.exitCode = 1;
15987
+ if (options.strict === true && (hasWarn || contractIssue !== null)) process.exitCode = 1;
15065
15988
  }
15066
15989
  async function baselineListCommand(options) {
15067
15990
  const bundleDir = await resolveSkillsBundleDir(options);
15068
15991
  const manifest = await readHarnessManifest(bundleDir);
15069
- const knowledgeDir = join10(bundleDir, ".jioogen", "custom", "knowledge");
15992
+ const knowledgeDir = join12(bundleDir, ".jioogen", "custom", "knowledge");
15070
15993
  let knowledgeFiles = [];
15071
15994
  try {
15072
- const entries = await readdir7(knowledgeDir, { withFileTypes: true });
15995
+ const entries = await readdir8(knowledgeDir, { withFileTypes: true });
15073
15996
  knowledgeFiles = entries.filter((entry) => entry.isFile()).map((entry) => entry.name).sort();
15074
15997
  } catch {
15075
15998
  knowledgeFiles = [];
@@ -15077,24 +16000,24 @@ async function baselineListCommand(options) {
15077
16000
  const nonEmptyKnowledge = [];
15078
16001
  for (const name of knowledgeFiles) {
15079
16002
  try {
15080
- const content = await readFile10(join10(knowledgeDir, name), "utf8");
16003
+ const content = await readFile12(join12(knowledgeDir, name), "utf8");
15081
16004
  if (content.trim().length > 0) nonEmptyKnowledge.push(name);
15082
16005
  } catch {
15083
16006
  }
15084
16007
  }
15085
- const customSkillsDir = join10(bundleDir, ".jioogen", "custom", "skills");
16008
+ const customSkillsDir = join12(bundleDir, ".jioogen", "custom", "skills");
15086
16009
  let customSkillNames = [];
15087
16010
  try {
15088
- const entries = await readdir7(customSkillsDir, { withFileTypes: true });
16011
+ const entries = await readdir8(customSkillsDir, { withFileTypes: true });
15089
16012
  customSkillNames = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
15090
16013
  } catch {
15091
16014
  customSkillNames = [];
15092
16015
  }
15093
- const agentsPath = join10(bundleDir, "AGENTS.md");
16016
+ const agentsPath = join12(bundleDir, "AGENTS.md");
15094
16017
  let agentsExists = false;
15095
16018
  let agentsBaseline = false;
15096
16019
  try {
15097
- const content = await readFile10(agentsPath, "utf8");
16020
+ const content = await readFile12(agentsPath, "utf8");
15098
16021
  agentsExists = true;
15099
16022
  agentsBaseline = content.includes("jioogen-execution-skill");
15100
16023
  } catch {
@@ -15178,12 +16101,12 @@ async function syncCommand(options) {
15178
16101
  ];
15179
16102
  if (options.files !== void 0) {
15180
16103
  for (const raw of options.files.split(",")) {
15181
- const relative2 = raw.trim();
15182
- if (relative2.length === 0) continue;
15183
- assertBundleRelative(relative2);
16104
+ const relative3 = raw.trim();
16105
+ if (relative3.length === 0) continue;
16106
+ assertBundleRelative(relative3);
15184
16107
  files.push({
15185
- path: relative2,
15186
- content: await readFile10(join10(bundleDir, relative2), "utf8")
16108
+ path: relative3,
16109
+ content: await readFile12(join12(bundleDir, relative3), "utf8")
15187
16110
  });
15188
16111
  }
15189
16112
  }
@@ -15438,7 +16361,7 @@ async function assertPullDefaultDir(cwd, dirOption) {
15438
16361
  async function assertPullTarget(target, projectId, force = false) {
15439
16362
  let entries;
15440
16363
  try {
15441
- entries = await readdir7(target);
16364
+ entries = await readdir8(target);
15442
16365
  } catch (error) {
15443
16366
  if (isMissingFile7(error)) return;
15444
16367
  throw error;
@@ -15472,17 +16395,17 @@ async function assertLinkTarget(target, projectId) {
15472
16395
  }
15473
16396
  async function hasBundleMarkers(target) {
15474
16397
  try {
15475
- await readFile10(join10(target, "PRD.md"));
16398
+ await readFile12(join12(target, "PRD.md"));
15476
16399
  return true;
15477
16400
  } catch (error) {
15478
16401
  if (!isMissingFile7(error)) throw error;
15479
16402
  }
15480
- return hasTaskMarkdown(join10(target, "tasks"));
16403
+ return hasTaskMarkdown(join12(target, "tasks"));
15481
16404
  }
15482
16405
  async function hasTaskMarkdown(directory) {
15483
16406
  let names;
15484
16407
  try {
15485
- names = await readdir7(directory);
16408
+ names = await readdir8(directory);
15486
16409
  } catch (error) {
15487
16410
  if (isMissingFile7(error)) return false;
15488
16411
  throw error;
@@ -15490,15 +16413,15 @@ async function hasTaskMarkdown(directory) {
15490
16413
  return names.some((name) => name.toLowerCase().endsWith(".md"));
15491
16414
  }
15492
16415
  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");
16416
+ const stackDir = join12(bundleDir, ".jioogen", "custom", "stack");
16417
+ const knowledgeDir = join12(bundleDir, ".jioogen", "custom", "knowledge");
16418
+ const designDir = join12(bundleDir, ".jioogen", "custom", "design");
16419
+ await mkdir10(stackDir, { recursive: true });
16420
+ await mkdir10(knowledgeDir, { recursive: true });
16421
+ await mkdir10(designDir, { recursive: true });
16422
+ const exampleFile = join12(stackDir, "STACK.md.example");
15500
16423
  try {
15501
- await stat7(exampleFile);
16424
+ await stat8(exampleFile);
15502
16425
  } catch {
15503
16426
  const template = [
15504
16427
  "# Custom Stack & Architecture Preferences",
@@ -15512,7 +16435,7 @@ async function scaffoldCustomLayer(bundleDir) {
15512
16435
  "- Testing Runner: Vitest (bukan Jest)",
15513
16436
  ""
15514
16437
  ].join("\n");
15515
- await writeFile8(exampleFile, template, "utf8").catch(() => {
16438
+ await writeFile10(exampleFile, template, "utf8").catch(() => {
15516
16439
  });
15517
16440
  }
15518
16441
  }
@@ -15714,7 +16637,7 @@ async function readLine() {
15714
16637
  }
15715
16638
 
15716
16639
  // src/index.ts
15717
- var VERSION = "0.2.12";
16640
+ var VERSION = "0.2.13";
15718
16641
  function parseTaskModeOption(value) {
15719
16642
  if (value === void 0) return void 0;
15720
16643
  const parsed = TaskModeSchema.safeParse(value);
@@ -15752,6 +16675,8 @@ Usage:
15752
16675
  jioogen authoring install [--dir <dir>]
15753
16676
  jioogen authoring status [--dir <dir>] [--json]
15754
16677
  jioogen authoring remove [--dir <dir>]
16678
+ jioogen align [--dir <dir>] [--json]
16679
+ jioogen approve [--dir <dir>] [--note <text>] [--json]
15755
16680
  jioogen check [--dir <dir>] [--json]
15756
16681
  jioogen doctor [--fix] [--dir <dir>] [--json]
15757
16682
  jioogen drift [--dir <dir>] [--json] [--strict] [--acknowledge] [--prd] [--specs] [--tasks] [--note <text>]
@@ -15960,6 +16885,12 @@ async function dispatch(command, rest, options) {
15960
16885
  case "authoring":
15961
16886
  await dispatchAuthoring(rest, options);
15962
16887
  return;
16888
+ case "align":
16889
+ await alignCommand(options);
16890
+ return;
16891
+ case "approve":
16892
+ await approveCommand(options);
16893
+ return;
15963
16894
  case "check":
15964
16895
  await checkCommand(options);
15965
16896
  return;