@aisdlc/core 3.2.0 → 3.4.0

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.cjs CHANGED
@@ -5087,6 +5087,256 @@ function emitCiOutput(key, value, env = process.env) {
5087
5087
  writeEnvOutputFile(envOutputFile, key, value);
5088
5088
  }
5089
5089
  }
5090
+ var DEFAULT_DLP_RULES = [
5091
+ {
5092
+ id: "DLP-001-PRIVATE-KEY",
5093
+ description: "PEM / RSA / EC / OPENSSH Private Key Block",
5094
+ pattern: "-----BEGIN (?:[A-Z0-9_-]+ )?PRIVATE KEY-----[\\s\\S]*?-----END (?:[A-Z0-9_-]+ )?PRIVATE KEY-----",
5095
+ replacement: "[REDACTED:PRIVATE_KEY]",
5096
+ enabled: true
5097
+ },
5098
+ {
5099
+ id: "DLP-002-API-TOKEN",
5100
+ description: "Cloud, GitHub, Slack, OpenAI, Stripe, and AWS Access Tokens",
5101
+ pattern: "\\b(?:gh[pousr]_[A-Za-z0-9_]{36,255}|github_pat_[0-9a-zA-Z_]{82}|sk-(?:proj-|live-)?[a-zA-Z0-9_-]{32,}|AKIA[0-9A-Z]{16}|xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*|(?:sk|rk)_(?:live|test)_[0-9a-zA-Z]{24,99})\\b",
5102
+ replacement: "[REDACTED:API_TOKEN]",
5103
+ enabled: true
5104
+ },
5105
+ {
5106
+ id: "DLP-003-JWT",
5107
+ description: "Plaintext JSON Web Token (JWT)",
5108
+ pattern: "\\beyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\b",
5109
+ replacement: "[REDACTED:JWT_TOKEN]",
5110
+ enabled: true
5111
+ },
5112
+ {
5113
+ id: "DLP-004-CREDIT-CARD",
5114
+ description: "Payment Card Number (13-19 digits formatted)",
5115
+ pattern: "\\b(?:\\d{4}[- ]\\d{4}[- ]\\d{4}[- ]\\d{4}|(?!9007199254740991)\\d{16})\\b",
5116
+ replacement: "[REDACTED:CREDIT_CARD]",
5117
+ enabled: true
5118
+ },
5119
+ {
5120
+ id: "DLP-005-EMAIL",
5121
+ description: "Personal or Corporate Email Address",
5122
+ pattern: "\\b[A-Za-z0-9._%+-]+@(?!example\\.com|localhost|test\\.local)[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b",
5123
+ replacement: "[REDACTED:EMAIL]",
5124
+ enabled: true
5125
+ },
5126
+ {
5127
+ id: "DLP-006-INTERNAL-URL",
5128
+ description: "Internal Intranet / Corp Service URL",
5129
+ pattern: "https?://(?:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+@|[A-Za-z0-9.-]+\\.(?:internal|corp|intranet|local)\\b)[^\\s\"'`<>]*",
5130
+ replacement: "[REDACTED:INTERNAL_URL]",
5131
+ enabled: true
5132
+ }
5133
+ ];
5134
+ function createDefaultDlpPolicy() {
5135
+ return {
5136
+ version: "1.0",
5137
+ enabled: true,
5138
+ zero_data_retention_required: true,
5139
+ rules: [...DEFAULT_DLP_RULES]
5140
+ };
5141
+ }
5142
+ function normalizeParsedRule(raw, idx) {
5143
+ if (typeof raw.pattern !== "string" || !raw.pattern) return null;
5144
+ return {
5145
+ id: typeof raw.id === "string" ? raw.id : `DLP-CUSTOM-${idx + 1}`,
5146
+ description: typeof raw.description === "string" ? raw.description : "Custom DLP rule",
5147
+ pattern: raw.pattern,
5148
+ replacement: typeof raw.replacement === "string" ? raw.replacement : "[REDACTED]",
5149
+ enabled: raw.enabled !== false
5150
+ };
5151
+ }
5152
+ function parseDlpDoc(yamlContent) {
5153
+ let doc;
5154
+ try {
5155
+ doc = yaml3__default.default.load(yamlContent);
5156
+ } catch (err) {
5157
+ throw new Error(`[AI-SDLC Fail-Closed] Invalid YAML in dlp-policy: ${err instanceof Error ? err.message : String(err)}`);
5158
+ }
5159
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
5160
+ throw new Error(`[AI-SDLC Fail-Closed] Invalid dlp-policy structure: root must be a YAML mapping`);
5161
+ }
5162
+ const record = doc;
5163
+ if (record.rules !== void 0 && !Array.isArray(record.rules)) {
5164
+ throw new Error(`[AI-SDLC Fail-Closed] Invalid dlp-policy: rules must be an array`);
5165
+ }
5166
+ return record;
5167
+ }
5168
+ function parseDlpPolicy(yamlContent) {
5169
+ const fallback = createDefaultDlpPolicy();
5170
+ if (!yamlContent || !yamlContent.trim()) return fallback;
5171
+ const record = parseDlpDoc(yamlContent);
5172
+ const rawRules = Array.isArray(record.rules) ? record.rules : [];
5173
+ const parsedRules = rawRules.map((r, i) => normalizeParsedRule(r, i)).filter((r) => r !== null);
5174
+ return {
5175
+ version: typeof record.version === "string" ? record.version : "1.0",
5176
+ enabled: record.enabled !== false,
5177
+ zero_data_retention_required: Boolean(record.zero_data_retention_required ?? true),
5178
+ rules: parsedRules.length > 0 ? parsedRules : fallback.rules
5179
+ };
5180
+ }
5181
+ function loadDlpPolicy(rootDir, customPolicyPath) {
5182
+ const base = rootDir || process.cwd();
5183
+ const filePath = customPolicyPath ? path5__namespace.isAbsolute(customPolicyPath) ? customPolicyPath : path5__namespace.join(base, customPolicyPath) : path5__namespace.join(base, "dlp-policy.yaml");
5184
+ if (!fs8__namespace.existsSync(filePath)) return createDefaultDlpPolicy();
5185
+ return parseDlpPolicy(fs8__namespace.readFileSync(filePath, "utf-8"));
5186
+ }
5187
+ function applySingleDlpRule(text, rule) {
5188
+ if (rule.enabled === false) return { output: text, matches: 0 };
5189
+ try {
5190
+ const regex = new RegExp(rule.pattern, "g");
5191
+ let matches = 0;
5192
+ const output = text.replace(regex, () => {
5193
+ matches++;
5194
+ return rule.replacement;
5195
+ });
5196
+ return { output, matches };
5197
+ } catch {
5198
+ return { output: text, matches: 0 };
5199
+ }
5200
+ }
5201
+ function sanitizeDlpText(text, policy = createDefaultDlpPolicy()) {
5202
+ if (!policy.enabled || !text) {
5203
+ return { sanitizedText: text, redactionCount: 0, triggeredRuleIds: [] };
5204
+ }
5205
+ let current = text;
5206
+ let totalRedactions = 0;
5207
+ const triggered = [];
5208
+ for (const rule of policy.rules) {
5209
+ const res = applySingleDlpRule(current, rule);
5210
+ if (res.matches > 0) {
5211
+ current = res.output;
5212
+ totalRedactions += res.matches;
5213
+ triggered.push(rule.id);
5214
+ }
5215
+ }
5216
+ return {
5217
+ sanitizedText: current,
5218
+ redactionCount: totalRedactions,
5219
+ triggeredRuleIds: triggered
5220
+ };
5221
+ }
5222
+ function sanitizeDlpPayload(payload, policy = createDefaultDlpPolicy()) {
5223
+ if (!policy.enabled || payload === null || payload === void 0) return payload;
5224
+ if (typeof payload === "string") {
5225
+ return sanitizeDlpText(payload, policy).sanitizedText;
5226
+ }
5227
+ const serialized = JSON.stringify(payload);
5228
+ const { sanitizedText } = sanitizeDlpText(serialized, policy);
5229
+ try {
5230
+ return JSON.parse(sanitizedText);
5231
+ } catch {
5232
+ return payload;
5233
+ }
5234
+ }
5235
+
5236
+ // src/adapters/sdd/review-report.ts
5237
+ var REVIEW_VERDICTS = ["COMPLIANT", "SUGGESTIONS", "BLOCKING"];
5238
+ var REVIEWER_ROLES = [
5239
+ "agent-code-reviewer",
5240
+ "agent-security-auditor",
5241
+ "agent-compliance-checker",
5242
+ "agent-privacy-officer",
5243
+ "agent-expert-user",
5244
+ "auditor",
5245
+ "reviewer"
5246
+ ];
5247
+ function isReviewerRole(role) {
5248
+ if (!role || typeof role !== "string") return false;
5249
+ const normalized = role.toLowerCase().trim();
5250
+ return REVIEWER_ROLES.includes(normalized);
5251
+ }
5252
+ function validateChangeId(changeId, rootDir) {
5253
+ if (!changeId || typeof changeId !== "string") {
5254
+ return { ok: false, error: "Missing changeId for review report submission" };
5255
+ }
5256
+ const rawChange = changeId.trim();
5257
+ if (rawChange.includes("..") || rawChange.includes("/") || rawChange.includes("\\") || !/^[a-zA-Z0-9_\-.]+$/.test(rawChange)) {
5258
+ return { ok: false, error: `Invalid changeId: path traversal or invalid characters detected '${rawChange}'` };
5259
+ }
5260
+ const activeChangeDir = path5__namespace.join(rootDir, "specs", "changes", "active", rawChange);
5261
+ if (!fs8__namespace.existsSync(activeChangeDir)) {
5262
+ return { ok: false, error: `Active change not found in specs/changes/active: '${rawChange}'` };
5263
+ }
5264
+ return { ok: true, changeDir: activeChangeDir, rawChange };
5265
+ }
5266
+ function validateReviewer(reviewer) {
5267
+ if (!reviewer || typeof reviewer !== "string") {
5268
+ return { ok: false, error: "Reviewer role is required" };
5269
+ }
5270
+ const rawReviewer = reviewer.trim().toLowerCase();
5271
+ if (rawReviewer.includes("..") || rawReviewer.includes("/") || rawReviewer.includes("\\")) {
5272
+ return { ok: false, error: `Invalid reviewer name: path traversal detected '${rawReviewer}'` };
5273
+ }
5274
+ if (!isReviewerRole(rawReviewer)) {
5275
+ return {
5276
+ ok: false,
5277
+ error: `Role '${reviewer}' is not an authorized reviewer role. Authorized roles: ${REVIEWER_ROLES.join(", ")}`
5278
+ };
5279
+ }
5280
+ return { ok: true, rawReviewer };
5281
+ }
5282
+ function validateVerdictAndBody(verdict, body) {
5283
+ if (!verdict || !REVIEW_VERDICTS.includes(verdict)) {
5284
+ return {
5285
+ ok: false,
5286
+ error: `Invalid verdict '${verdict}'. Allowed verdicts: ${REVIEW_VERDICTS.join(", ")}`
5287
+ };
5288
+ }
5289
+ if (!body || typeof body !== "string" || !body.trim()) {
5290
+ return { ok: false, error: "Review report body cannot be empty" };
5291
+ }
5292
+ return { ok: true };
5293
+ }
5294
+ function buildReportMarkdown(change, reviewer, verdict, body, date) {
5295
+ return [
5296
+ `# Review Report: ${reviewer}`,
5297
+ "",
5298
+ `- change: ${change}`,
5299
+ `- reviewer: ${reviewer}`,
5300
+ `- verdict: ${verdict}`,
5301
+ `- date: ${date}`,
5302
+ "",
5303
+ "## Findings",
5304
+ "",
5305
+ body,
5306
+ ""
5307
+ ].join("\n");
5308
+ }
5309
+ function persistReportFile(changeDir, rawReviewer, content) {
5310
+ const reviewsDir = path5__namespace.join(changeDir, "reviews");
5311
+ if (!fs8__namespace.existsSync(reviewsDir)) {
5312
+ fs8__namespace.mkdirSync(reviewsDir, { recursive: true });
5313
+ }
5314
+ const reportFileName = `${rawReviewer}.md`;
5315
+ fs8__namespace.writeFileSync(path5__namespace.join(reviewsDir, reportFileName), content, "utf-8");
5316
+ return crypto3__namespace.createHash("sha256").update(content.replace(/\r\n/g, "\n")).digest("hex");
5317
+ }
5318
+ function submitReviewReport(options) {
5319
+ const root = options.rootDir || process.cwd();
5320
+ const changeCheck = validateChangeId(options.changeId, root);
5321
+ if (!changeCheck.ok) return { success: false, error: changeCheck.error };
5322
+ const reviewerCheck = validateReviewer(options.reviewer);
5323
+ if (!reviewerCheck.ok) return { success: false, error: reviewerCheck.error };
5324
+ const contentCheck = validateVerdictAndBody(options.verdict, options.body);
5325
+ if (!contentCheck.ok) return { success: false, error: contentCheck.error };
5326
+ const rawChange = changeCheck.rawChange;
5327
+ const rawReviewer = reviewerCheck.rawReviewer;
5328
+ const dlpPolicy = loadDlpPolicy(root);
5329
+ const sanitizedBody = sanitizeDlpText(options.body.trim(), dlpPolicy).sanitizedText;
5330
+ const date = options.date || (/* @__PURE__ */ new Date()).toISOString();
5331
+ const reportContent = buildReportMarkdown(rawChange, rawReviewer, options.verdict, sanitizedBody, date);
5332
+ const digest = persistReportFile(changeCheck.changeDir, rawReviewer, reportContent);
5333
+ return {
5334
+ success: true,
5335
+ reportPath: `specs/changes/active/${rawChange}/reviews/${rawReviewer}.md`,
5336
+ digest,
5337
+ verdict: options.verdict
5338
+ };
5339
+ }
5090
5340
 
5091
5341
  // src/adapters/sdd/index.ts
5092
5342
  function getSddAdapter(framework) {
@@ -7388,6 +7638,46 @@ function verifyLicenses(options = {}) {
7388
7638
  const reportMarkdown = generateLicenseReportMarkdown(dependencies, violations, policy, artifacts.sbomPath);
7389
7639
  return assembleDynamicLicenseResult(dependencies, permittedCount, violations, reportMarkdown, artifacts, vulnData);
7390
7640
  }
7641
+ var IGNORED_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "bin", "obj", "dist", "build", "target", "reports", "templates"]);
7642
+ var MSBUILD_WEAKENING = [
7643
+ /<TreatWarningsAsErrors>\s*false\s*<\/TreatWarningsAsErrors>/i,
7644
+ /<Nullable>\s*disable\s*<\/Nullable>/i,
7645
+ /<RunAnalyzers>\s*false\s*<\/RunAnalyzers>/i
7646
+ ];
7647
+ var TSCONFIG_WEAKENING = [/"strict"\s*:\s*false/, /"noImplicitAny"\s*:\s*false/, /"strictNullChecks"\s*:\s*false/];
7648
+ function walkFiles(dir, rootDir, out) {
7649
+ for (const entry of fs8__namespace.readdirSync(dir, { withFileTypes: true })) {
7650
+ if (entry.isDirectory() && !IGNORED_DIRS.has(entry.name)) walkFiles(path5__namespace.join(dir, entry.name), rootDir, out);
7651
+ else if (entry.isFile()) out.push(path5__namespace.relative(rootDir, path5__namespace.join(dir, entry.name)).replace(/\\/g, "/"));
7652
+ }
7653
+ return out;
7654
+ }
7655
+ function matchWeakening(rel, content, patterns) {
7656
+ return patterns.filter((p) => p.test(content)).map((p) => `[CODING-RULES-BYPASS] '${rel}' weakens the strict coding rules (${p.source}).`);
7657
+ }
7658
+ function checkMsBuildFile(rel, content) {
7659
+ const issues = matchWeakening(rel, content, MSBUILD_WEAKENING);
7660
+ const isNestedBuildProps = /(^|\/)Directory\.Build\.props$/.test(rel) && rel !== "Directory.Build.props";
7661
+ if (isNestedBuildProps && !content.includes("GetPathOfFileAbove")) {
7662
+ issues.push(`[CODING-RULES-BYPASS] Nested '${rel}' does not import the parent Directory.Build.props (GetPathOfFileAbove), silently dropping root rules.`);
7663
+ }
7664
+ return issues;
7665
+ }
7666
+ function checkFile(rel, content, hasDotnetRules, hasTsRules) {
7667
+ if (hasDotnetRules && /\.(csproj|props|targets)$/.test(rel)) return checkMsBuildFile(rel, content);
7668
+ if (hasTsRules && /(^|\/)tsconfig[^/]*\.json$/.test(rel) && !rel.endsWith("tsconfig.strict.json")) {
7669
+ return matchWeakening(rel, content, TSCONFIG_WEAKENING);
7670
+ }
7671
+ return [];
7672
+ }
7673
+ function collectCodingRulesBypassViolations(rootDir) {
7674
+ const hasDotnetRules = fs8__namespace.existsSync(path5__namespace.join(rootDir, "Directory.Build.props"));
7675
+ const hasTsRules = fs8__namespace.existsSync(path5__namespace.join(rootDir, "tsconfig.strict.json"));
7676
+ if (!hasDotnetRules && !hasTsRules) return [];
7677
+ return walkFiles(rootDir, rootDir, []).flatMap(
7678
+ (rel) => checkFile(rel, fs8__namespace.readFileSync(path5__namespace.join(rootDir, rel), "utf-8"), hasDotnetRules, hasTsRules)
7679
+ );
7680
+ }
7391
7681
  var PROTECTED_BYPASS_PATTERNS = [
7392
7682
  /^schemas[\\/]/i,
7393
7683
  /^examples[\\/]security[\\/]/i,
@@ -7398,7 +7688,8 @@ var PROTECTED_BYPASS_PATTERNS = [
7398
7688
  /license-policy\.ya?ml$/i,
7399
7689
  /08_security_concept\.md$/i,
7400
7690
  /09_decisions[\\/]/i,
7401
- /migrations?[\\/]/i
7691
+ /migrations?[\\/]/i,
7692
+ /^\.github[\\/]CODEOWNERS$/i
7402
7693
  ];
7403
7694
  function detectProfileFromChange(changeDir) {
7404
7695
  if (!fs8__namespace.existsSync(changeDir)) return "standard";
@@ -7534,7 +7825,10 @@ function verifyProgressiveFriction(options = {}) {
7534
7825
  const changeDir = resolveChangeDirectory(rootDir, options);
7535
7826
  const profile = changeDir ? detectProfileFromChange(changeDir) : "standard";
7536
7827
  const modifiedFiles = options.diffFiles || options.modifiedFiles || (profile === "patch" ? detectGitDiffFiles(rootDir) : []);
7537
- const violations = profile === "patch" ? collectPatchViolations(rootDir, modifiedFiles) : [];
7828
+ const violations = [
7829
+ ...profile === "patch" ? collectPatchViolations(rootDir, modifiedFiles) : [],
7830
+ ...collectCodingRulesBypassViolations(rootDir)
7831
+ ];
7538
7832
  const bypassed = violations.length > 0;
7539
7833
  const success = !bypassed;
7540
7834
  return {
@@ -10337,6 +10631,28 @@ function extractCommitKpisFromRange(baseRef, headRef = "HEAD", options = {}) {
10337
10631
  }
10338
10632
  return records;
10339
10633
  }
10634
+ function extractAllRepoCommitKpis(options = {}) {
10635
+ const cwd = options.cwd || process.cwd();
10636
+ const format = "---AI_SDLC_COMMIT---%n%H%x1f%an%x1f%ae%x1f%aI%x1f%s%n%B%n---AI_SDLC_BODY_END---";
10637
+ let rawOutput = "";
10638
+ try {
10639
+ rawOutput = child_process.execFileSync("git", ["log", "--all", `--format=${format}`, "--numstat"], {
10640
+ cwd,
10641
+ encoding: "utf-8",
10642
+ stdio: ["pipe", "pipe", "pipe"]
10643
+ });
10644
+ } catch {
10645
+ return [];
10646
+ }
10647
+ if (!rawOutput) return [];
10648
+ const chunks = parseRawLogChunks(rawOutput);
10649
+ const records = [];
10650
+ for (const chunk of chunks) {
10651
+ const rec = buildCommitKpiRecord(chunk);
10652
+ if (rec) records.push(rec);
10653
+ }
10654
+ return records;
10655
+ }
10340
10656
  var AGENT_ENV_MAPPINGS = [
10341
10657
  { envKey: "ANTIGRAVITY_AGENT", defaultModel: "gemini-3.8-flash", source: "antigravity" },
10342
10658
  { envKey: "ANTIGRAVITY_CONVERSATION_ID", defaultModel: "gemini-3.8-flash", source: "antigravity" },
@@ -10520,6 +10836,24 @@ if echo "$CURRENT_BRANCH" | grep -qE "^(main|master|release/.*)$"; then
10520
10836
  exit 1
10521
10837
  fi
10522
10838
 
10839
+ # Immutable Coding Rules Guard: block AI agents from adding, modifying or deleting coding rules files
10840
+ IS_AGENT=0
10841
+ if [ -n "$AI_MODEL" ] || [ -n "$AI_AGENT_NAME" ] || [ -n "$ANTIGRAVITY_AGENT" ] || [ -n "$ANTIGRAVITY_AGENT_ID" ] || [ -n "$ANTIGRAVITY_CONVERSATION_ID" ] || [ -n "$CLAUDE_CODE" ] || [ -n "$CURSOR_AGENT" ] || [ -n "$WINDSURF_AGENT" ] || [ -n "$AIDER_MODEL" ] || [ -f ".ai-sdlc/session-telemetry.json" ]; then
10842
+ IS_AGENT=1
10843
+ fi
10844
+
10845
+ if [ "$IS_AGENT" = "1" ]; then
10846
+ TAMPERED_RULES=$(git diff --cached --diff-filter=AMDR --name-only 2>/dev/null | grep -E "(^|/)(Directory\\.Build\\.props|tsconfig\\.strict\\.json|eslint\\.config\\.mjs|gradle/init\\.d/aisdlc-strict\\.init\\.gradle\\.kts|config/pmd/aisdlc-ruleset\\.xml|config/detekt/detekt\\.yml|\\.cargo/config\\.toml|\\.clippy\\.toml|\\.golangci\\.yml|\\.clang-tidy|cmake/AisdlcStrictCompiler\\.cmake|\\.github/CODEOWNERS|templates/coding-rules/.+)$" || echo "")
10847
+ if [ -n "$TAMPERED_RULES" ]; then
10848
+ echo "" >&2
10849
+ echo "\u274C [AI-SDLC Immutable Coding Rules Guard] BLOCKED: AI agents are forbidden from adding, modifying or deleting coding rules files:" >&2
10850
+ echo "$TAMPERED_RULES" >&2
10851
+ echo "Fix the source or test code to comply with the compiler/linter rules instead of altering the rule configuration." >&2
10852
+ echo "" >&2
10853
+ exit 1
10854
+ fi
10855
+ fi
10856
+
10523
10857
  exit 0
10524
10858
  `;
10525
10859
  var PREPARE_COMMIT_MSG_SCRIPT = `#!/usr/bin/env bash
@@ -10637,7 +10971,7 @@ function installGitHooks(rootDir = process.cwd()) {
10637
10971
  fs8__namespace.mkdirSync(hooksDir, { recursive: true });
10638
10972
  }
10639
10973
  const prepareCommitMsgPath = path5__namespace.join(hooksDir, "prepare-commit-msg");
10640
- const preCommitPath = path5__namespace.join(hooksDir, "pre-commit");
10974
+ const preCommitPath = path5__namespace.join(gitDir, "hooks", "pre-commit");
10641
10975
  try {
10642
10976
  fs8__namespace.writeFileSync(prepareCommitMsgPath, PREPARE_COMMIT_MSG_SCRIPT, { encoding: "utf-8", mode: 493 });
10643
10977
  fs8__namespace.writeFileSync(preCommitPath, PRE_COMMIT_SCRIPT, { encoding: "utf-8", mode: 493 });
@@ -11025,7 +11359,7 @@ function getCytoscapeScript() {
11025
11359
  const scriptPath = resolveCytoscapePath();
11026
11360
  if (scriptPath) {
11027
11361
  try {
11028
- cachedScript = fs8__namespace.readFileSync(scriptPath, "utf-8");
11362
+ cachedScript = fs8__namespace.readFileSync(scriptPath, "utf-8").replace(/\b9007199254740991\b/g, "(Math.pow(2,53)-1)");
11029
11363
  return cachedScript;
11030
11364
  } catch {
11031
11365
  }
@@ -12031,7 +12365,7 @@ var DASHBOARD_CLIENT_SCRIPT = `
12031
12365
  container: document.getElementById('cy'),
12032
12366
  elements: safeElements,
12033
12367
  boxSelectionEnabled: false,
12034
- autoungrabify: true,
12368
+ autoungrabify: false,
12035
12369
  style: [
12036
12370
  {
12037
12371
  selector: 'node',
@@ -12321,6 +12655,9 @@ var DASHBOARD_CLIENT_SCRIPT = `
12321
12655
  }
12322
12656
  });
12323
12657
 
12658
+ setTimeout(function() { if (cy) { cy.resize(); cy.fit(30); } }, 150);
12659
+ window.addEventListener('resize', function() { if (cy) { cy.resize(); } });
12660
+
12324
12661
  cy.on('tap', 'node', function(evt) {
12325
12662
  var node = evt.target;
12326
12663
  var data = node.data();
@@ -13547,7 +13884,28 @@ function collectGitPrefixedBranches(rootDir) {
13547
13884
  return [];
13548
13885
  }
13549
13886
  }
13550
- function resolveCandidateBranches(rootDir, activeBranch, history) {
13887
+ function addDefaultGitBranches(rootDir, branchSet) {
13888
+ for (const def of ["main", "master"]) {
13889
+ try {
13890
+ child_process.execFileSync("git", ["rev-parse", "--verify", "--quiet", def], {
13891
+ cwd: rootDir,
13892
+ stdio: ["pipe", "pipe", "pipe"]
13893
+ });
13894
+ branchSet.add(def);
13895
+ } catch {
13896
+ }
13897
+ }
13898
+ }
13899
+ function addCommitTrailerBranches(allRepoCommits, branchSet) {
13900
+ if (!allRepoCommits) return;
13901
+ for (const c of allRepoCommits) {
13902
+ const pRef = c.trailers?.parentRef;
13903
+ if (pRef && /^(feat|bug|task|release)\//i.test(pRef)) {
13904
+ branchSet.add(pRef);
13905
+ }
13906
+ }
13907
+ }
13908
+ function resolveCandidateBranches(rootDir, activeBranch, history, allRepoCommits) {
13551
13909
  const branchSet = /* @__PURE__ */ new Set();
13552
13910
  if (activeBranch && activeBranch !== "HEAD") {
13553
13911
  branchSet.add(activeBranch);
@@ -13557,14 +13915,38 @@ function resolveCandidateBranches(rootDir, activeBranch, history) {
13557
13915
  }
13558
13916
  for (const b of collectGitUnmergedBranches(rootDir)) branchSet.add(b);
13559
13917
  for (const b of collectGitPrefixedBranches(rootDir)) branchSet.add(b);
13918
+ addDefaultGitBranches(rootDir, branchSet);
13919
+ addCommitTrailerBranches(allRepoCommits, branchSet);
13560
13920
  return Array.from(branchSet);
13561
13921
  }
13562
- function fetchBranchKpi(rootDir, branch) {
13922
+ function fetchDefaultBranchKpi(rootDir, branch, allRepoCommits) {
13923
+ if (allRepoCommits && allRepoCommits.length > 0) {
13924
+ return aggregateCommitKpiRecords(allRepoCommits, branch, branch);
13925
+ }
13926
+ const base = resolveDefaultBranchBase(rootDir, branch);
13927
+ const kpi = aggregatePrKpis(base, branch, { cwd: rootDir });
13928
+ return kpi && kpi.totalCommits > 0 ? kpi : null;
13929
+ }
13930
+ function isCommitMatchingBranch(c, branch, branchBase) {
13931
+ const pRef = (c.trailers?.parentRef || "").toLowerCase();
13932
+ const bLower = branch.toLowerCase();
13933
+ const baseLower = branchBase.toLowerCase();
13934
+ return pRef === bLower || pRef === baseLower || pRef.length > 0 && bLower.includes(pRef) || c.subject.toLowerCase().includes("(" + baseLower + ")");
13935
+ }
13936
+ function fetchMergedBranchKpi(branch, allRepoCommits) {
13937
+ if (!allRepoCommits || allRepoCommits.length === 0) return null;
13938
+ const branchBase = branch.replace(/^(feat|bug|task|release)\//i, "");
13939
+ const matched = allRepoCommits.filter((c) => isCommitMatchingBranch(c, branch, branchBase));
13940
+ return matched.length > 0 ? aggregateCommitKpiRecords(matched, "main", branch) : null;
13941
+ }
13942
+ function fetchBranchKpi(rootDir, branch, allRepoCommits) {
13563
13943
  try {
13564
- const isDefault = branch === "main" || branch === "master";
13565
- const base = isDefault ? resolveDefaultBranchBase(rootDir, branch) : "main";
13566
- const kpi = aggregatePrKpis(base, branch, { cwd: rootDir });
13567
- return kpi && kpi.totalCommits > 0 ? kpi : null;
13944
+ if (branch === "main" || branch === "master") {
13945
+ return fetchDefaultBranchKpi(rootDir, branch, allRepoCommits);
13946
+ }
13947
+ const kpi = aggregatePrKpis("main", branch, { cwd: rootDir });
13948
+ if (kpi && kpi.totalCommits > 0) return kpi;
13949
+ return fetchMergedBranchKpi(branch, allRepoCommits);
13568
13950
  } catch {
13569
13951
  return null;
13570
13952
  }
@@ -13573,10 +13955,10 @@ function recordBranchKpi(telemetries, commitMap, branch, kpi) {
13573
13955
  telemetries[branch] = kpi;
13574
13956
  for (const rec of kpi.commitRecords || []) commitMap.set(rec.sha, rec);
13575
13957
  }
13576
- function populateCandidateTelemetries(rootDir, candidateBranches, telemetries, commitMap) {
13958
+ function populateCandidateTelemetries(rootDir, candidateBranches, telemetries, commitMap, allRepoCommits) {
13577
13959
  for (const branch of candidateBranches) {
13578
13960
  if (telemetries[branch]) continue;
13579
- const kpi = fetchBranchKpi(rootDir, branch);
13961
+ const kpi = fetchBranchKpi(rootDir, branch, allRepoCommits);
13580
13962
  if (kpi) recordBranchKpi(telemetries, commitMap, branch, kpi);
13581
13963
  }
13582
13964
  }
@@ -13589,11 +13971,15 @@ function computeConsolidatedTelemetry(uniqueCommits, fallback) {
13589
13971
  function collectAllBranchTelemetries(rootDir, activeBranch, history, activePrKpi) {
13590
13972
  const branchTelemetries = {};
13591
13973
  const uniqueCommits = /* @__PURE__ */ new Map();
13974
+ const allRepoCommits = extractAllRepoCommitKpis({ cwd: rootDir });
13975
+ for (const c of allRepoCommits) {
13976
+ uniqueCommits.set(c.sha, c);
13977
+ }
13592
13978
  if (activePrKpi && activeBranch && activeBranch !== "HEAD") {
13593
13979
  recordBranchKpi(branchTelemetries, uniqueCommits, activeBranch, activePrKpi);
13594
13980
  }
13595
- const candidateBranches = resolveCandidateBranches(rootDir, activeBranch, history);
13596
- populateCandidateTelemetries(rootDir, candidateBranches, branchTelemetries, uniqueCommits);
13981
+ const candidateBranches = resolveCandidateBranches(rootDir, activeBranch, history, allRepoCommits);
13982
+ populateCandidateTelemetries(rootDir, candidateBranches, branchTelemetries, uniqueCommits, allRepoCommits);
13597
13983
  const totalTelemetry = computeConsolidatedTelemetry(Array.from(uniqueCommits.values()), activePrKpi);
13598
13984
  return { branchTelemetries, totalTelemetry };
13599
13985
  }
@@ -13844,9 +14230,10 @@ var SPECIALIZED_AGENT_TEMPLATES = [
13844
14230
 
13845
14231
  ## Phase 0: Greenfield Product Inception (New Product Intent)
13846
14232
  - **Trigger**: When the user expresses intent to create a new product from scratch with the framework (or when \`specs/product/\` has no baseline product model yet), initiate **Phase 0** before any SDD change (\`change:new\`) or implementation:
13847
- 1. **Structured Discovery Interview (3\u20135 Questions)**: Ask a concise 3\u20135 question interview to clarify: (a) core problem and mission statement, (b) primary actors/stakeholders (\`ACT-*\`), (c) essential MVP capabilities/use cases (\`UC-*\`), and (d) top 3\u20135 priority quality goals and constraints (\`QR-*\`, \`CON-*\`).
13848
- 2. **Enterprise & Capability Vision (\`ARCH-INTRO-001\`)**: Draft the root vision artifact (\`type: architecture-introduction\`, \`naf-perspective: "Enterprise & Capability"\`, \`status: draft\`) using \`templates/architecture/introduction-and-goals.template.md\` (\`schemas/architecture/introduction-and-goals.schema.json\`).
14233
+ 1. **Iterative Discovery Interview (Up to 15 Questions or Until Product is Crystal Clear)**: Conduct an iterative discovery interview (up to 15 questions, grouped logically in conversational rounds until zero product ambiguities remain) before drafting specs, clarifying: (a) core problem and mission statement, (b) primary actors/stakeholders (\`ACT-*\`), authentication/role model, and **target user interface modality** (e.g., Web UI, Desktop GUI, Console/TUI/CLI, Mobile app, or headless API/SDK), (c) foundational master entities/catalogs and CRUD flows required to operate the system, (d) essential MVP capabilities/use cases (\`UC-*\`) and business rules/invariants (\`BR-*\`) vs. future roadmap, and (e) top 3\u20135 priority quality goals and constraints (\`QR-*\`, \`CON-*\`). Do not proceed to draft artifacts until the product scope is completely clear.
14234
+ 2. **Enterprise & Capability Vision (\`ARCH-INTRO-001\`)**: Draft the root vision artifact (\`type: architecture-introduction\`, \`naf-perspective: "Enterprise & Capability"\`, \`status: draft\`) using \`templates/architecture/introduction-and-goals.template.md\` (\`schemas/architecture/introduction-and-goals.schema.json\`), explicitly recording the agreed UI/interaction modality.
13849
14235
  3. **ProductShape Derivation**: Derive the initial draft artifacts (\`ACT-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, \`QR-*\` with \`status: draft\`) in \`specs/product/\` linked to \`ARCH-INTRO-001\` for human Product Owner review.
14236
+ 4. **Mandatory End-to-End Presentation Interface & Master Data Prerequisite Rule (ANTI-LIBRARY-ONLY MVP)**: Whenever primary actors (\`ACT-*\`) are human users, the MVP ProductShape baseline MUST include: (a) an explicit presentation/interaction requirement (\`FR-*\`) or vertical UI/CLI acceptance criteria matching the modality agreed in Step 1 (Web UI, Desktop GUI, or Console/TUI/CLI \u2014 never proposing a library-only/in-memory MVP without a runnable entry point), (b) user authentication/session access when multi-role actors exist, and (c) CRUD/configuration flows for foundational master entities (e.g., rooms, staff, students, catalogs) required to operate the core business flows without manual database intervention.
13850
14237
 
13851
14238
  ## Operational Directives & Guardrails
13852
14239
  - Every generated artifact must strictly adhere to the canonical Markdown and YAML frontmatter format in \`schemas/product/\` and \`schemas/architecture/introduction-and-goals.schema.json\`.
@@ -13923,6 +14310,7 @@ var SPECIALIZED_AGENT_TEMPLATES = [
13923
14310
  - Decompose the system into building blocks \`CMP-*\` ensuring each component declares which use cases \`UC-*\` it implements and which requirements (\`FR-*\`, \`QR-*\`, \`SEC-REQ-*\`, \`PRIV-REQ-*\`) it fulfills under \`satisfies-requirements\`.
13924
14311
  - **Modular & Hexagonal Architecture (Ports & Adapters)**: Structure building blocks (\`CMP-*\`, Level 2/3 of arc42) around Bounded Contexts (\`BC-*\`) and Vertical Slices (\`UC-*\`) following Hexagonal Architecture (Ports & Adapters). Separate the pure Domain/Application Core from Inbound/Driving Ports (API, CLI, UI handlers) and Outbound/Driven Ports (persistence, queues, external SDKs/LLMs), enforcing the Dependency Rule (dependencies point strictly inward toward the Core; avoid speculative empty layers per YAGNI and respect existing \`ADR-*\` architecture in brownfield repos).
13925
14312
  - **Contract-First Full-Stack Integration**: Whenever a feature or change spans Frontend (UI) and Backend (API/services), define an explicit shared typed contract (Zod schemas, shared TypeScript DTOs, or OpenAPI specification) in \`design.md\` before implementation so both layers compile against a single source of truth.
14313
+ - **No Orphan Presentation Components (\`CMP-WEB-*\` / \`CMP-UI-*\` / \`CMP-CLI-*\`)**: When modeling architecture for a system with human actors (\`ACT-*\`), never leave the agreed presentation/driving adapter (Web UI, Desktop GUI, or Console/CLI) as an unmapped \`proposed\` spec while scheduling only backend class-library tasks in \`tasks.md\`. Wave 0 (\`CHG-001\`) MUST bootstrap the runnable presentation host shell matching the modality defined in Inception, and every subsequent \`CHG-*\` for a human-facing \`UC-*\` must include tasks (\`TSK-*\`) implementing its corresponding views/screens/commands and E2E tests as a complete vertical slice.
13926
14314
  - Generate interaction and sequence diagrams in native Mermaid syntax.
13927
14315
  - Document critical technological decisions using immutable \`ADR-*\` records conforming to \`schemas/architecture/adr.schema.json\`.
13928
14316
  - Validate that architectural choices comply with legal constraints in \`license-policy.yaml\` and data protection constraints in \`privacy-policy.yaml\`.
@@ -14048,6 +14436,7 @@ Execute every implementation task following this strict sequential order:
14048
14436
  ## Operational Directives & Guardrails
14049
14437
  - Operate under bimodal discipline depending on the lifecycle phase:
14050
14438
  1. **Design Mode (Upstream)**: Adopt the primary actor persona under real-world field conditions (stress, latency, constrained viewports). Separate strict Minimum Viable Product (MVP) core from future roadmap ideas using \`templates/product/user-design-feedback.template.md\`.
14439
+ - **FORBIDDEN Library-Only MVP for Human Actors**: Whenever primary actors (\`ACT-*\`) are human users, verify that the target interaction modality (Web UI, Desktop GUI, Console/TUI/CLI, or Mobile) was explicitly defined in \`ARCH-INTRO-*\` / \`specs/product/\`, and reject as \`[BLOCKING_DEFECT]\` any MVP proposal that defers the agreed presentation layer, role authentication (when applicable), or foundational master-entity CRUDs (e.g., creating rooms, teachers, students, schedules) to post-MVP or leaves the system operable only via unit tests/in-memory calls. An MVP for human operators must be end-to-end usable from day one via its agreed interface.
14051
14440
  2. **Functional Validation Mode (Downstream / Pre-PR / Post-Development Functional Validation)**: Inspect \`agent-developer\` deliverables once unit tests pass green by executing the real application (via Playwright or Chrome DevTools MCP when UI is present). Contrast actual UI, CLI, and API behavior against approved \`UC-*\` and \`FR-*\` criteria, verifying real Backend connectivity, the 4 UI usability states (\`Loading\`, \`Empty\`, \`Error\`, \`Nominal\`), keyboard/ARIA accessibility, and \`0\` browser \`console.error\` / network failures.
14052
14441
  - Formulate decisive questions under \`open-questions\` for the human Product Owner.
14053
14442
  - Emit handoff block suggesting the Pre-Merge Audit Triad (\`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-privacy-officer\`, \`agent-compliance-checker\`) if compliant, or return to \`agent-developer\` on functional drift or fake-wiring.`
@@ -14091,6 +14480,52 @@ Execute every implementation task following this strict sequential order:
14091
14480
  - **Cross-Workflow Audit**: When fixing any CI/CD or configuration defect detected in a PR, search all \`.github/workflows/*.yml\` for the same pattern (including release, post-merge, and publishing pipelines) before declaring the fix complete.
14092
14481
  - **Remote Verification**: Creating a PR (\`gh pr create\`) does not equal success; actively verify that remote checks pass (\`gh pr checks\`).
14093
14482
  - If autonomy is $\\ge$ \`HUMAN_REVIEW_PLAN\`, conclude by emitting the Workflow Handoff block (\`templates/workflow/agent-handoff.template.md\`) to the human Tech Lead or Release Manager, opening the Human Action Window. In \`AUTONOMOUS\` mode, omit interactive handoff.`
14483
+ },
14484
+ {
14485
+ id: "agent-auditor",
14486
+ title: "Transversal Quality and Improvement Auditor",
14487
+ description: "Polymorphically inspect deliverables from any AI-SDLC specialist agent on demand, identifying structural weaknesses, overengineering, or blind spots, and proposing concrete, minimal solutions adhering strictly to YAGNI.",
14488
+ globs: "**/*",
14489
+ claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
14490
+ antigravityTools: ["read_file", "run_command", "call_mcp_tool", "ask_question"],
14491
+ body: `## Role & Mission
14492
+ - **Role**: Transversal Quality and Constructive Auditor Agent (\`agent-auditor\`).
14493
+ - **Mission**: Inspect the output deliverables of any upstream specialist agent upon demand across any phase, identifying structural weaknesses, premature abstractions, overengineering, or blind spots, and proposing concrete, minimal, and standard solutions adhering strictly to Simplicity First (YAGNI).
14494
+
14495
+ ## Operational Directives & Guardrails
14496
+ - **Polymorphic On-Demand Scope**: May be invoked over deliverables from any role (\`agent-product-analyst\`, \`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-qa-engineer\`, \`agent-developer\`, \`agent-devops\`).
14497
+ - **Simplicity First (YAGNI)**: Actively challenge speculative parameters, redundant interfaces, unused design patterns, and unrequested flexibility.
14498
+ - **End-to-End MVP Completeness Check (Anti-Library-Only Drift)**: When auditing Product (\`specs/product/\`), Architecture (\`specs/architecture/\`), or SDD change plans (\`design.md\`, \`tasks.md\`) involving human actors (\`ACT-*\`), flag as \`[BLOCKING_DEFECT]\` any scope cut that fails to define the target user interface modality at Inception or omits the runnable driving adapter (Web UI, Desktop GUI, or Console/CLI), role access/auth (when applicable), or master-data CRUD flows required to operate the use case end-to-end without manual database manipulation.
14499
+ - **Classification of Findings**: Label every finding as:
14500
+ * \`[BLOCKING_DEFECT]\`: Critical omission, structural debt, or standard violation that must be resolved.
14501
+ * \`[SIMPLIFICATION]\`: Opportunity to remove unneeded complexity or reduce code/spec surface without loss of function.
14502
+ * \`[ADVISORY]\`: Non-blocking observation or suggestion.
14503
+ - **NON-INVASIVE GUARDRAIL**: You do NOT modify upstream files or specifications directly.
14504
+ - **Mandatory Return Handoff**: Emit a structured report citing canonical IDs and SHA-256 digests, concluding with the canonical Workflow Handoff block (\`templates/workflow/agent-handoff.template.md\`) directed back to the audited specialist agent.
14505
+ - **ANTI-PING-PONG GUARDRAIL**: Enforce maximum 1 audit return round per increment unless blocking defects persist.`
14506
+ },
14507
+ {
14508
+ id: "agent-adversary",
14509
+ title: "Transversal Red Team and Chaos Adversary",
14510
+ description: "Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps for every discovered failure mode.",
14511
+ globs: "**/*",
14512
+ claudeTools: ["View", "GlobTool", "GrepTool", "LS", "Bash"],
14513
+ antigravityTools: ["read_file", "run_command", "call_mcp_tool", "ask_question"],
14514
+ body: `## Role & Mission
14515
+ - **Role**: Transversal Red Team and Stress Adversary Agent (\`agent-adversary\`).
14516
+ - **Mission**: Actively attempt to break, bypass, or invalidate the deliverables of any target specialist agent across any phase, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps for every discovered failure mode.
14517
+
14518
+ ## Operational Directives & Guardrails
14519
+ - **Polymorphic On-Demand Scope**:
14520
+ * **Product**: Uncover contradictory requirements, unreachable business states, and logic traps.
14521
+ * **Architecture**: Simulate race conditions, cascading failures, resource exhaustion, and single points of failure (SPOFs).
14522
+ * **QA**: Perform conceptual mutation testing; demonstrate how flawed or empty implementations could falsely pass tests green.
14523
+ * **Development**: Attack boundary inputs, concurrency race triggers, and memory/type edge breaks.
14524
+ * **DevOps**: Probe pipeline isolation, credential boundaries, and cold-start/dependency outages.
14525
+ - **MANDATORY PROOF-OF-BREAK**: Abstract criticism without reproducible proof is strictly forbidden. Every finding must include: (1) Target Entity ID, (2) Failure Scenario / Attack Vector, (3) Concrete PoC (input vector, sequence breakdown, or mutant code), and (4) Expected Impact.
14526
+ - **NON-INVASIVE GUARDRAIL**: You do NOT patch the vulnerabilities or bugs yourself.
14527
+ - **Mandatory Return Handoff**: Emit the canonical Workflow Handoff block (\`templates/workflow/agent-handoff.template.md\`) addressing the audited agent, demanding verified mitigation before downstream promotion.
14528
+ - **ANTI-PING-PONG GUARDRAIL**: Enforce maximum 1 adversarial return round per increment.`
14094
14529
  }
14095
14530
  ];
14096
14531
  function renderAntigravityAgentFile(agent) {
@@ -14160,12 +14595,20 @@ var LIFECYCLE_SKILL_TEMPLATES = [
14160
14595
  {
14161
14596
  id: "aisdlc-greenfield",
14162
14597
  title: "Greenfield Project Inception & Delivery Playbook",
14163
- description: "Orchestrate end-to-end AI-SDLC onboarding and Phase 0 Inception for brand-new (Greenfield) projects, from repository initialization (aisdlc init) and NAF v4 Vision (ARCH-INTRO-*) through ProductShape, STRIDE Threat Modeling, arc42 Architecture, and initial SDD increment delivery.",
14598
+ description: "Orchestrate end-to-end AI-SDLC onboarding and Phase 0 Inception for brand-new (Greenfield) projects, from repository initialization (aisdlc init) and NAF v4 Vision (ARCH-INTRO-*) through ProductShape, STRIDE Threat Modeling, arc42 Architecture, transversal auditor/adversary verification loops, and initial SDD increment delivery.",
14164
14599
  references: "[`process/02_product_definition.md`](../../process/02_product_definition.md), [`process/04b_data_protection_and_privacy.md`](../../process/04b_data_protection_and_privacy.md), [`process/05_architecture_arc42_nafv4.md`](../../process/05_architecture_arc42_nafv4.md), [`process/06_spec_driven_development.md`](../../process/06_spec_driven_development.md), and [`process/09_agent_protocols.md`](../../process/09_agent_protocols.md).",
14165
14600
  globs: "product/**, specs/product/**, architecture/**, templates/**",
14166
14601
  body: `## Purpose & Trigger
14167
14602
  Use this skill when starting a **brand-new software project from scratch (Greenfield)** or when \`specs/product/\` has no canonical baseline yet. It coordinates the sequential execution of AI-SDLC MCP/CLI tools and specialized role agents so no code is written before product vision, security enclaves, privacy-by-design controls, and architecture contracts exist.
14168
14603
 
14604
+ ## Mandatory Transversal Quality & Adversarial Protocol
14605
+ Every authoring agent deliverable across Phase 0 and Inception undergoes mandatory quality auditing and adversarial stress-testing before downstream progression:
14606
+ - **Concurrent Inspection**: Immediately following the execution of any authoring agent (\`agent-product-analyst\`, \`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`), invoke [\`agent-auditor\`](../agent-auditor/SKILL.md) (evaluating YAGNI, structural debt, and simplification) and [\`agent-adversary\`](../agent-adversary/SKILL.md) (stress-testing logic traps, SPOFs, attack vectors, or broken invariants) **concurrently** in clean, isolated context windows.
14607
+ - **Non-Invasive Review**: Neither auditor nor adversary modifies deliverables directly; both deliver structured reports citing canonical IDs and SHA-256 digests.
14608
+ - **Consolidated Remediation Re-Execution**: Consolidate findings and emit the Workflow Handoff back to the authoring agent, who is re-executed to resolve blocking defects and apply simplifications.
14609
+ - **Anti-Ping-Pong Guardrail (Max 2 Rounds)**: Bounded strictly to a maximum of **2 correction rounds** per phase/deliverable. If non-blocking advisories remain after round 2, proceed to the downstream phase; if blocking defects persist after round 2, escalate immediately to the Human Tech Lead.
14610
+ - **Exclusion of Downstream Review & Validation Roles**: Review and validation agents (\`agent-expert-user\`, \`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-compliance-checker\`) evaluate finished deliverables and are excluded from being audited by this loop.
14611
+
14169
14612
  ## End-to-End Execution Playbook
14170
14613
 
14171
14614
  ### Step 1: Repository Turnkey Initialization
@@ -14175,16 +14618,21 @@ Use this skill when starting a **brand-new software project from scratch (Greenf
14175
14618
 
14176
14619
  ### Step 2: Phase 0 Product Inception (\`agent-product-analyst\`)
14177
14620
  1. Delegate to or adopt [\`agent-product-analyst\`](../agent-product-analyst/SKILL.md).
14178
- 2. **Discovery Interview (3\u20135 Questions)**: Before generating artifacts, clarify with the human Product Owner:
14621
+ 2. **Iterative Discovery Interview (Up to 15 Questions or Until Product Scope is 100% Clear)**: Before generating artifacts, clarify with the human Product Owner in rounds of 3\u20135 questions (up to **15 questions maximum**, stopping earlier as soon as the product is clear):
14179
14622
  - Core mission statement and business problem.
14180
14623
  - Primary actors (\`ACT-*\`) and external systems.
14181
- - Essential MVP capabilities (\`UC-*\`) vs. future roadmap.
14624
+ - **Target Interaction & Presentation Modality (\`CON-*\` / \`ARCH-INTRO-001\`)**: Explicitly define at inception how human actors will interact with the MVP (e.g., **Web UI**, **Desktop GUI**, **Interactive Console/TUI/CLI**, **Mobile App**, or **Headless API/SDK** if actors are exclusively external systems). Never assume a headless C#/TS class library when human actors exist.
14625
+ - Essential MVP capabilities (\`UC-*\`) vs. future roadmap, ensuring **foundational entity CRUD / master data workflows** (creating/managing core domain entities before executing transactions on them) are explicitly included in the MVP.
14182
14626
  - Top 3\u20135 quality goals (\`QR-*\`) and regulatory/technical constraints (\`CON-*\`).
14183
- 3. **Enterprise & Capability Vision**: Create \`specs/architecture/ARCH-INTRO-001.md\` (\`status: draft\`, \`naf-perspective: "Enterprise & Capability"\`) using \`templates/architecture/introduction-and-goals.template.md\`.
14627
+ 3. **Enterprise & Capability Vision**: Create \`specs/architecture/ARCH-INTRO-001.md\` (\`status: draft\`, \`naf-perspective: "Enterprise & Capability"\`) using \`templates/architecture/introduction-and-goals.template.md\`, explicitly recording the chosen presentation/UI modality.
14184
14628
  4. **ProductShape Baseline**: Derive initial draft artifacts in \`specs/product/\`:
14185
14629
  - Actors (\`ACT-*\`), Use Cases (\`UC-*\`), Business Rules (\`BR-*\`), Functional Requirements (\`FR-*\` with mandatory \`@nominal\`, \`@boundary\`, \`@invalid\` Gherkin blocks), and Quality Requirements (\`QR-*\`).
14630
+ - **Vertical Slice Completeness Rule**: Every human-triggered \`UC-*\` in the MVP must specify observable user interaction through the agreed presentation modality (Web screens/forms, Desktop views, or Console commands/menus) and state persistence\u2014never stop at internal library/service method calls.
14186
14631
  5. Validate schemas and duplicates via MCP tools \`verify_schemas\` and \`verify_duplicates\` (or \`npx aisdlc check --fix\`).
14187
- 6. **Mandatory Upstream UX & MVP Boundary Gate (\`agent-expert-user\`)**: Invoke [\`agent-expert-user\`](../agent-expert-user/SKILL.md) in **Design Mode** to stress-test the proposed workflows, enforce strict MVP boundaries, and separate core MVP \`UC-*\` from future roadmap backlog (\`templates/product/user-design-feedback.template.md\`).
14632
+ 6. **Mandatory Upstream UX & MVP Boundary Gate (\`agent-expert-user\`)**: Invoke [\`agent-expert-user\`](../agent-expert-user/SKILL.md) in **Design Mode** to stress-test the proposed workflows, enforce strict MVP boundaries, reject any headless/library-only MVP when human actors exist, verify master-data CRUD prerequisites, and separate core MVP \`UC-*\` from future roadmap backlog (\`templates/product/user-design-feedback.template.md\`).
14633
+ 7. **Transversal Quality & Adversarial Loop (\`agent-product-analyst\`)**:
14634
+ - Concurrently invoke \`agent-auditor\` and \`agent-adversary\` on the draft product artifacts in isolated context windows.
14635
+ - Consolidate findings and hand off back to \`agent-product-analyst\` to re-execute and remediate issues (max 2 correction rounds).
14188
14636
 
14189
14637
  ### Step 3: Shift-Left Cybersecurity & Privacy-by-Design (\`agent-threat-modeler\` \u2794 \`agent-privacy-officer\`)
14190
14638
  1. Delegate to or adopt [\`agent-threat-modeler\`](../agent-threat-modeler/SKILL.md).
@@ -14192,25 +14640,36 @@ Use this skill when starting a **brand-new software project from scratch (Greenf
14192
14640
  - Threat Actors (\`ACT-THREAT-*\`)
14193
14641
  - Abuse Cases (\`ABUSE-*\` targeting \`UC-*\`)
14194
14642
  - Security Requirements (\`SEC-REQ-*\` with \`@security @mitigation\` negative Gherkin scenarios and \`SEC-ENC-*\` Zero Trust enclave bindings).
14195
- 3. Hand off to [\`agent-privacy-officer\`](../agent-privacy-officer/SKILL.md) to apply LINDDUN and GDPR/LOPDGDD/ISO 27701 in \`specs/privacy/\`:
14643
+ 3. **Transversal Quality & Adversarial Loop (\`agent-threat-modeler\`)**:
14644
+ - Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over the security threat models.
14645
+ - Consolidate findings and return handoff to \`agent-threat-modeler\` to re-execute and remediate (max 2 correction rounds).
14646
+ 4. Hand off to [\`agent-privacy-officer\`](../agent-privacy-officer/SKILL.md) to apply LINDDUN and GDPR/LOPDGDD/ISO 27701 in \`specs/privacy/\`:
14196
14647
  - Personal Data Assets (\`DATA-ASSET-*\`), GDPR Art. 30 Records of Processing (\`PRIV-ROPA-*\`), and Privacy Requirements (\`PRIV-REQ-*\` with \`@privacy @gdpr\` Gherkin scenarios).
14197
- 4. Run \`verify_schemas\` and \`verify_privacy\` (\`npx aisdlc verify privacy\`).
14648
+ 5. **Transversal Quality & Adversarial Loop (\`agent-privacy-officer\`)**:
14649
+ - Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over the privacy records and requirements.
14650
+ - Consolidate findings and return handoff to \`agent-privacy-officer\` to re-execute and remediate (max 2 correction rounds).
14651
+ 6. Run \`verify_schemas\` and \`verify_privacy\` (\`npx aisdlc verify privacy\`).
14198
14652
 
14199
14653
  ### Step 4: Modular Systems Architecture (\`agent-system-architect\`)
14200
14654
  1. Delegate to or adopt [\`agent-system-architect\`](../agent-system-architect/SKILL.md).
14201
14655
  2. Define building blocks (\`CMP-*\`) and Architectural Decision Records (\`ADR-*\`) in \`specs/architecture/\` using \`templates/architecture/\`, ensuring every \`CMP-*\` cites \`implements-use-cases\` (\`UC-*\`) and \`satisfies-requirements\` (\`FR-*\`, \`QR-*\`, \`SEC-REQ-*\`, \`PRIV-REQ-*\`).
14202
14656
  3. Inspect third-party stack choices against \`license-policy.yaml\` via \`verify_licenses\` and subprocessors against \`privacy-policy.yaml\` via \`verify_privacy\`.
14203
14657
  4. **Technical Security & Privacy Feedback Loop**: If new infrastructure, persistence, LLM, or auth decisions introduce attack vectors or PII flows, return to \`agent-threat-modeler\` \u2794 \`agent-privacy-officer\` to add technical \`SEC-REQ-*\` and \`PRIV-REQ-*\` mitigations before coding.
14658
+ 5. **Transversal Quality & Adversarial Loop (\`agent-system-architect\`)**:
14659
+ - Concurrently invoke \`agent-auditor\` (evaluating YAGNI, architecture bloat, Ports & Adapters interfaces) and \`agent-adversary\` (simulating SPOFs, race conditions, cascading outages) in isolated context windows.
14660
+ - Consolidate findings and return handoff to \`agent-system-architect\` to re-execute and remediate (max 2 correction rounds).
14204
14661
 
14205
14662
  ### Step 5: Release Milestone & Topological Wave SDD Plan (\`1 UC-* = 1 CHG-*\`)
14206
14663
  1. **Open Release Milestone (\`Tier 2: release/v1.0.0\`)**: Group the approved MVP Use Cases (\`UC-001\`, \`UC-002\`, ...) under the initial release milestone (\`release/v1.0.0\`) and visualize the branch hierarchy via \`npx aisdlc git plan\`.
14207
14664
  2. **Decompose into Topological Waves (DAG Parallelism)**:
14208
- - **Wave 0 \u2014 Foundational Core (Sequential)**: Identify the foundational \`UC-*\` (core domain entities, shared contracts, auth/config) and deliver it first as \`CHG-001\` via [\`aisdlc-increment\`](../aisdlc-increment/SKILL.md) so downstream agents share locked interfaces.
14209
- - **Waves 1..N \u2014 Orthogonal Capabilities (Parallel Multi-Agent)**: Once Wave 0 contracts are merged into \`release/v1.0.0\`, scaffold independent \`CHG-*\` increments (\`1 UC-* = 1 CHG-*\`) and execute them **in parallel** across isolated branches/worktrees (\`feat/CHG-002\`, \`feat/CHG-003\`, ...) whenever they target distinct components (\`CMP-*\`) or bounded contexts (\`BC-*\`).
14665
+ - **Wave 0 \u2014 Foundational Core & Executable Presentation Host (Sequential)**: Identify the foundational \`UC-*\` (core domain entities, shared contracts, auth/config, **plus the runnable application host/shell for the agreed UI modality**\u2014e.g., Web server + layout, Desktop shell, or CLI entrypoint + DB bootstrap) and deliver it first as \`CHG-001\` via [\`aisdlc-increment\`](../aisdlc-increment/SKILL.md) so the product is immediately executable and downstream agents share locked interfaces.
14666
+ - **Waves 1..N \u2014 Orthogonal End-to-End Vertical Slices (Parallel Multi-Agent)**: Once Wave 0 contracts and host shell are merged into \`release/v1.0.0\`, scaffold independent \`CHG-*\` increments (\`1 UC-* = 1 CHG-*\`) and execute them **in parallel** across isolated branches/worktrees (\`feat/CHG-002\`, \`feat/CHG-003\`, ...) whenever they target distinct components (\`CMP-*\`) or bounded contexts (\`BC-*\`). Every \`CHG-*\` implementing a human \`UC-*\` must deliver its complete vertical slice (Domain + Persistence + UI/CLI presentation view/command + E2E test).
14210
14667
  3. **Release Consolidation (\`release/v1.0.0\` \u2794 \`main\`)**: Once all MVP \`CHG-*\` increments are integrated (\`sdd_integrate\`), run \`verify\` (\`npx aisdlc verify all\`), generate SBOM (\`npx aisdlc verify licenses --sbom reports/sbom.cdx.json --notices THIRD_PARTY_NOTICES.md\`), compute release KPIs (\`kpi_release\`), and open the Release PR into \`main\` for human Product Owner & Release Manager sign-off.
14211
14668
 
14212
14669
  ## Non-Negotiable Guardrails
14213
14670
  - **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles in the same conversation context window. In subagent-capable IDEs (Antigravity \`invoke_subagent\`, Claude Code \`Task\` / \`.claude/agents/\`, GitHub Copilot \`@agent-*\`), always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk (\`specs/\`, \`handoff.yaml\`, \`get_active_handoff\`). In chat-based IDEs (Cursor, Windsurf, Aider), persist all artifacts to disk, emit the Workflow Handoff block, and instruct the user to open a **New Chat** (or \`/clear\`) before running the next specialist.
14671
+ - **Mandatory Transversal Quality & Adversarial Loop**: Every authoring agent deliverable must undergo concurrent inspection by \`agent-auditor\` and \`agent-adversary\` in isolated context windows, followed by a re-execution of the authoring agent to remediate findings. To prevent infinite cycles, enforce the **Anti-Ping-Pong Guardrail**: maximum 2 correction rounds per phase; if unresolved blocking defects persist after round 2, escalate to the Human Tech Lead.
14672
+ - **FORBIDDEN Library-Only MVP for Human-Facing Products**: Whenever a product defines human actors (\`ACT-*\`), no agent may scope the MVP (\`release/v1.0.0\`) as headless class libraries or in-memory-only modules without an executable presentation host. The target interaction modality (Web UI, Desktop GUI, Console/TUI/CLI, or Mobile) must be explicitly agreed with the user during Phase 0 Inception and delivered as a runnable end-to-end application across the MVP waves.
14214
14673
  - **FORBIDDEN Greenfield Monolith (\`1 UC-* = 1 CHG-*\`)**: Never bundle the entire product or multiple \`UC-*\` into a single SDD change (\`CHG-001\`). Deterministic Gate 3 (\`verify_governance\`) blocks any \`handoff.yaml\` containing $> 1$ Use Case (\`Greenfield monolith detected\`). Parallelism is achieved by running **multiple bounded \`CHG-*\` concurrently** on separate branches/worktrees, never by stuffing multiple \`UC-*\` into one \`CHG-*\`.
14215
14674
  - Never invoke \`sdd_change_new\` or write application code in \`src/\` on a Greenfield project before \`ARCH-INTRO-001\`, \`agent-expert-user\` MVP validation, and at least one \`UC-*\` and \`FR-*\` exist.
14216
14675
  - All newly drafted specifications must start with \`status: draft\`.
@@ -14219,12 +14678,20 @@ Use this skill when starting a **brand-new software project from scratch (Greenf
14219
14678
  {
14220
14679
  id: "aisdlc-legacy-onboarding",
14221
14680
  title: "Legacy / Brownfield Retro-Inception Playbook",
14222
- description: "Orchestrate progressive AI-SDLC adoption and Brownfield retro-inception on existing or legacy repositories without breaking production code, reverse-engineering architecture (ARCH-INTRO-*, CMP-*) and establishing baseline quality, security, and license audits before new SDD increments.",
14681
+ description: "Orchestrate progressive AI-SDLC adoption and Brownfield retro-inception on existing or legacy repositories without breaking production code, reverse-engineering architecture (ARCH-INTRO-*, CMP-*), transversal auditor/adversary verification loops, and establishing baseline quality, security, and license audits before new SDD increments.",
14223
14682
  references: "[`process/02_product_definition.md`](../../process/02_product_definition.md), [`process/04_open_source_license_compliance.md`](../../process/04_open_source_license_compliance.md), [`process/04b_data_protection_and_privacy.md`](../../process/04b_data_protection_and_privacy.md), [`process/05_architecture_arc42_nafv4.md`](../../process/05_architecture_arc42_nafv4.md), [`process/10_quality_management_and_release_gates.md`](../../process/10_quality_management_and_release_gates.md), and [`process/09_agent_protocols.md`](../../process/09_agent_protocols.md).",
14224
14683
  globs: "architecture/**, specs/**, src/**, packages/**",
14225
14684
  body: `## Purpose & Trigger
14226
14685
  Use this skill when **adopting AI-SDLC in an existing or legacy codebase (Brownfield)** that already has production source code (\`src/\`, \`packages/\`, etc.) but lacks canonical PDaC specifications, arc42 architecture views, or deterministic quality/license/privacy gates.
14227
14686
 
14687
+ ## Mandatory Transversal Quality & Adversarial Protocol
14688
+ Every authoring agent deliverable during Brownfield retro-inception undergoes mandatory quality auditing and adversarial stress-testing before downstream progression:
14689
+ - **Concurrent Inspection**: Immediately following the execution of any authoring agent (\`agent-product-analyst\`, \`agent-system-architect\`, \`agent-threat-modeler\`, \`agent-privacy-officer\`), invoke [\`agent-auditor\`](../agent-auditor/SKILL.md) (evaluating YAGNI, over-specification, and structural clarity) and [\`agent-adversary\`](../agent-adversary/SKILL.md) (uncovering hidden assumptions, boundary breaks, and contradictory legacy rules) **concurrently** in clean, isolated context windows.
14690
+ - **Non-Invasive Review**: Neither auditor nor adversary modifies deliverables directly; both deliver structured reports citing canonical IDs and SHA-256 digests.
14691
+ - **Consolidated Remediation Re-Execution**: Consolidate findings and emit the Workflow Handoff back to the authoring agent, who is re-executed to resolve blocking defects and apply simplifications.
14692
+ - **Anti-Ping-Pong Guardrail (Max 2 Rounds)**: Bounded strictly to a maximum of **2 correction rounds** per phase/deliverable. If non-blocking advisories remain after round 2, proceed to the downstream phase; if blocking defects persist after round 2, escalate immediately to the Human Tech Lead.
14693
+ - **Exclusion of Diagnostic/Review Roles**: Read-only baseline verifiers and diagnostic review roles (\`agent-compliance-checker\`, \`agent-security-auditor\`, \`agent-code-reviewer\`) assess pre-existing code and are excluded from being audited by this loop.
14694
+
14228
14695
  ## End-to-End Execution Playbook
14229
14696
 
14230
14697
  ### Step 1: Non-Destructive Framework Scaffolding
@@ -14242,9 +14709,13 @@ Before modifying any code or creating SDD changes, run diagnostic verifiers to q
14242
14709
  ### Step 3: Brownfield Retro-Inception (\`agent-system-architect\` & \`agent-product-analyst\`)
14243
14710
  Instead of attempting to document 100% of a legacy monolith upfront, apply **bounded retro-inception** focused on the system boundary and the domain areas under active evolution:
14244
14711
  1. **System Vision & Context (\`ARCH-INTRO-001\`)**: Use [\`agent-product-analyst\`](../agent-product-analyst/SKILL.md) to document the current system's mission, primary actors (\`ACT-*\`), and top quality goals (\`QR-*\`) in \`specs/architecture/ARCH-INTRO-001.md\`.
14712
+ - **Transversal Loop**: Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over \`ARCH-INTRO-001\`. Consolidate findings and return handoff to \`agent-product-analyst\` to re-execute and remediate (max 2 correction rounds).
14245
14713
  2. **As-Is Component Mapping (\`CMP-*\` & \`ADR-*\`)**: Use [\`agent-system-architect\`](../agent-system-architect/SKILL.md) to map existing core modules/services into \`specs/architecture/CMP-*.md\` and capture historical architectural constraints (\`CON-*\`, \`ADR-*\`).
14714
+ - **Transversal Loop**: Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over component models. Consolidate findings and return handoff to \`agent-system-architect\` to re-execute and remediate (max 2 correction rounds).
14246
14715
  3. **Core Use Cases Extraction (\`UC-*\`, \`FR-*\`)**: Extract canonical \`UC-*\` and \`FR-*\` artifacts in \`specs/product/\` for the specific bounded context or module that will be modified or extended next, including Gherkin acceptance scenarios reflecting current expected behavior (characterization specs).
14716
+ - **Transversal Loop**: Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over extracted \`UC-*\`/\`FR-*\`. Consolidate findings and return handoff to \`agent-product-analyst\` to re-execute and remediate (max 2 correction rounds).
14247
14717
  4. **Threat & Privacy Boundary Mapping (\`agent-threat-modeler\` \u2794 \`agent-privacy-officer\`)**: Map existing trust zones (\`SEC-ENC-*\`), active threat vectors (\`ACT-THREAT-*\`, \`ABUSE-*\`, \`SEC-REQ-*\`), and personal data inventories (\`DATA-ASSET-*\`, \`PRIV-ROPA-*\`, \`PRIV-REQ-*\`) on the target module.
14718
+ - **Transversal Loop**: Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over threat and privacy models. Consolidate findings and return handoff to \`agent-threat-modeler\` and \`agent-privacy-officer\` to re-execute and remediate (max 2 correction rounds).
14248
14719
 
14249
14720
  ### Step 4: Characterization Testing & Synchronization
14250
14721
  1. Run MCP tool \`sdd_check_fix\` (\`npx aisdlc check --fix\`) to extract \`.feature\` files and compute canonical SHA-256 digests.
@@ -14255,6 +14726,7 @@ Once the target domain's baseline artifacts (\`ARCH-INTRO-*\`, \`UC-*\`, \`FR-*\
14255
14726
 
14256
14727
  ## Non-Negotiable Guardrails
14257
14728
  - **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles in the same conversation context window. In subagent-capable IDEs (Antigravity \`invoke_subagent\`, Claude Code \`Task\` / \`.claude/agents/\`, GitHub Copilot \`@agent-*\`), always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk (\`specs/\`, \`handoff.yaml\`, \`get_active_handoff\`). In chat-based IDEs (Cursor, Windsurf, Aider), persist all artifacts to disk, emit the Workflow Handoff block, and instruct the user to open a **New Chat** (or \`/clear\`) before running the next specialist.
14729
+ - **Mandatory Transversal Quality & Adversarial Loop**: Every authoring agent deliverable must undergo concurrent inspection by \`agent-auditor\` and \`agent-adversary\` in isolated context windows, followed by a re-execution of the authoring agent to remediate findings. To prevent infinite cycles, enforce the **Anti-Ping-Pong Guardrail**: maximum 2 correction rounds per phase; if unresolved blocking defects persist after round 2, escalate to the Human Tech Lead.
14258
14730
  - **Zero Drive-By Rewrites**: Never mass-refactor untouched legacy modules during onboarding. Apply the Strangler / Boy Scout rule: bring touched functions into compliance with \`quality-policy.yaml\` incrementally via governed SDD tasks (\`TSK-*\`).
14259
14731
  - **Characterization First**: Never alter legacy business logic without first capturing its current behavior in an \`FR-*\` Gherkin specification and a verifiable test suite (\`agent-qa-engineer\`).
14260
14732
  - **Immediate Secret Remediation**: If Step 2 (\`verify_security\`) uncovers leaked credentials (exit code 4), halt feature work and remediate/rotate secrets immediately.`
@@ -14262,7 +14734,7 @@ Once the target domain's baseline artifacts (\`ARCH-INTRO-*\`, \`UC-*\`, \`FR-*\
14262
14734
  {
14263
14735
  id: "aisdlc-increment",
14264
14736
  title: "Bounded SDD Feature & Bugfix Delivery Playbook",
14265
- description: "Orchestrate the complete Spec-Driven Development (SDD) lifecycle for bounded feature increments, enhancements, and bugfixes (CHG-* / TSK-*), from upstream requirement derivation and 4-tier Git branching through Red-Green-Refactor TDD, Pre-Merge Audit Triad, all 11 Quality Gates, and canonical baseline integration.",
14737
+ description: "Orchestrate the complete Spec-Driven Development (SDD) lifecycle for bounded feature increments, enhancements, and bugfixes (CHG-* / TSK-*), from upstream requirement derivation and 4-tier Git branching through Red-Green-Refactor TDD, transversal auditor/adversary verification loops, Pre-Merge Audit Triad, all 11 Quality Gates, and canonical baseline integration.",
14266
14738
  references: "[`process/06_spec_driven_development.md`](../../process/06_spec_driven_development.md), [`process/08_citation_contract_and_drift.md`](../../process/08_citation_contract_and_drift.md), [`process/10_quality_management_and_release_gates.md`](../../process/10_quality_management_and_release_gates.md), [`process/11_git_branching_and_lifecycle.md`](../../process/11_git_branching_and_lifecycle.md), and [`process/09_agent_protocols.md`](../../process/09_agent_protocols.md).",
14267
14739
  globs: "specs/changes/**, src/**, packages/**, tests/**",
14268
14740
  body: `## Purpose & Trigger
@@ -14274,9 +14746,12 @@ Use this skill for **every evolutionary increment (new feature, enhancement, ref
14274
14746
  1. Inspect active changes via MCP tool \`get_active_handoff\` and verify whether the target Use Case (\`UC-*\`) or Requirement (\`FR-*\`) already exists in \`specs/product/\`.
14275
14747
  2. If the increment introduces new behavior or modifies business rules:
14276
14748
  - Use [\`agent-product-analyst\`](../agent-product-analyst/SKILL.md) to create or update the \`UC-*\`, \`BR-*\`, and \`FR-*\` (with \`@nominal\`, \`@boundary\`, \`@invalid\` Gherkin scenarios).
14749
+ - **Transversal Loop (\`agent-product-analyst\`)**: Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over updated specs. Consolidate findings and return handoff to \`agent-product-analyst\` to re-execute and remediate (max 2 correction rounds).
14277
14750
  - Run MCP tool \`verify_duplicates\` (\`npx aisdlc verify duplicates\`) to block lexical or functional collisions early.
14278
14751
  - Use [\`agent-threat-modeler\`](../agent-threat-modeler/SKILL.md) to model any new \`ABUSE-*\` and \`SEC-REQ-*\` mitigations.
14752
+ - **Transversal Loop (\`agent-threat-modeler\`)**: Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over security models. Consolidate findings and return handoff to \`agent-threat-modeler\` to re-execute and remediate (max 2 correction rounds).
14279
14753
  - Hand off to [\`agent-privacy-officer\`](../agent-privacy-officer/SKILL.md) to model any personal data assets (\`DATA-ASSET-*\`), GDPR Art. 30 processing activities (\`PRIV-ROPA-*\`), and privacy requirements (\`PRIV-REQ-*\`).
14754
+ - **Transversal Loop (\`agent-privacy-officer\`)**: Concurrently invoke \`agent-auditor\` and \`agent-adversary\` over privacy models. Consolidate findings and return handoff to \`agent-privacy-officer\` to re-execute and remediate (max 2 correction rounds).
14280
14755
  3. Run \`sdd_check_fix\` (\`npx aisdlc check --fix\`) to sync Gherkin \`.feature\` files and validate schemas.
14281
14756
 
14282
14757
  ### Step 2: SDD Change Scaffolding & Architectural Design (\`agent-system-architect\`)
@@ -14284,7 +14759,10 @@ Use this skill for **every evolutionary increment (new feature, enhancement, ref
14284
14759
  2. Use [\`agent-system-architect\`](../agent-system-architect/SKILL.md) to complete \`specs/changes/active/<chg-id>/design.md\` and \`specs/architecture/CMP-*.md\`:
14285
14760
  - Structure \`CMP-*\` and \`design.md\` around **Modular & Hexagonal Architecture (Ports & Adapters)** (Domain/Application Core + Inbound/Outbound Ports) and define **Contract-First** shared interfaces/DTOs/schemas when spanning Frontend and Backend.
14286
14761
  - Map 100% of \`handoff.yaml\` requirements and components to atomic tasks (\`TSK-*\`) in \`tasks.md\` with explicit \`autonomy-mode\` (\`AUTONOMOUS\`, \`HUMAN_REVIEW_PLAN\`, \`HIGH_RISK_MANUAL\`, \`AMBIGUOUS\`).
14287
- 3. Run \`verify_governance\` and \`verify_friction\` to validate task governance, 100% design/handoff scope coverage, and anti-monolith limits (\`maxUseCasesPerChange = 1\`).
14762
+ 3. **Transversal Loop (\`agent-system-architect\`)**:
14763
+ - Concurrently invoke \`agent-auditor\` (evaluating YAGNI, interface bloat, task completeness) and \`agent-adversary\` (probing race conditions, contract drift, SPOFs) in isolated context windows.
14764
+ - Consolidate findings and return handoff to \`agent-system-architect\` to re-execute and remediate (max 2 correction rounds).
14765
+ 4. Run \`verify_governance\` and \`verify_friction\` to validate task governance, 100% design/handoff scope coverage, and anti-monolith limits (\`maxUseCasesPerChange = 1\`).
14288
14766
 
14289
14767
  ### Step 3: 4-Tier Git Branch Navigation & Multi-Agent Parallelism
14290
14768
  1. Navigate to the task branch using \`npx aisdlc git checkout <TSK-ID>\` (\`pnpm run git:checkout <TSK-ID>\`), which cascade-creates:
@@ -14297,7 +14775,10 @@ Use this skill for **every evolutionary increment (new feature, enhancement, ref
14297
14775
  ### Step 4: Red Phase \u2014 Failing Test Suites (\`agent-qa-engineer\`)
14298
14776
  1. Delegate to or adopt [\`agent-qa-engineer\`](../agent-qa-engineer/SKILL.md).
14299
14777
  2. Author FAILING (red) BDD/Gherkin step definitions, integration/contract tests, and mandatory E2E/UI tests (evaluating Happy Path, Sad Path, and Boundary Values for every interactive UI element, plus \`UC-*\` alternative/exception flows) in \`tests/\`.
14300
- 3. Run \`verify_testing\` (\`npx aisdlc verify testing\`) to confirm requirement test coverage before writing production code.
14778
+ 3. **Transversal Loop (\`agent-qa-engineer\`)**:
14779
+ - Concurrently invoke \`agent-auditor\` (checking test overengineering, brittle assertions) and \`agent-adversary\` (running conceptual mutation testing to prove whether trivial or empty implementations could falsely pass tests green) in isolated context windows.
14780
+ - Consolidate findings and return handoff to \`agent-qa-engineer\` to re-execute and harden test suites (max 2 correction rounds).
14781
+ 4. Run \`verify_testing\` (\`npx aisdlc verify testing\`) to confirm requirement test coverage before writing production code.
14301
14782
 
14302
14783
  ### Step 5: Green & Refactor Phase \u2014 Surgical Implementation (\`agent-developer\`)
14303
14784
  1. Delegate to or adopt [\`agent-developer\`](../agent-developer/SKILL.md).
@@ -14305,6 +14786,19 @@ Use this skill for **every evolutionary increment (new feature, enhancement, ref
14305
14786
  - (1) Modular & Hexagonal Architecture (Ports & Adapters) boundaries, (2) Inter-module interfaces/ports first, (3) Concrete component implementation (zero fake-wiring; all 4 UI states \`Loading\`, \`Empty\`, \`Error\`, \`Nominal\`), (4) Exhaustive per-function unit tests in \`tests/unit/\` (Happy Path, Sad Path, Boundary, Null/Empty).
14306
14787
  3. Verify any new dependency against \`license-policy.yaml\` via \`verify_licenses\` and PII handling against \`privacy-policy.yaml\` via \`verify_privacy\`.
14307
14788
  4. Run \`sdd_check_fix\` (\`npx aisdlc check --fix\`) and \`verify_quality\` (\`npx aisdlc verify quality\`) until Cyclomatic Complexity $\\le 10$, Cognitive $\\le 15$, Maintainability $\\ge 50$, and Function Length $\\le 40$ lines pass with zero violations.
14789
+ 5. **Transversal Loop (\`agent-developer\`)**:
14790
+ - Concurrently invoke \`agent-auditor\` (detecting overengineering, speculative parameters, AST complexity) and \`agent-adversary\` (attacking boundary inputs, concurrency races, type edge breaks with concrete PoCs) in isolated context windows.
14791
+ - Consolidate findings and return handoff to \`agent-developer\` to re-execute and remediate (max 2 correction rounds).
14792
+
14793
+ ### Mandatory Transversal Quality & Adversarial Protocol
14794
+ - **Systematic Post-Agent Execution**: Immediately following the execution of any authoring agent (\`agent-product-analyst\`, \`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-qa-engineer\`, \`agent-developer\`, \`agent-devops\`), invoke \`agent-auditor\` and \`agent-adversary\` concurrently in clean, isolated context windows over that agent's deliverables.
14795
+ - **Concurrent Inspection**:
14796
+ * [\`agent-auditor\`](../agent-auditor/SKILL.md) inspects deliverables for structural debt, premature generalizations, or unneeded complexity (YAGNI).
14797
+ * [\`agent-adversary\`](../agent-adversary/SKILL.md) actively stress-tests deliverables: uncovers requirement contradictions, simulates architectural race conditions/SPOFs, conducts conceptual mutation testing on QA suites, or crafts breaking boundary payloads for code with mandatory proof-of-break.
14798
+ - **Non-Invasive Guardrail**: Neither auditor nor adversary edits files directly. Both emit structured findings citing canonical IDs and SHA-256 hashes.
14799
+ - **Consolidated Handoff & Remediation Re-Execution**: Consolidate findings and emit the Workflow Handoff back to the audited authoring agent, who is re-executed to resolve the findings.
14800
+ - **Anti-Ping-Pong Guardrail (Max 2 Rounds)**: Enforce a strict boundary of maximum **2 correction rounds** per phase/deliverable. If non-blocking advisories remain after round 2, proceed downstream; if blocking defects persist after round 2, escalate to the Human Tech Lead.
14801
+ - **Exclusion of Downstream Review & Validation Roles**: Pre-merge review agents (\`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-compliance-checker\`) and validation agents (\`agent-expert-user\`) evaluate finished deliverables and are excluded from being audited by this loop.
14308
14802
 
14309
14803
  ### Step 6: Post-Development Functional Validation & Pre-Merge Audit Triad
14310
14804
  1. **Functional Validation (\`agent-expert-user\`)**: Validate live runtime behavior against \`UC-*\` and \`FR-*\` criteria (including \`0\` browser \`console.error\`/\`pageerror\` on UI changes).
@@ -14324,6 +14818,7 @@ Use this skill for **every evolutionary increment (new feature, enhancement, ref
14324
14818
 
14325
14819
  ## Non-Negotiable Guardrails
14326
14820
  - **Clean Context Window Isolation per Specialist Agent (Cross-IDE)**: Never execute two distinct specialist roles (e.g., \`agent-qa-engineer\` and \`agent-developer\`, or \`agent-developer\` and \`agent-security-auditor\`) in the same conversation context window. In subagent-capable IDEs (Antigravity \`invoke_subagent\`, Claude Code \`Task\` / \`.claude/agents/\`, GitHub Copilot \`@agent-*\`), always spawn each specialist in a fresh isolated subagent context that reads state strictly from disk (\`specs/\`, \`handoff.yaml\`, \`get_active_handoff\`). In chat-based IDEs (Cursor, Windsurf, Aider), persist all artifacts to disk, emit the Workflow Handoff block, and instruct the user to open a **New Chat** (or \`/clear\`) before running the next specialist.
14821
+ - **Mandatory Transversal Quality & Adversarial Loop**: Every authoring agent deliverable must undergo concurrent inspection by \`agent-auditor\` and \`agent-adversary\` in isolated context windows, followed by a re-execution of the authoring agent to remediate findings. To prevent infinite cycles, enforce the **Anti-Ping-Pong Guardrail**: maximum 2 correction rounds per phase; if unresolved blocking defects persist after round 2, escalate to the Human Tech Lead.
14327
14822
  - **Single-Use-Case Scope (\`1 UC-* = 1 CHG-*\`)**: Each SDD change (\`CHG-*\`) must deliver at most 1 Use Case (\`UC-*\`). Bundling multiple \`UC-*\` into one \`handoff.yaml\` is blocked by \`verify_governance\` (\`Greenfield monolith detected\`). Scale throughput via parallel \`CHG-*\` branches/worktrees, not monolithic changes.
14328
14823
  - **100% Design & Handoff Coverage in \`tasks.md\`**: Every \`CMP-*\`, \`FR-*\`, \`SEC-REQ-*\`, and \`PRIV-REQ-*\` declared in \`design.md\` and \`handoff.yaml\` must be explicitly assigned to at least one \`TSK-*\` in \`tasks.md\`.`
14329
14824
  }
@@ -14405,10 +14900,11 @@ This file defines the operational rules and specialized role mappings for Google
14405
14900
 
14406
14901
  ### 1. \`agent-product-analyst\` (Product Analyst / Scribe)
14407
14902
  - **Mission**: Capture new product intent via NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`) and define/refine the product model using ProductShape.
14408
- - **Phase 0 (Greenfield Product Inception)**: When creating a new product from scratch (or when \`specs/product/\` has no baseline), run a concise 3\u20135 question discovery interview (mission/problem, actors \`ACT-*\`, MVP capabilities \`UC-*\`, priority quality goals \`QR-*\`), draft \`ARCH-INTRO-001\` (\`templates/architecture/introduction-and-goals.template.md\`), and derive initial \`ACT-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, and \`QR-*\` drafts.
14903
+ - **Phase 0 (Greenfield Product Inception)**: When creating a new product from scratch (or when \`specs/product/\` has no baseline), run an iterative discovery interview of **up to 15 questions (or until the product scope is 100% clear and unambiguous)** covering: mission/problem, actors \`ACT-*\`, role/auth model, **target UI/interaction modality (Web UI, Desktop GUI, Console/TUI/CLI, Mobile, or API/SDK)**, master-data CRUD prerequisites, MVP capabilities \`UC-*\`, business rules \`BR-*\`, and priority quality goals \`QR-*\`; then draft \`ARCH-INTRO-001\` (\`templates/architecture/introduction-and-goals.template.md\`), and derive initial \`ACT-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, and \`QR-*\` drafts.
14409
14904
  - **Input**: Business intent or natural language specification.
14410
14905
  - **Output**: Markdown artifacts with YAML frontmatter compliant with \`schemas/architecture/introduction-and-goals.schema.json\` (\`ARCH-INTRO-*\`) and \`schemas/product/\` (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`).
14411
14906
  - **Guardrails**:
14907
+ - **FORBIDDEN Library-Only MVP for Human Actors**: Whenever primary actors (\`ACT-*\`) are human users, the target UI modality (Web, Desktop, Console/CLI, or Mobile) MUST be explicitly defined at Inception, and the MVP baseline MUST include a runnable presentation interface matching that modality, authentication/session access (when multi-role), and CRUD flows for foundational master entities required to execute the core business use cases without manual database seeding.
14412
14908
  - \`status\` always starts in \`draft\`.
14413
14909
  - In \`UC-*\`, format section \`1. Intent and Outcome\` under the standard English structure: \`As a <ACT-ID>... I want <action>... To <outcome>...\`.
14414
14910
  - Mandatory Gherkin criteria with \`@<ID> @automated @regression\`.
@@ -14436,6 +14932,7 @@ This file defines the operational rules and specialized role mappings for Google
14436
14932
  - **Output**: Architecture components (\`CMP-*\`), Mermaid diagrams, and immutable \`ADR-*\` records compliant with \`schemas/architecture/\`.
14437
14933
  - **Guardrails**:
14438
14934
  - Every \`CMP-*\` must declare \`satisfies-requirements\` linking \`FR-*\`, \`QR-*\`, \`SEC-REQ-*\`, and \`PRIV-REQ-*\`, and structure modules following **Modular & Hexagonal Architecture (Ports & Adapters)** (Domain/Application Core + Inbound/Outbound Ports, enforcing the Dependency Rule).
14935
+ - **No Orphan Presentation Components (\`CMP-WEB-*\` / \`CMP-UI-*\` / \`CMP-CLI-*\`)**: Never leave a presentation driving adapter unmapped in \`tasks.md\` while scheduling only backend class-library tasks. Wave 0 (\`CHG-001\`) must bootstrap the runnable host shell for the agreed UI modality (Web, Desktop, or Console/CLI) when human actors exist, and every human-facing \`CHG-*\` must deliver its vertical slice end-to-end (Domain + Persistence + Agreed UI/CLI Adapter + E2E).
14439
14936
  - Emit a return handoff to \`agent-threat-modeler\` (chaining to \`agent-privacy-officer\`) in the technical security/privacy feedback loop when infrastructure or persistence decisions introduce new attack vectors or PII flows.
14440
14937
 
14441
14938
  ### 5. \`agent-qa-engineer\` (QA Engineer and SDET)
@@ -14477,7 +14974,7 @@ This file defines the operational rules and specialized role mappings for Google
14477
14974
  ### 9. \`agent-expert-user\` (Expert User and Domain Evaluator)
14478
14975
  - **Mission**: Contrast design and specifications (design phase) and functionally validate finished software against \`UC-*\` and \`FR-*\` (post-development phase).
14479
14976
  - **Directives**:
14480
- - Design mode (upstream): Adopt the primary actor's profile under stressful field conditions, applying bimodal discrimination (strict MVP core vs. roadmap suggestion backlog in \`templates/product/user-design-feedback.template.md\`).
14977
+ - Design mode (upstream): Adopt the primary actor's profile under stressful field conditions, applying bimodal discrimination (strict MVP core vs. roadmap suggestion backlog in \`templates/product/user-design-feedback.template.md\`). Reject as \`[BLOCKING_DEFECT]\` any library-only MVP proposal for human actors that fails to define or omits the runnable presentation layer (Web, Desktop, or Console/CLI), role access, or master-data CRUD flows.
14481
14978
  - Functional validation mode (downstream / pre-PR / post-development functional validation): Thoroughly contrast interface and actual CLI execution against \`UC-*\` and \`FR-*\` acceptance criteria before pre-merge security audit.
14482
14979
  - Emit handoff block suggesting \`agent-code-reviewer\` / \`agent-security-auditor\` / \`agent-privacy-officer\` if compliant, or return to \`agent-developer\` on functional drift.
14483
14980
 
@@ -14500,6 +14997,14 @@ This file defines the operational rules and specialized role mappings for Google
14500
14997
  - **Cross-Workflow Audit**: When fixing any CI/CD or configuration defect detected in a PR, search all \`.github/workflows/*.yml\` for the same pattern (including release, post-merge, and publishing pipelines) before declaring the fix complete.
14501
14998
  - **Remote Verification**: Creating a PR (\`gh pr create\`) does not equal success; actively verify that remote checks pass (\`gh pr checks\`).
14502
14999
 
15000
+ ### 12. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
15001
+ - **Mission**: Polymorphically inspect deliverables from any specialist agent on demand, identifying structural weaknesses, overengineering, or blind spots, and proposing minimal solutions adhering strictly to YAGNI.
15002
+ - **Directives**: Constructive critique; classify findings into \`[BLOCKING_DEFECT]\`, \`[SIMPLIFICATION]\`, and \`[ADVISORY]\`; non-invasive (never edit files directly); always return handoff to the audited agent (max 1 return round).
15003
+
15004
+ ### 13. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
15005
+ - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps.
15006
+ - **Directives**: Expose failure modes across Product (logic traps), Architecture (SPOF/races), QA (mutation testing/false greens), Code (boundary/concurrency), and DevOps (pipeline escape); mandatory proof-of-break; non-invasive; always return handoff to the audited agent (max 1 return round).
15007
+
14503
15008
  ---
14504
15009
 
14505
15010
  ## 3. Git 4-Tier Hierarchy and Commit Conventions
@@ -14519,7 +15024,7 @@ This file defines the operational rules and specialized role mappings for Google
14519
15024
  - **Conditional Activation Rule by Autonomy**:
14520
15025
  - \u{1F7E2} **\`AUTONOMOUS\`** (or exclusive final supervision in PR/CI): **OMITTED**. Do not request or emit interactive handoff to avoid interrupting unattended execution.
14521
15026
  - \u{1F7E1} **Autonomy $\\ge$ \`HUMAN_REVIEW_PLAN\`** (\`HUMAN_REVIEW_PLAN\`, \`AMBIGUOUS\`, \`HIGH_RISK_MANUAL\`): **MANDATORY**. Emit the Workflow Handoff block compliant with [\`templates/workflow/agent-handoff.template.md\`](../../templates/workflow/agent-handoff.template.md) and **STOP**.
14522
- - **Block Contents**: Declare produced deliverables, recommend the next role in workflow (\`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-qa-engineer\`, \`agent-developer\`, \`agent-expert-user\`, \`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-compliance-checker\`, \`agent-devops\`, etc.), provide suggested invocation prompt, and keep **the Human Action Window open at all times for the human user to take action** (review, edit by hand, pause/reroute, or delegate).
15027
+ - **Block Contents**: Declare produced deliverables, recommend the next role in workflow (\`agent-threat-modeler\`, \`agent-privacy-officer\`, \`agent-system-architect\`, \`agent-qa-engineer\`, \`agent-developer\`, \`agent-expert-user\`, \`agent-code-reviewer\`, \`agent-security-auditor\`, \`agent-compliance-checker\`, \`agent-devops\`, \`agent-auditor\`, \`agent-adversary\`, etc.), provide suggested invocation prompt, and keep **the Human Action Window open at all times for the human user to take action** (review, edit by hand, pause/reroute, or delegate).
14523
15028
  `;
14524
15029
  var STARTER_CURSOR_CORE_RULES = `---
14525
15030
  description: Global canonical directives, 5 unbreakable commandments, and AI-SDLC pre-flight
@@ -14555,7 +15060,7 @@ Before finalizing changes or proposing commits:
14555
15060
  ## 4. Specialized Roles Mapping
14556
15061
  | Role | Mission (summary) |
14557
15062
  | :--- | :--- |
14558
- | \`agent-product-analyst\` | Phase 0 NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`, 3\u20135 question interview) + ProductShape artifacts (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`); status starts \`draft\`. |
15063
+ | \`agent-product-analyst\` | Phase 0 NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`, up to 15-question discovery interview defining UI modality & CRUD prerequisites) + ProductShape artifacts (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`); status starts \`draft\`. |
14559
15064
  | \`agent-threat-modeler\` | STRIDE/OWASP threat triad (\`ACT-THREAT-*\`, \`ABUSE-*\`, \`SEC-REQ-*\`); hands off to \`agent-privacy-officer\`. |
14560
15065
  | \`agent-privacy-officer\` | LINDDUN & GDPR/LOPDGDD privacy triad (\`DATA-ASSET-*\`, \`PRIV-ROPA-*\`, \`PRIV-REQ-*\`) + Pre-Merge \`verify:privacy\`. |
14561
15066
  | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, Mermaid diagrams, \`ADR-*\`). |
@@ -14566,6 +15071,8 @@ Before finalizing changes or proposing commits:
14566
15071
  | \`agent-expert-user\` | Bimodal MVP evaluation (design) and functional validation against \`UC-*\` and \`FR-*\` (pre-PR). |
14567
15072
  | \`agent-code-reviewer\` | PR audit (SOLID, DRY, YAGNI): \`[BLOCKING]\` / \`[CLEAN_CODE_SUGGESTION]\` / \`[COMPLIANT]\`. |
14568
15073
  | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
15074
+ | \`agent-auditor\` | Transversal on-demand constructive auditor; identifies overengineering, blind spots & YAGNI simplifications; returns handoff to audited agent. |
15075
+ | \`agent-adversary\` | Transversal on-demand Red Team adversary; breaks deliverables with reproducible PoC & mutation tests; returns handoff to audited agent. |
14569
15076
 
14570
15077
  ## 5. Task Autonomy Modes (\`tasks.md\`)
14571
15078
  - \u{1F7E2} **\`AUTONOMOUS\`**: Low risk. Implement directly, omit handoff block.
@@ -14606,7 +15113,7 @@ Every generated or modified artifact must follow canonical naming and satisfy it
14606
15113
  - Privacy Requirements: \`PRIV-REQ-[SUFFIX]\` (\`schemas/privacy/privacy-req.schema.json\`)
14607
15114
 
14608
15115
  ## 2. "AI as Scribe" Protocol Rules
14609
- - **Phase 0 (New Product Inception)**: When starting a new product, conduct a 3\u20135 question discovery interview, instantiate \`ARCH-INTRO-001\` (\`naf-perspective: "Enterprise & Capability"\`) in \`draft\`, and derive \`ACT-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, and \`QR-*\`.
15116
+ - **Phase 0 (New Product Inception)**: When starting a new product, conduct an iterative discovery interview of up to 15 questions (or until the product scope and target UI modality \u2014 Web, Desktop, Console/CLI, Mobile, or API/SDK \u2014 are completely clear), instantiate \`ARCH-INTRO-001\` (\`naf-perspective: "Enterprise & Capability"\`) in \`draft\`, and derive \`ACT-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, and \`QR-*\` (including runnable UI/CLI requirements and master-entity CRUD prerequisites when human actors exist).
14610
15117
  - **Initial Status**: Every new artifact strictly starts with \`status: draft\`. Creating artifacts directly as \`active\` or \`approved\` is forbidden.
14611
15118
  - **Gherkin Acceptance Criteria**: In every \`FR-*\` requirement, include a \`\`\`gherkin block with tags \`@<ID> @automated @regression\` and at least one \`Scenario Outline\` with an \`Examples\` data table.
14612
15119
  - **Security & Privacy Mitigations**: Every \`SEC-REQ-*\` must include negative Gherkin tests (\`@security @mitigation\`) and every \`PRIV-REQ-*\` must include Gherkin privacy scenarios (\`@privacy @gdpr\`).
@@ -14692,10 +15199,10 @@ npx tsx packages/cli/src/index.ts sdd integrate --change <chg-id>
14692
15199
 
14693
15200
  ### 1. \`agent-product-analyst\` (Product Analyst / Scribe)
14694
15201
  - **Mission**: Capture new product intent via NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`) and define/refine the product model using ProductShape.
14695
- - **Phase 0 (Greenfield Product Inception)**: When creating a new product from scratch (or when \`specs/product/\` has no baseline), run a concise 3\u20135 question discovery interview (mission/problem, actors \`ACT-*\`, MVP capabilities \`UC-*\`, priority quality goals \`QR-*\`), draft \`ARCH-INTRO-001\` (\`templates/architecture/introduction-and-goals.template.md\`), and derive initial \`ACT-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, and \`QR-*\` drafts.
15202
+ - **Phase 0 (Greenfield Product Inception)**: When creating a new product from scratch (or when \`specs/product/\` has no baseline), run an iterative discovery interview of **up to 15 questions (or until the product scope is 100% clear and unambiguous)** covering: mission/problem, actors \`ACT-*\`, role/auth model, **target UI/interaction modality (Web UI, Desktop GUI, Console/TUI/CLI, Mobile, or API/SDK)**, master-data CRUD prerequisites, MVP capabilities \`UC-*\`, business rules \`BR-*\`, and priority quality goals \`QR-*\`; then draft \`ARCH-INTRO-001\` (\`templates/architecture/introduction-and-goals.template.md\`), and derive initial \`ACT-*\`, \`UC-*\`, \`BR-*\`, \`FR-*\`, and \`QR-*\` drafts.
14696
15203
  - **Input**: Business intent or natural language specification.
14697
15204
  - **Output**: Markdown artifacts with YAML frontmatter compliant with \`schemas/architecture/introduction-and-goals.schema.json\` (\`ARCH-INTRO-*\`) and \`schemas/product/\` (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`).
14698
- - **Guardrails**: \`status\` always starts in \`draft\`. Mandatory Gherkin criteria with \`@<ID> @automated @regression\`.
15205
+ - **Guardrails**: \`status\` always starts in \`draft\`. Library-only MVPs without the agreed runnable UI/CLI entry point and master-data CRUDs for human actors are forbidden. Mandatory Gherkin criteria with \`@<ID> @automated @regression\`.
14699
15206
 
14700
15207
  ### 2. \`agent-threat-modeler\` (Threat Modeler and Security Specialist)
14701
15208
  - **Mission**: Analyze use cases and proactively model adversaries, STRIDE attack vectors, and OWASP ASVS mitigations, both at product level and in the technical security feedback loop over architecture, handing off to \`agent-privacy-officer\`.
@@ -14736,6 +15243,14 @@ npx tsx packages/cli/src/index.ts sdd integrate --change <chg-id>
14736
15243
  - **Mission**: Maintain, evolve, and audit automated project infrastructure: CI/CD workflows, Docker containers, IaC manifests, and support scripts.
14737
15244
  - **NON-INVASION GUARDRAIL**: STRICTLY FORBIDDEN from modifying application source code (\`src/\`, \`packages/*/src/\`).
14738
15245
 
15246
+ ### 12. \`agent-auditor\` (Transversal Quality and Improvement Auditor)
15247
+ - **Mission**: Polymorphically inspect deliverables from any specialist agent on demand, identifying structural weaknesses, overengineering, or blind spots, and proposing minimal solutions adhering strictly to YAGNI.
15248
+ - **Directives**: Constructive critique; classify findings into \`[BLOCKING_DEFECT]\`, \`[SIMPLIFICATION]\`, and \`[ADVISORY]\`; non-invasive (never edit files directly); always return handoff to the audited agent (max 1 return round).
15249
+
15250
+ ### 13. \`agent-adversary\` (Transversal Red Team and Chaos Adversary)
15251
+ - **Mission**: Actively attempt to break, bypass, or invalidate deliverables from any target specialist agent, providing concrete proofs-of-concept (PoC), counterexamples, and reproduction steps.
15252
+ - **Directives**: Expose failure modes across Product (logic traps), Architecture (SPOF/races), QA (mutation testing/false greens), Code (boundary/concurrency), and DevOps (pipeline escape); mandatory proof-of-break; non-invasive; always return handoff to the audited agent (max 1 return round).
15253
+
14739
15254
  ---
14740
15255
 
14741
15256
  ## 4. Task Autonomy Modes (\`tasks.md\`)
@@ -14859,7 +15374,7 @@ Non-Negotiable Quality Thresholds (\`quality-policy.yaml\`):
14859
15374
 
14860
15375
  | Role | Mission (summary) |
14861
15376
  | :--- | :--- |
14862
- | \`agent-product-analyst\` | Phase 0 NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`, 3\u20135 question interview) + ProductShape artifacts (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`); \`status\` starts \`draft\`. |
15377
+ | \`agent-product-analyst\` | Phase 0 NAF v4 Enterprise & Capability Vision (\`ARCH-INTRO-*\`, up to 15-question discovery interview defining UI modality & CRUD prerequisites) + ProductShape artifacts (\`ACT-*\`, \`UC-*\`, \`FR-*\`, \`QR-*\`, \`BR-*\`); \`status\` starts \`draft\`. |
14863
15378
  | \`agent-threat-modeler\` | STRIDE/OWASP threat triad (\`ACT-THREAT-*\`, \`ABUSE-*\`, \`SEC-REQ-*\`); hands off to \`agent-privacy-officer\`. |
14864
15379
  | \`agent-privacy-officer\` | LINDDUN & GDPR/LOPDGDD privacy triad (\`DATA-ASSET-*\`, \`PRIV-ROPA-*\`, \`PRIV-REQ-*\`) + Pre-Merge \`verify:privacy\`. |
14865
15380
  | \`agent-system-architect\` | Modular arc42 + NAF v4 architecture (\`CMP-*\`, Mermaid diagrams, \`ADR-*\`). |
@@ -14870,6 +15385,8 @@ Non-Negotiable Quality Thresholds (\`quality-policy.yaml\`):
14870
15385
  | \`agent-expert-user\` | Bimodal MVP evaluation (design) and functional validation against \`UC-*\` and \`FR-*\` (pre-PR). |
14871
15386
  | \`agent-code-reviewer\` | PR audit (SOLID, DRY, YAGNI): \`[BLOCKING]\` / \`[CLEAN_CODE_SUGGESTION]\` / \`[COMPLIANT]\`. |
14872
15387
  | \`agent-devops\` | CI/CD, Docker, IaC only \u2014 **FORBIDDEN** to touch \`src/\` or \`packages/*/src/\`. |
15388
+ | \`agent-auditor\` | Transversal on-demand constructive auditor; identifies overengineering, blind spots & YAGNI simplifications; returns handoff to audited agent. |
15389
+ | \`agent-adversary\` | Transversal on-demand Red Team adversary; breaks deliverables with reproducible PoC & mutation tests; returns handoff to audited agent. |
14873
15390
 
14874
15391
  ---
14875
15392
 
@@ -16031,6 +16548,522 @@ var STARTER_BASE_TEMPLATES = [
16031
16548
  { relPath: "process/README.md", content: STARTER_PROCESS_README },
16032
16549
  { relPath: "compliance/license-manifest.yaml", content: STARTER_COMPLIANCE_LICENSE_MANIFEST_YAML }
16033
16550
  ];
16551
+ var VALID_CODING_RULE_STACKS = [
16552
+ "dotnet",
16553
+ "typescript",
16554
+ "javascript",
16555
+ "angular",
16556
+ "java",
16557
+ "kotlin",
16558
+ "rust",
16559
+ "go",
16560
+ "c",
16561
+ "cpp"
16562
+ ];
16563
+ var PROTECTED_CODING_RULES_FILES = [
16564
+ "Directory.Build.props",
16565
+ "tsconfig.strict.json",
16566
+ "eslint.config.mjs",
16567
+ "gradle/init.d/aisdlc-strict.init.gradle.kts",
16568
+ "config/pmd/aisdlc-ruleset.xml",
16569
+ "config/detekt/detekt.yml",
16570
+ ".cargo/config.toml",
16571
+ ".clippy.toml",
16572
+ ".golangci.yml",
16573
+ ".clang-tidy",
16574
+ "cmake/AisdlcStrictCompiler.cmake",
16575
+ ".github/CODEOWNERS"
16576
+ ];
16577
+ var DOTNET_DIRECTORY_BUILD_PROPS = `<Project>
16578
+ <!-- 1. Global strict compiler and analyzer rules for all projects (src and tests) -->
16579
+ <PropertyGroup>
16580
+ <Nullable>enable</Nullable>
16581
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
16582
+ <AnalysisLevel>latest-recommended</AnalysisLevel>
16583
+ <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
16584
+ </PropertyGroup>
16585
+
16586
+ <!-- 2. Strict unit/E2E test guardrails (xUnit, MSTest, NUnit) -->
16587
+ <PropertyGroup Condition="'$(IsTestProject)' == 'true' or $(MSBuildProjectName.EndsWith('Tests')) or $(MSBuildProjectName.EndsWith('Test'))">
16588
+ <IsTestProject>true</IsTestProject>
16589
+ <NoWarn>$(NoWarn);CA1707;CA2007</NoWarn>
16590
+ <MSTestAnalysisMode>Recommended</MSTestAnalysisMode>
16591
+ <WarningsAsErrors>$(WarningsAsErrors);S2699;S1607;MSTEST0006;MSTEST0014;MSTEST0015;MSTEST0017;MSTEST0032;xUnit1026;xUnit1013</WarningsAsErrors>
16592
+ </PropertyGroup>
16593
+
16594
+ <ItemGroup Condition="'$(IsTestProject)' == 'true' or $(MSBuildProjectName.EndsWith('Tests')) or $(MSBuildProjectName.EndsWith('Test'))">
16595
+ <PackageReference Include="SonarAnalyzer.CSharp" Version="10.*">
16596
+ <PrivateAssets>all</PrivateAssets>
16597
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
16598
+ </PackageReference>
16599
+ </ItemGroup>
16600
+ </Project>
16601
+ `;
16602
+ var TS_STRICT_TSCONFIG = `{
16603
+ "$schema": "https://json.schemastore.org/tsconfig",
16604
+ "compilerOptions": {
16605
+ "strict": true,
16606
+ "allowJs": true,
16607
+ "checkJs": true,
16608
+ "noImplicitOverride": true,
16609
+ "noPropertyAccessFromIndexSignature": true,
16610
+ "noImplicitReturns": true,
16611
+ "noFallthroughCasesInSwitch": true,
16612
+ "noUnusedLocals": true,
16613
+ "noUnusedParameters": true,
16614
+ "noUncheckedIndexedAccess": true,
16615
+ "exactOptionalPropertyTypes": true,
16616
+ "forceConsistentCasingInFileNames": true
16617
+ },
16618
+ "angularCompilerOptions": {
16619
+ "strictInjectionParameters": true,
16620
+ "strictInputAccessModifiers": true,
16621
+ "strictTemplates": true,
16622
+ "strictStandalone": true,
16623
+ "extendedDiagnostics": {
16624
+ "defaultCategory": "error"
16625
+ }
16626
+ }
16627
+ }
16628
+ `;
16629
+ var TS_ESLINT_CONFIG_MJS = `// AI-SDLC: Immutable Strict Coding & Test Rules for TypeScript / JavaScript / Angular
16630
+ import tseslint from "typescript-eslint";
16631
+
16632
+ export default tseslint.config(
16633
+ {
16634
+ files: ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"],
16635
+ extends: [...tseslint.configs.strictTypeChecked],
16636
+ languageOptions: {
16637
+ parserOptions: {
16638
+ projectService: true,
16639
+ },
16640
+ },
16641
+ rules: {
16642
+ "@typescript-eslint/no-explicit-any": "error",
16643
+ "@typescript-eslint/ban-ts-comment": "error",
16644
+ "@typescript-eslint/no-floating-promises": "error",
16645
+ "@typescript-eslint/await-thenable": "error",
16646
+ "@typescript-eslint/no-misused-promises": "error",
16647
+ "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
16648
+ },
16649
+ },
16650
+ {
16651
+ files: ["**/*.spec.ts", "**/*.test.ts", "**/*.spec.js", "**/*.test.js"],
16652
+ rules: {
16653
+ "no-restricted-globals": [
16654
+ "error",
16655
+ { "name": "fit", "message": "Focused tests (fit) are forbidden by AI-SDLC." },
16656
+ { "name": "fdescribe", "message": "Focused suites (fdescribe) are forbidden by AI-SDLC." },
16657
+ { "name": "xit", "message": "Skipped tests (xit) are forbidden by AI-SDLC." },
16658
+ { "name": "xdescribe", "message": "Skipped suites (xdescribe) are forbidden by AI-SDLC." }
16659
+ ]
16660
+ }
16661
+ }
16662
+ );
16663
+ `;
16664
+ var GRADLE_STRICT_INIT_KTS = `// AI-SDLC: Immutable Gradle Strict Compiler & Test Guardrails (Java & Kotlin)
16665
+ allprojects {
16666
+ tasks.withType<JavaCompile>().configureEach {
16667
+ options.compilerArgs.addAll(listOf("-Werror", "-Xlint:all", "-Xlint:-processing"))
16668
+ }
16669
+ tasks.withType<Test>().configureEach {
16670
+ useJUnitPlatform()
16671
+ failOnNoDiscoveredTests.set(true)
16672
+ }
16673
+ }
16674
+ `;
16675
+ var JAVA_PMD_RULESET_XML = `<?xml version="1.0" encoding="UTF-8"?>
16676
+ <ruleset name="AI-SDLC Strict Java &amp; JUnit Rules"
16677
+ xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
16678
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
16679
+ xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.github.io/schema/ruleset_2_0_0.xsd">
16680
+ <description>AI-SDLC Mandatory Java &amp; Unit Test Verification Rules</description>
16681
+ <rule ref="category/java/bestpractices.xml/JUnitTestsShouldIncludeAssert" />
16682
+ <rule ref="category/java/bestpractices.xml/UnusedLocalVariable" />
16683
+ <rule ref="category/java/bestpractices.xml/UnusedPrivateMethod" />
16684
+ <rule ref="category/java/errorprone.xml/EmptyCatchBlock" />
16685
+ </ruleset>
16686
+ `;
16687
+ var KOTLIN_DETEKT_YML = `# AI-SDLC: Immutable Detekt Rules for Kotlin & Unit Tests
16688
+ build:
16689
+ maxIssues: 0
16690
+
16691
+ potential-bugs:
16692
+ active: true
16693
+ IgnoredReturnValue:
16694
+ active: true
16695
+ UnreachableCode:
16696
+ active: true
16697
+
16698
+ exceptions:
16699
+ active: true
16700
+ SwallowedException:
16701
+ active: true
16702
+ EmptyCatchBlock:
16703
+ active: true
16704
+
16705
+ style:
16706
+ active: true
16707
+ ForbiddenAnnotation:
16708
+ active: true
16709
+ annotations:
16710
+ - 'org.junit.jupiter.api.Disabled'
16711
+ - 'org.junit.Ignore'
16712
+ - 'kotlin.test.Ignore'
16713
+ `;
16714
+ var RUST_CARGO_CONFIG_TOML = `# AI-SDLC: Immutable Rust Compiler & Clippy Guardrails
16715
+ [build]
16716
+ rustflags = [
16717
+ "-D", "warnings",
16718
+ "-D", "unused-must-use",
16719
+ "-D", "dead-code",
16720
+ "-D", "clippy::all",
16721
+ "-D", "clippy::unwrap_used",
16722
+ "-D", "clippy::todo",
16723
+ "-D", "clippy::unimplemented",
16724
+ "-D", "clippy::ignore_without_reason",
16725
+ "-D", "clippy::assertions_on_constants"
16726
+ ]
16727
+ `;
16728
+ var RUST_CLIPPY_TOML = `# AI-SDLC: Clippy configuration
16729
+ allow-unwrap-in-tests = true
16730
+ `;
16731
+ var GO_GOLANGCI_YML = `# AI-SDLC: Immutable Go & Testing Linter Guardrails
16732
+ run:
16733
+ tests: true
16734
+
16735
+ issues:
16736
+ max-issues-per-linter: 0
16737
+ max-same-issues: 0
16738
+
16739
+ linters:
16740
+ enable:
16741
+ - errcheck
16742
+ - govet
16743
+ - staticcheck
16744
+ - unused
16745
+ - ineffassign
16746
+ - testifylint
16747
+ - thelper
16748
+ - forbidigo
16749
+
16750
+ linters-settings:
16751
+ testifylint:
16752
+ enable-all: true
16753
+ forbidigo:
16754
+ analyze-types: true
16755
+ forbid:
16756
+ - p: ^testing\\.T\\.Skip.*$
16757
+ msg: "Skipping unit tests with t.Skip() is forbidden by AI-SDLC."
16758
+ `;
16759
+ var CPP_CLANG_TIDY = `# AI-SDLC: Immutable C/C++ Clang-Tidy Guardrails
16760
+ Checks: >
16761
+ -*,
16762
+ bugprone-*,
16763
+ cert-*,
16764
+ clang-analyzer-*,
16765
+ cppcoreguidelines-*,
16766
+ modernize-*,
16767
+ performance-*,
16768
+ readability-*
16769
+ WarningsAsErrors: '*'
16770
+ `;
16771
+ var CPP_CMAKE_STRICT = `# AI-SDLC: Immutable C/C++ Compiler & CTest Guardrails
16772
+ if(MSVC)
16773
+ add_compile_options(/W4 /WX /permissive-)
16774
+ else()
16775
+ add_compile_options(-Wall -Wextra -Wpedantic -Werror -Wnull-dereference -Wunused-result)
16776
+ endif()
16777
+
16778
+ set(CMAKE_CXX_CLANG_TIDY "clang-tidy")
16779
+ set(CMAKE_C_CLANG_TIDY "clang-tidy")
16780
+ `;
16781
+ var STARTER_ANTIGRAVITY_HOOKS_JSON = `{
16782
+ "branch-guard": {
16783
+ "enabled": true,
16784
+ "PreToolUse": [
16785
+ {
16786
+ "matcher": "edit_file|write_file",
16787
+ "hooks": [
16788
+ {
16789
+ "type": "command",
16790
+ "command": "node scripts/guard-branch.cjs",
16791
+ "timeout": 10
16792
+ }
16793
+ ]
16794
+ }
16795
+ ]
16796
+ }
16797
+ }
16798
+ `;
16799
+ var STARTER_AGENT_GUARD_WRAPPER_CJS = `#!/usr/bin/env node
16800
+ // Forwarding wrapper or direct execution from .agent
16801
+ require('../../scripts/guard-branch.cjs');
16802
+ `;
16803
+ var STARTER_GUARD_BRANCH_CJS = `#!/usr/bin/env node
16804
+ /**
16805
+ * AI-SDLC: Antigravity PreToolUse Branch & Immutable Coding Rules Guard Hook
16806
+ * 1. Prevents AI agents from modifying or writing files directly on protected branches (main, master, release/*).
16807
+ * 2. Prevents AI agents from modifying or weakening deployed coding rules files once created.
16808
+ */
16809
+
16810
+ const { execSync } = require('child_process');
16811
+ const path = require('path');
16812
+
16813
+ const PROTECTED_CODING_RULES_FILES = [
16814
+ 'Directory.Build.props',
16815
+ 'tsconfig.strict.json',
16816
+ 'eslint.config.mjs',
16817
+ 'gradle/init.d/aisdlc-strict.init.gradle.kts',
16818
+ 'config/pmd/aisdlc-ruleset.xml',
16819
+ 'config/detekt/detekt.yml',
16820
+ '.cargo/config.toml',
16821
+ '.clippy.toml',
16822
+ '.golangci.yml',
16823
+ '.clang-tidy',
16824
+ 'cmake/AisdlcStrictCompiler.cmake',
16825
+ '.github/CODEOWNERS',
16826
+ ];
16827
+
16828
+ function getWorkingBranch(cwd) {
16829
+ try {
16830
+ const sym = execSync('git symbolic-ref --short HEAD', {
16831
+ cwd,
16832
+ encoding: 'utf-8',
16833
+ stdio: ['pipe', 'pipe', 'ignore'],
16834
+ }).trim();
16835
+ if (sym) return sym;
16836
+ } catch {}
16837
+
16838
+ try {
16839
+ return execSync('git rev-parse --abbrev-ref HEAD', {
16840
+ cwd,
16841
+ encoding: 'utf-8',
16842
+ stdio: ['pipe', 'pipe', 'ignore'],
16843
+ }).trim();
16844
+ } catch {}
16845
+
16846
+ return '';
16847
+ }
16848
+
16849
+ function isProtectedCodingRulesTarget(targetPath, cwd) {
16850
+ if (!targetPath) return false;
16851
+ const resolved = path.resolve(cwd, targetPath);
16852
+
16853
+ const norm = resolved.replace(/\\\\/g, '/');
16854
+ const rel = path.relative(cwd, resolved).replace(/\\\\/g, '/');
16855
+ return PROTECTED_CODING_RULES_FILES.some(
16856
+ (ruleFile) => rel === ruleFile || norm.endsWith('/' + ruleFile)
16857
+ ) || rel.startsWith('templates/coding-rules/');
16858
+ }
16859
+
16860
+ function evaluateGuardDecision(payload) {
16861
+ const targetPath = payload.toolCall?.args?.Path || '';
16862
+ const workspacePaths = payload.workspacePaths || [];
16863
+ const cwd = workspacePaths[0] || process.cwd();
16864
+ const resolvedPath = targetPath ? path.resolve(cwd, targetPath) : '';
16865
+ const normPath = resolvedPath.replace(/\\\\/g, '/');
16866
+
16867
+ if (isProtectedCodingRulesTarget(resolvedPath, cwd)) {
16868
+ return {
16869
+ decision: 'deny',
16870
+ reason: \`\u274C [AI-SDLC Immutable Coding Rules Guard] BLOCKED: AI agents are forbidden from modifying protected coding rules file '\${path.basename(targetPath)}'. Fix the source or test code to satisfy the compiler/linter rules instead of altering the rule configuration.\`,
16871
+ };
16872
+ }
16873
+
16874
+ if (
16875
+ normPath.includes('/.gemini/') ||
16876
+ normPath.includes('/brain/') ||
16877
+ normPath.includes('/scratch/')
16878
+ ) {
16879
+ return { decision: 'allow' };
16880
+ }
16881
+
16882
+ const branch = getWorkingBranch(cwd);
16883
+ if (/^(main|master|release\\/.*)$/.test(branch)) {
16884
+ return {
16885
+ decision: 'deny',
16886
+ reason: \`\u274C [AI-SDLC Security Guard] BLOCKED: Direct file modifications on protected branch '\${branch}' are forbidden. You must create and checkout a new working branch first before editing files (e.g. 'git checkout -b feat/<CHG-ID>-<slug>' or 'git checkout -b task/<PARENT-ID>/<TSK-ID>-<slug>').\`,
16887
+ };
16888
+ }
16889
+
16890
+ return { decision: 'allow' };
16891
+ }
16892
+
16893
+ function main() {
16894
+ let input = '';
16895
+ process.stdin.setEncoding('utf-8');
16896
+ process.stdin.on('data', (chunk) => {
16897
+ input += chunk;
16898
+ });
16899
+ process.stdin.on('end', () => {
16900
+ try {
16901
+ const payload = input.trim() ? JSON.parse(input) : {};
16902
+ console.log(JSON.stringify(evaluateGuardDecision(payload)));
16903
+ } catch {
16904
+ console.log(JSON.stringify({ decision: 'allow' }));
16905
+ }
16906
+ });
16907
+ }
16908
+
16909
+ main();
16910
+ `;
16911
+ var STACK_FILE_MAP = {
16912
+ dotnet: [{ relPath: "Directory.Build.props", content: DOTNET_DIRECTORY_BUILD_PROPS }],
16913
+ typescript: [
16914
+ { relPath: "tsconfig.strict.json", content: TS_STRICT_TSCONFIG },
16915
+ { relPath: "eslint.config.mjs", content: TS_ESLINT_CONFIG_MJS }
16916
+ ],
16917
+ javascript: [
16918
+ { relPath: "tsconfig.strict.json", content: TS_STRICT_TSCONFIG },
16919
+ { relPath: "eslint.config.mjs", content: TS_ESLINT_CONFIG_MJS }
16920
+ ],
16921
+ angular: [
16922
+ { relPath: "tsconfig.strict.json", content: TS_STRICT_TSCONFIG },
16923
+ { relPath: "eslint.config.mjs", content: TS_ESLINT_CONFIG_MJS }
16924
+ ],
16925
+ java: [
16926
+ { relPath: "gradle/init.d/aisdlc-strict.init.gradle.kts", content: GRADLE_STRICT_INIT_KTS },
16927
+ { relPath: "config/pmd/aisdlc-ruleset.xml", content: JAVA_PMD_RULESET_XML }
16928
+ ],
16929
+ kotlin: [
16930
+ { relPath: "gradle/init.d/aisdlc-strict.init.gradle.kts", content: GRADLE_STRICT_INIT_KTS },
16931
+ { relPath: "config/detekt/detekt.yml", content: KOTLIN_DETEKT_YML }
16932
+ ],
16933
+ rust: [
16934
+ { relPath: ".cargo/config.toml", content: RUST_CARGO_CONFIG_TOML },
16935
+ { relPath: ".clippy.toml", content: RUST_CLIPPY_TOML }
16936
+ ],
16937
+ go: [{ relPath: ".golangci.yml", content: GO_GOLANGCI_YML }],
16938
+ c: [
16939
+ { relPath: ".clang-tidy", content: CPP_CLANG_TIDY },
16940
+ { relPath: "cmake/AisdlcStrictCompiler.cmake", content: CPP_CMAKE_STRICT }
16941
+ ],
16942
+ cpp: [
16943
+ { relPath: ".clang-tidy", content: CPP_CLANG_TIDY },
16944
+ { relPath: "cmake/AisdlcStrictCompiler.cmake", content: CPP_CMAKE_STRICT }
16945
+ ]
16946
+ };
16947
+ function getReferenceCodingRulesTemplates() {
16948
+ return [
16949
+ { relPath: "templates/coding-rules/dotnet/Directory.Build.props", content: DOTNET_DIRECTORY_BUILD_PROPS },
16950
+ { relPath: "templates/coding-rules/typescript/tsconfig.strict.json", content: TS_STRICT_TSCONFIG },
16951
+ { relPath: "templates/coding-rules/typescript/eslint.config.mjs", content: TS_ESLINT_CONFIG_MJS },
16952
+ { relPath: "templates/coding-rules/jvm/aisdlc-strict.init.gradle.kts", content: GRADLE_STRICT_INIT_KTS },
16953
+ { relPath: "templates/coding-rules/java/aisdlc-ruleset.xml", content: JAVA_PMD_RULESET_XML },
16954
+ { relPath: "templates/coding-rules/kotlin/detekt.yml", content: KOTLIN_DETEKT_YML },
16955
+ { relPath: "templates/coding-rules/rust/config.toml", content: RUST_CARGO_CONFIG_TOML },
16956
+ { relPath: "templates/coding-rules/rust/.clippy.toml", content: RUST_CLIPPY_TOML },
16957
+ { relPath: "templates/coding-rules/go/.golangci.yml", content: GO_GOLANGCI_YML },
16958
+ { relPath: "templates/coding-rules/cpp/.clang-tidy", content: CPP_CLANG_TIDY },
16959
+ { relPath: "templates/coding-rules/cpp/AisdlcStrictCompiler.cmake", content: CPP_CMAKE_STRICT }
16960
+ ];
16961
+ }
16962
+ function hasFileMatching(entries, suffixOrName) {
16963
+ return entries.some((e) => e === suffixOrName || e.endsWith(suffixOrName));
16964
+ }
16965
+ function detectJvmAndNativeStacks(entries, detected) {
16966
+ if (hasFileMatching(entries, "pom.xml") || hasFileMatching(entries, "build.gradle")) {
16967
+ detected.add("java");
16968
+ }
16969
+ if (hasFileMatching(entries, "build.gradle.kts")) {
16970
+ detected.add("java");
16971
+ detected.add("kotlin");
16972
+ }
16973
+ if (hasFileMatching(entries, "Cargo.toml")) detected.add("rust");
16974
+ if (hasFileMatching(entries, "go.mod")) detected.add("go");
16975
+ if (hasFileMatching(entries, "CMakeLists.txt") || hasFileMatching(entries, "Makefile")) {
16976
+ detected.add("cpp");
16977
+ }
16978
+ }
16979
+ function detectProjectStacks(targetDir) {
16980
+ if (!fs8__namespace.existsSync(targetDir)) return [];
16981
+ let entries = [];
16982
+ try {
16983
+ entries = fs8__namespace.readdirSync(targetDir);
16984
+ } catch {
16985
+ return [];
16986
+ }
16987
+ const detected = /* @__PURE__ */ new Set();
16988
+ if (hasFileMatching(entries, ".sln") || hasFileMatching(entries, ".slnx") || hasFileMatching(entries, ".csproj")) {
16989
+ detected.add("dotnet");
16990
+ }
16991
+ if (hasFileMatching(entries, "angular.json")) detected.add("angular");
16992
+ else if (hasFileMatching(entries, "tsconfig.json")) detected.add("typescript");
16993
+ else if (hasFileMatching(entries, "package.json")) detected.add("javascript");
16994
+ detectJvmAndNativeStacks(entries, detected);
16995
+ return Array.from(detected);
16996
+ }
16997
+ var STACK_ALIASES = {
16998
+ "c#": "dotnet",
16999
+ csharp: "dotnet",
17000
+ cs: "dotnet",
17001
+ net: "dotnet",
17002
+ ".net": "dotnet",
17003
+ ts: "typescript",
17004
+ js: "javascript",
17005
+ ng: "angular",
17006
+ kt: "kotlin",
17007
+ rs: "rust",
17008
+ golang: "go",
17009
+ "c++": "cpp",
17010
+ cxx: "cpp"
17011
+ };
17012
+ function parseSingleStackToken(token, out) {
17013
+ if (token === "all") {
17014
+ VALID_CODING_RULE_STACKS.forEach((s) => out.add(s));
17015
+ return true;
17016
+ }
17017
+ const mapped = STACK_ALIASES[token] || token;
17018
+ if (VALID_CODING_RULE_STACKS.includes(mapped)) {
17019
+ out.add(mapped);
17020
+ return true;
17021
+ }
17022
+ return false;
17023
+ }
17024
+ function resolveCodingRuleStacks(stackOption, targetDir) {
17025
+ if (stackOption === void 0 || stackOption === null || stackOption === "") {
17026
+ return { valid: true, stacks: detectProjectStacks(targetDir) };
17027
+ }
17028
+ const rawList = Array.isArray(stackOption) ? stackOption : String(stackOption).split(",");
17029
+ const resolved = /* @__PURE__ */ new Set();
17030
+ for (const raw of rawList) {
17031
+ const token = raw.trim().toLowerCase();
17032
+ if (!token || token === "none" || token === "false") continue;
17033
+ if (!parseSingleStackToken(token, resolved)) {
17034
+ return {
17035
+ valid: false,
17036
+ stacks: [],
17037
+ error: `Unrecognized technology stack: '${raw.trim()}'. Valid options: ${VALID_CODING_RULE_STACKS.join(", ")}, all, none.`
17038
+ };
17039
+ }
17040
+ }
17041
+ return { valid: true, stacks: Array.from(resolved) };
17042
+ }
17043
+ function getCodingRulesFilesForStacks(stacks) {
17044
+ const seen = /* @__PURE__ */ new Set();
17045
+ const files = [];
17046
+ for (const stack of stacks) {
17047
+ const entries = STACK_FILE_MAP[stack] || [];
17048
+ for (const entry of entries) {
17049
+ if (!seen.has(entry.relPath)) {
17050
+ seen.add(entry.relPath);
17051
+ files.push(entry);
17052
+ }
17053
+ }
17054
+ }
17055
+ return files;
17056
+ }
17057
+ function isProtectedCodingRulesFile(filePath, rootDir) {
17058
+ const norm = filePath.replace(/\\/g, "/").replace(/^\.\//, "");
17059
+ const rel = rootDir ? path5__namespace.relative(rootDir, path5__namespace.resolve(rootDir, filePath)).replace(/\\/g, "/") : norm;
17060
+ if (rel.startsWith("templates/coding-rules/") || norm.includes("/templates/coding-rules/")) {
17061
+ return true;
17062
+ }
17063
+ return PROTECTED_CODING_RULES_FILES.some(
17064
+ (protectedRel) => rel === protectedRel || norm === protectedRel || norm.endsWith("/" + protectedRel)
17065
+ );
17066
+ }
16034
17067
 
16035
17068
  // src/init/index.ts
16036
17069
  var VALID_CI_PROVIDERS = ["github", "gitlab", "azure", "bitbucket"];
@@ -16740,7 +17773,12 @@ function resolveAgentTargets(agents) {
16740
17773
  }
16741
17774
  function appendAntigravityFiles(dirs, files) {
16742
17775
  dirs.push(".agent/rules", ".agent/agents", ".agent/skills");
16743
- files.push({ relPath: ".agent/rules/ai-sdlc.md", content: STARTER_ANTIGRAVITY_RULES });
17776
+ files.push(
17777
+ { relPath: ".agent/rules/ai-sdlc.md", content: STARTER_ANTIGRAVITY_RULES },
17778
+ { relPath: ".agent/hooks.json", content: STARTER_ANTIGRAVITY_HOOKS_JSON },
17779
+ { relPath: ".agent/scripts/guard-branch.cjs", content: STARTER_AGENT_GUARD_WRAPPER_CJS },
17780
+ { relPath: "scripts/guard-branch.cjs", content: STARTER_GUARD_BRANCH_CJS }
17781
+ );
16744
17782
  for (const agent of SPECIALIZED_AGENT_TEMPLATES) {
16745
17783
  const content = renderAntigravityAgentFile(agent);
16746
17784
  files.push({ relPath: `.agent/agents/${agent.id}.md`, content });
@@ -16811,24 +17849,25 @@ function collectAgentFiles(targets) {
16811
17849
  appendMcpFiles(dirs, files);
16812
17850
  return { dirs, files };
16813
17851
  }
17852
+ function recordDryRunFile(exists, canOverwrite, relPath, results) {
17853
+ if (exists && canOverwrite) results.filesUpdated.push(relPath);
17854
+ else if (!exists) results.filesCreated.push(relPath);
17855
+ }
17856
+ function persistFileToDisk(fullFilePath, content, exists, relPath, results) {
17857
+ const parentDir = path5__namespace.dirname(fullFilePath);
17858
+ if (!fs8__namespace.existsSync(parentDir)) fs8__namespace.mkdirSync(parentDir, { recursive: true });
17859
+ fs8__namespace.writeFileSync(fullFilePath, content, "utf-8");
17860
+ if (exists) results.filesUpdated.push(relPath);
17861
+ else results.filesCreated.push(relPath);
17862
+ }
16814
17863
  function writeSingleFile(fullFilePath, content, relPath, opts, results) {
16815
17864
  const exists = fs8__namespace.existsSync(fullFilePath);
17865
+ const canOverwrite = Boolean(opts.force && !PROTECTED_CODING_RULES_FILES.includes(relPath));
16816
17866
  if (opts.dryRun) {
16817
- if (exists && opts.force) results.filesUpdated.push(relPath);
16818
- else if (!exists) results.filesCreated.push(relPath);
17867
+ recordDryRunFile(exists, canOverwrite, relPath, results);
16819
17868
  return;
16820
17869
  }
16821
- const parentDir = path5__namespace.dirname(fullFilePath);
16822
- if (!fs8__namespace.existsSync(parentDir)) {
16823
- fs8__namespace.mkdirSync(parentDir, { recursive: true });
16824
- }
16825
- if (!exists) {
16826
- fs8__namespace.writeFileSync(fullFilePath, content, "utf-8");
16827
- results.filesCreated.push(relPath);
16828
- } else if (opts.force) {
16829
- fs8__namespace.writeFileSync(fullFilePath, content, "utf-8");
16830
- results.filesUpdated.push(relPath);
16831
- }
17870
+ if (!exists || canOverwrite) persistFileToDisk(fullFilePath, content, exists, relPath, results);
16832
17871
  }
16833
17872
  function writeProjectFiles(destDir, files, dryRun, force) {
16834
17873
  const results = { filesCreated: [], filesUpdated: [] };
@@ -16884,6 +17923,7 @@ var BASE_DIRECTORIES = [
16884
17923
  "templates/sdd",
16885
17924
  "templates/manuals",
16886
17925
  "templates/ci",
17926
+ "templates/coding-rules",
16887
17927
  "templates/workflow",
16888
17928
  "specs",
16889
17929
  "reports",
@@ -16918,25 +17958,32 @@ function createDirectoriesOnDisk(destDir, directories, dryRun) {
16918
17958
  }
16919
17959
  return created;
16920
17960
  }
16921
- function collectStarterFiles(ciProvider, agentFiles = [], archGranularity = "minimal") {
16922
- const files = [
17961
+ function collectPolicyAndSchemaFiles() {
17962
+ return [
16923
17963
  { relPath: "quality-policy.yaml", content: STARTER_QUALITY_POLICY },
16924
17964
  { relPath: "license-policy.yaml", content: STARTER_LICENSE_POLICY },
16925
17965
  { relPath: "privacy-policy.yaml", content: STARTER_PRIVACY_POLICY },
16926
17966
  ...STARTER_BASE_TEMPLATES,
16927
17967
  ...STARTER_SCHEMAS.map((s) => ({ relPath: s.relPath, content: s.content })),
17968
+ ...getReferenceCodingRulesTemplates()
17969
+ ];
17970
+ }
17971
+ function collectArchitectureTemplateFiles(archGranularity) {
17972
+ return getArchitectureTemplates(archGranularity).map((t) => ({
17973
+ relPath: path5__namespace.join("templates", "architecture", t.filename).replace(/\\/g, "/"),
17974
+ content: t.content
17975
+ }));
17976
+ }
17977
+ function collectStarterFiles(ciProvider, agentFiles = [], archGranularity = "minimal", stacks = []) {
17978
+ const files = [
17979
+ ...collectPolicyAndSchemaFiles(),
17980
+ ...getCodingRulesFilesForStacks(stacks),
16928
17981
  ...getCiWorkflowFiles(ciProvider),
16929
17982
  ...agentFiles,
16930
- ...getArchitectureTemplates(archGranularity).map((t) => ({
16931
- relPath: path5__namespace.join("templates", "architecture", t.filename).replace(/\\/g, "/"),
16932
- content: t.content
16933
- }))
17983
+ ...collectArchitectureTemplateFiles(archGranularity)
16934
17984
  ];
16935
17985
  if (ciProvider === "github" || !ciProvider) {
16936
- files.push({
16937
- relPath: ".github/PULL_REQUEST_TEMPLATE.md",
16938
- content: STARTER_GITHUB_PULL_REQUEST_TEMPLATE
16939
- });
17986
+ files.push({ relPath: ".github/PULL_REQUEST_TEMPLATE.md", content: STARTER_GITHUB_PULL_REQUEST_TEMPLATE });
16940
17987
  }
16941
17988
  return files;
16942
17989
  }
@@ -17004,7 +18051,7 @@ function mergeDirectories(base, extra) {
17004
18051
  }
17005
18052
  return result;
17006
18053
  }
17007
- function buildInitSuccessResult(destDir, directoriesCreated, filesCreated, filesUpdated, ciProvider, agentsConfigured, architectureGranularity, gitHookInstalled) {
18054
+ function buildInitSuccessResult(destDir, directoriesCreated, filesCreated, filesUpdated, ciProvider, agentsConfigured, architectureGranularity, stacksConfigured, gitHookInstalled) {
17008
18055
  return {
17009
18056
  success: true,
17010
18057
  targetDir: destDir,
@@ -17014,6 +18061,7 @@ function buildInitSuccessResult(destDir, directoriesCreated, filesCreated, files
17014
18061
  ciProvider,
17015
18062
  agentsConfigured,
17016
18063
  architectureGranularity,
18064
+ stacksConfigured,
17017
18065
  gitHookInstalled
17018
18066
  };
17019
18067
  }
@@ -17024,182 +18072,37 @@ function validateInitOptions(options) {
17024
18072
  if (!archRes.valid) return { valid: false, archGranularity: "minimal", error: archRes.error };
17025
18073
  return { valid: true, ciProvider: ciRes.provider, archGranularity: archRes.granularity };
17026
18074
  }
17027
- function assembleScaffoldingPlan(ciProvider, agents, archGranularity) {
18075
+ function assembleScaffoldingPlan(ciProvider, agents, archGranularity, stacks = []) {
17028
18076
  const agentTargets = resolveAgentTargets(agents);
17029
18077
  const { dirs: agentDirs, files: agentFiles } = collectAgentFiles(agentTargets);
17030
18078
  const directories = mergeDirectories(getBaseDirectories(ciProvider), agentDirs);
17031
- const starterFiles = collectStarterFiles(ciProvider, agentFiles, archGranularity);
18079
+ const starterFiles = collectStarterFiles(ciProvider, agentFiles, archGranularity, stacks);
17032
18080
  return { agentTargets, directories, starterFiles };
17033
18081
  }
17034
- function initProject(options = {}) {
17035
- const destDir = path5__namespace.resolve(options.rootDir || process.cwd(), options.targetDir || ".");
17036
- const validated = validateInitOptions(options);
17037
- if (!validated.valid) return buildInitError(destDir, validated.error);
17038
- const { agentTargets, directories, starterFiles } = assembleScaffoldingPlan(
17039
- validated.ciProvider,
17040
- options.agents,
17041
- validated.archGranularity
17042
- );
18082
+ function executeScaffoldingOnDisk(destDir, options, ciProvider, archGranularity, stacks) {
18083
+ const { agentTargets, directories, starterFiles } = assembleScaffoldingPlan(ciProvider, options.agents, archGranularity, stacks);
17043
18084
  const dirsCreated = createDirectoriesOnDisk(destDir, directories, options.dryRun);
17044
18085
  const { filesCreated, filesUpdated } = writeProjectFiles(destDir, starterFiles, options.dryRun, options.force);
17045
- if (updateConsumerPackageJson(destDir, options.dryRun)) {
17046
- filesCreated.push("package.json");
17047
- }
18086
+ if (updateConsumerPackageJson(destDir, options.dryRun)) filesCreated.push("package.json");
17048
18087
  return buildInitSuccessResult(
17049
18088
  destDir,
17050
18089
  dirsCreated,
17051
18090
  filesCreated,
17052
18091
  filesUpdated,
17053
- validated.ciProvider,
18092
+ ciProvider,
17054
18093
  formatAgentsConfigured(agentTargets),
17055
- validated.archGranularity,
18094
+ archGranularity,
18095
+ stacks,
17056
18096
  tryInstallGitHook(destDir, options.dryRun)
17057
18097
  );
17058
18098
  }
17059
- var DEFAULT_DLP_RULES = [
17060
- {
17061
- id: "DLP-001-PRIVATE-KEY",
17062
- description: "PEM / RSA / EC / OPENSSH Private Key Block",
17063
- pattern: "-----BEGIN (?:[A-Z0-9_-]+ )?PRIVATE KEY-----[\\s\\S]*?-----END (?:[A-Z0-9_-]+ )?PRIVATE KEY-----",
17064
- replacement: "[REDACTED:PRIVATE_KEY]",
17065
- enabled: true
17066
- },
17067
- {
17068
- id: "DLP-002-API-TOKEN",
17069
- description: "Cloud, GitHub, Slack, OpenAI, Stripe, and AWS Access Tokens",
17070
- pattern: "\\b(?:gh[pousr]_[A-Za-z0-9_]{36,255}|github_pat_[0-9a-zA-Z_]{82}|sk-(?:proj-|live-)?[a-zA-Z0-9_-]{32,}|AKIA[0-9A-Z]{16}|xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*|(?:sk|rk)_(?:live|test)_[0-9a-zA-Z]{24,99})\\b",
17071
- replacement: "[REDACTED:API_TOKEN]",
17072
- enabled: true
17073
- },
17074
- {
17075
- id: "DLP-003-JWT",
17076
- description: "Plaintext JSON Web Token (JWT)",
17077
- pattern: "\\beyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\b",
17078
- replacement: "[REDACTED:JWT_TOKEN]",
17079
- enabled: true
17080
- },
17081
- {
17082
- id: "DLP-004-CREDIT-CARD",
17083
- description: "Payment Card Number (13-19 digits formatted)",
17084
- pattern: "\\b(?:\\d{4}[- ]\\d{4}[- ]\\d{4}[- ]\\d{4}|\\d{16})\\b",
17085
- replacement: "[REDACTED:CREDIT_CARD]",
17086
- enabled: true
17087
- },
17088
- {
17089
- id: "DLP-005-EMAIL",
17090
- description: "Personal or Corporate Email Address",
17091
- pattern: "\\b[A-Za-z0-9._%+-]+@(?!example\\.com|localhost|test\\.local)[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b",
17092
- replacement: "[REDACTED:EMAIL]",
17093
- enabled: true
17094
- },
17095
- {
17096
- id: "DLP-006-INTERNAL-URL",
17097
- description: "Internal Intranet / Corp Service URL",
17098
- pattern: "https?://(?:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+@|[A-Za-z0-9.-]+\\.(?:internal|corp|intranet|local)\\b)[^\\s\"'`<>]*",
17099
- replacement: "[REDACTED:INTERNAL_URL]",
17100
- enabled: true
17101
- }
17102
- ];
17103
- function createDefaultDlpPolicy() {
17104
- return {
17105
- version: "1.0",
17106
- enabled: true,
17107
- zero_data_retention_required: true,
17108
- rules: [...DEFAULT_DLP_RULES]
17109
- };
17110
- }
17111
- function normalizeParsedRule(raw, idx) {
17112
- if (typeof raw.pattern !== "string" || !raw.pattern) return null;
17113
- return {
17114
- id: typeof raw.id === "string" ? raw.id : `DLP-CUSTOM-${idx + 1}`,
17115
- description: typeof raw.description === "string" ? raw.description : "Custom DLP rule",
17116
- pattern: raw.pattern,
17117
- replacement: typeof raw.replacement === "string" ? raw.replacement : "[REDACTED]",
17118
- enabled: raw.enabled !== false
17119
- };
17120
- }
17121
- function parseDlpDoc(yamlContent) {
17122
- let doc;
17123
- try {
17124
- doc = yaml3__default.default.load(yamlContent);
17125
- } catch (err) {
17126
- throw new Error(`[AI-SDLC Fail-Closed] Invalid YAML in dlp-policy: ${err instanceof Error ? err.message : String(err)}`);
17127
- }
17128
- if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
17129
- throw new Error(`[AI-SDLC Fail-Closed] Invalid dlp-policy structure: root must be a YAML mapping`);
17130
- }
17131
- const record = doc;
17132
- if (record.rules !== void 0 && !Array.isArray(record.rules)) {
17133
- throw new Error(`[AI-SDLC Fail-Closed] Invalid dlp-policy: rules must be an array`);
17134
- }
17135
- return record;
17136
- }
17137
- function parseDlpPolicy(yamlContent) {
17138
- const fallback = createDefaultDlpPolicy();
17139
- if (!yamlContent || !yamlContent.trim()) return fallback;
17140
- const record = parseDlpDoc(yamlContent);
17141
- const rawRules = Array.isArray(record.rules) ? record.rules : [];
17142
- const parsedRules = rawRules.map((r, i) => normalizeParsedRule(r, i)).filter((r) => r !== null);
17143
- return {
17144
- version: typeof record.version === "string" ? record.version : "1.0",
17145
- enabled: record.enabled !== false,
17146
- zero_data_retention_required: Boolean(record.zero_data_retention_required ?? true),
17147
- rules: parsedRules.length > 0 ? parsedRules : fallback.rules
17148
- };
17149
- }
17150
- function loadDlpPolicy(rootDir, customPolicyPath) {
17151
- const base = rootDir || process.cwd();
17152
- const filePath = customPolicyPath ? path5__namespace.isAbsolute(customPolicyPath) ? customPolicyPath : path5__namespace.join(base, customPolicyPath) : path5__namespace.join(base, "dlp-policy.yaml");
17153
- if (!fs8__namespace.existsSync(filePath)) return createDefaultDlpPolicy();
17154
- return parseDlpPolicy(fs8__namespace.readFileSync(filePath, "utf-8"));
17155
- }
17156
- function applySingleDlpRule(text, rule) {
17157
- if (rule.enabled === false) return { output: text, matches: 0 };
17158
- try {
17159
- const regex = new RegExp(rule.pattern, "g");
17160
- let matches = 0;
17161
- const output = text.replace(regex, () => {
17162
- matches++;
17163
- return rule.replacement;
17164
- });
17165
- return { output, matches };
17166
- } catch {
17167
- return { output: text, matches: 0 };
17168
- }
17169
- }
17170
- function sanitizeDlpText(text, policy = createDefaultDlpPolicy()) {
17171
- if (!policy.enabled || !text) {
17172
- return { sanitizedText: text, redactionCount: 0, triggeredRuleIds: [] };
17173
- }
17174
- let current = text;
17175
- let totalRedactions = 0;
17176
- const triggered = [];
17177
- for (const rule of policy.rules) {
17178
- const res = applySingleDlpRule(current, rule);
17179
- if (res.matches > 0) {
17180
- current = res.output;
17181
- totalRedactions += res.matches;
17182
- triggered.push(rule.id);
17183
- }
17184
- }
17185
- return {
17186
- sanitizedText: current,
17187
- redactionCount: totalRedactions,
17188
- triggeredRuleIds: triggered
17189
- };
17190
- }
17191
- function sanitizeDlpPayload(payload, policy = createDefaultDlpPolicy()) {
17192
- if (!policy.enabled || payload === null || payload === void 0) return payload;
17193
- if (typeof payload === "string") {
17194
- return sanitizeDlpText(payload, policy).sanitizedText;
17195
- }
17196
- const serialized = JSON.stringify(payload);
17197
- const { sanitizedText } = sanitizeDlpText(serialized, policy);
17198
- try {
17199
- return JSON.parse(sanitizedText);
17200
- } catch {
17201
- return payload;
17202
- }
18099
+ function initProject(options = {}) {
18100
+ const destDir = path5__namespace.resolve(options.rootDir || process.cwd(), options.targetDir || ".");
18101
+ const validated = validateInitOptions(options);
18102
+ if (!validated.valid) return buildInitError(destDir, validated.error);
18103
+ const stackRes = resolveCodingRuleStacks(options.stack, destDir);
18104
+ if (!stackRes.valid) return buildInitError(destDir, stackRes.error);
18105
+ return executeScaffoldingOnDisk(destDir, options, validated.ciProvider, validated.archGranularity, stackRes.stacks);
17203
18106
  }
17204
18107
  var CITATION_REGEX = /\b(ARCH-INTRO|JRN|ACT-THREAT|ACT|UC|BR|BC|ABUSE|DATA-ASSET|PRIV-ROPA|HAZ|SEC-ENC|CMP|ADR|SEC-REQ|PRIV-REQ|FR|QR|CHG|TSK|HOF)-[A-Z0-9_-]+/g;
17205
18108
  function parseTasksFromDir(changeDirPath, rootDir) {
@@ -17667,13 +18570,20 @@ function formatInspectResultMarkdown(result) {
17667
18570
  exports.ALL_ARCHITECTURE_TEMPLATES = ALL_ARCHITECTURE_TEMPLATES;
17668
18571
  exports.BRANCH_PATTERNS = BRANCH_PATTERNS;
17669
18572
  exports.BddStepRegistry = BddStepRegistry;
18573
+ exports.CPP_CLANG_TIDY = CPP_CLANG_TIDY;
18574
+ exports.CPP_CMAKE_STRICT = CPP_CMAKE_STRICT;
17670
18575
  exports.DEFAULT_DLP_RULES = DEFAULT_DLP_RULES;
17671
18576
  exports.DEFAULT_EXCLUDED_PATTERNS = DEFAULT_EXCLUDED_PATTERNS;
17672
18577
  exports.DEFAULT_EXCLUDES = DEFAULT_EXCLUDES;
17673
18578
  exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
17674
18579
  exports.DEFAULT_PRIVACY_POLICY = DEFAULT_PRIVACY_POLICY;
17675
18580
  exports.DEFAULT_SAST_EXCLUDES = DEFAULT_SAST_EXCLUDES;
18581
+ exports.DOTNET_DIRECTORY_BUILD_PROPS = DOTNET_DIRECTORY_BUILD_PROPS;
17676
18582
  exports.GENERAL_SOURCE_EXTENSIONS = GENERAL_SOURCE_EXTENSIONS;
18583
+ exports.GO_GOLANGCI_YML = GO_GOLANGCI_YML;
18584
+ exports.GRADLE_STRICT_INIT_KTS = GRADLE_STRICT_INIT_KTS;
18585
+ exports.JAVA_PMD_RULESET_XML = JAVA_PMD_RULESET_XML;
18586
+ exports.KOTLIN_DETEKT_YML = KOTLIN_DETEKT_YML;
17677
18587
  exports.KPI_SUMMARY_END_TAG = KPI_SUMMARY_END_TAG;
17678
18588
  exports.KPI_SUMMARY_START_TAG = KPI_SUMMARY_START_TAG;
17679
18589
  exports.LIFECYCLE_SKILL_TEMPLATES = LIFECYCLE_SKILL_TEMPLATES;
@@ -17683,6 +18593,11 @@ exports.PREPARE_COMMIT_MSG_SCRIPT = PREPARE_COMMIT_MSG_SCRIPT;
17683
18593
  exports.PRE_COMMIT_SCRIPT = PRE_COMMIT_SCRIPT;
17684
18594
  exports.PROMPT_INJECTION_SIGNATURES = PROMPT_INJECTION_SIGNATURES;
17685
18595
  exports.PROTECTED_BYPASS_PATTERNS = PROTECTED_BYPASS_PATTERNS;
18596
+ exports.PROTECTED_CODING_RULES_FILES = PROTECTED_CODING_RULES_FILES;
18597
+ exports.REVIEWER_ROLES = REVIEWER_ROLES;
18598
+ exports.REVIEW_VERDICTS = REVIEW_VERDICTS;
18599
+ exports.RUST_CARGO_CONFIG_TOML = RUST_CARGO_CONFIG_TOML;
18600
+ exports.RUST_CLIPPY_TOML = RUST_CLIPPY_TOML;
17686
18601
  exports.SARIF_SCHEMA_2_1_0 = SARIF_SCHEMA_2_1_0;
17687
18602
  exports.SARIF_VERSION = SARIF_VERSION;
17688
18603
  exports.SAST_RULES = SAST_RULES;
@@ -17722,6 +18637,8 @@ exports.SCHEMA_SCHEMAS_SECURITY_THREAT_ACTOR_SCHEMA_JSON = SCHEMA_SCHEMAS_SECURI
17722
18637
  exports.SCHEMA_SCHEMAS_WORKFLOW_AGENT_HANDOFF_SCHEMA_JSON = SCHEMA_SCHEMAS_WORKFLOW_AGENT_HANDOFF_SCHEMA_JSON;
17723
18638
  exports.SECRET_RULES = SECRET_RULES;
17724
18639
  exports.SPECIALIZED_AGENT_TEMPLATES = SPECIALIZED_AGENT_TEMPLATES;
18640
+ exports.STARTER_AGENT_GUARD_WRAPPER_CJS = STARTER_AGENT_GUARD_WRAPPER_CJS;
18641
+ exports.STARTER_ANTIGRAVITY_HOOKS_JSON = STARTER_ANTIGRAVITY_HOOKS_JSON;
17725
18642
  exports.STARTER_ANTIGRAVITY_MCP = STARTER_ANTIGRAVITY_MCP;
17726
18643
  exports.STARTER_ANTIGRAVITY_RULES = STARTER_ANTIGRAVITY_RULES;
17727
18644
  exports.STARTER_ARCH_ADR = STARTER_ARCH_ADR;
@@ -17753,6 +18670,7 @@ exports.STARTER_GITHUB_PR_KPI = STARTER_GITHUB_PR_KPI;
17753
18670
  exports.STARTER_GITHUB_PULL_REQUEST_TEMPLATE = STARTER_GITHUB_PULL_REQUEST_TEMPLATE;
17754
18671
  exports.STARTER_GITHUB_SDD_INTEGRATE = STARTER_GITHUB_SDD_INTEGRATE;
17755
18672
  exports.STARTER_GITLAB_CI = STARTER_GITLAB_CI;
18673
+ exports.STARTER_GUARD_BRANCH_CJS = STARTER_GUARD_BRANCH_CJS;
17756
18674
  exports.STARTER_LICENSE_POLICY = STARTER_LICENSE_POLICY;
17757
18675
  exports.STARTER_PRIVACY_POLICY = STARTER_PRIVACY_POLICY;
17758
18676
  exports.STARTER_PROCESS_README = STARTER_PROCESS_README;
@@ -17801,6 +18719,8 @@ exports.STARTER_VSCODE_MCP = STARTER_VSCODE_MCP;
17801
18719
  exports.STARTER_WORKFLOW_HANDOFF_TEMPLATE = STARTER_WORKFLOW_HANDOFF_TEMPLATE;
17802
18720
  exports.STARTER__GITHUB_PULL_REQUEST_TEMPLATE_MD = STARTER__GITHUB_PULL_REQUEST_TEMPLATE_MD;
17803
18721
  exports.SpecKitAdapter = SpecKitAdapter;
18722
+ exports.TS_ESLINT_CONFIG_MJS = TS_ESLINT_CONFIG_MJS;
18723
+ exports.TS_STRICT_TSCONFIG = TS_STRICT_TSCONFIG;
17804
18724
  exports.TYPE_TO_SCHEMA_MAP = TYPE_TO_SCHEMA_MAP;
17805
18725
  exports.UNIT_TEST_SUFFIXES = UNIT_TEST_SUFFIXES;
17806
18726
  exports.VALID_AGENT_TARGETS = VALID_AGENT_TARGETS;
@@ -17808,6 +18728,7 @@ exports.VALID_ARCHITECTURE_GRANULARITIES = VALID_ARCHITECTURE_GRANULARITIES;
17808
18728
  exports.VALID_AUTONOMY_MODES = VALID_AUTONOMY_MODES;
17809
18729
  exports.VALID_CHANGE_PROFILES = VALID_CHANGE_PROFILES;
17810
18730
  exports.VALID_CI_PROVIDERS = VALID_CI_PROVIDERS;
18731
+ exports.VALID_CODING_RULE_STACKS = VALID_CODING_RULE_STACKS;
17811
18732
  exports.aggregateCommitKpiRecords = aggregateCommitKpiRecords;
17812
18733
  exports.aggregatePrKpis = aggregatePrKpis;
17813
18734
  exports.aggregateReleaseKpis = aggregateReleaseKpis;
@@ -17841,12 +18762,14 @@ exports.detectActiveChangeForIntegration = detectActiveChangeForIntegration;
17841
18762
  exports.detectAuthorIdentity = detectAuthorIdentity;
17842
18763
  exports.detectLanguage = detectLanguage;
17843
18764
  exports.detectProfileFromChange = detectProfileFromChange;
18765
+ exports.detectProjectStacks = detectProjectStacks;
17844
18766
  exports.detectPromptInjection = detectPromptInjection;
17845
18767
  exports.emitCiOutput = emitCiOutput;
17846
18768
  exports.evaluateCompoundLicense = evaluateCompoundLicense;
17847
18769
  exports.evaluateSingleDependency = evaluateSingleDependency;
17848
18770
  exports.evaluateVulnerabilityThresholds = evaluateVulnerabilityThresholds;
17849
18771
  exports.executeBddFeature = executeBddFeature;
18772
+ exports.extractAllRepoCommitKpis = extractAllRepoCommitKpis;
17850
18773
  exports.extractBaselineEntriesFromResults = extractBaselineEntriesFromResults;
17851
18774
  exports.extractCitations = extractCitations;
17852
18775
  exports.extractCommitKpisFromRange = extractCommitKpisFromRange;
@@ -17889,9 +18812,11 @@ exports.generateTestingCoverageReportMarkdown = generateTestingCoverageReportMar
17889
18812
  exports.generateThirdPartyNotices = generateThirdPartyNotices;
17890
18813
  exports.generateTraceabilityReportMarkdown = generateTraceabilityReportMarkdown;
17891
18814
  exports.getArchitectureTemplates = getArchitectureTemplates;
18815
+ exports.getCodingRulesFilesForStacks = getCodingRulesFilesForStacks;
17892
18816
  exports.getCytoscapeScript = getCytoscapeScript;
17893
18817
  exports.getGitDiffLines = getGitDiffLines;
17894
18818
  exports.getNextCorrelativeNumber = getNextCorrelativeNumber;
18819
+ exports.getReferenceCodingRulesTemplates = getReferenceCodingRulesTemplates;
17895
18820
  exports.getSddAdapter = getSddAdapter;
17896
18821
  exports.inferArtifactTypeFromId = inferArtifactTypeFromId;
17897
18822
  exports.inferMissingTrailers = inferMissingTrailers;
@@ -17906,8 +18831,10 @@ exports.isGitleaksInstalled = isGitleaksInstalled;
17906
18831
  exports.isMetricWorsened = isMetricWorsened;
17907
18832
  exports.isPathProtectedFromPatch = isPathProtectedFromPatch;
17908
18833
  exports.isPlaceholderOrIgnored = isPlaceholderOrIgnored;
18834
+ exports.isProtectedCodingRulesFile = isProtectedCodingRulesFile;
17909
18835
  exports.isReportContentSemanticallyEqual = isReportContentSemanticallyEqual;
17910
18836
  exports.isRequirementArtifact = isRequirementArtifact2;
18837
+ exports.isReviewerRole = isReviewerRole;
17911
18838
  exports.isSemgrepInstalled = isSemgrepInstalled;
17912
18839
  exports.isToolAvailable = isToolAvailable;
17913
18840
  exports.loadDlpPolicy = loadDlpPolicy;
@@ -17953,6 +18880,7 @@ exports.renderManualsTab = renderManualsTab;
17953
18880
  exports.resolveAgentTargets = resolveAgentTargets;
17954
18881
  exports.resolveBranchHierarchy = resolveBranchHierarchy;
17955
18882
  exports.resolveCiEnvironment = resolveCiEnvironment;
18883
+ exports.resolveCodingRuleStacks = resolveCodingRuleStacks;
17956
18884
  exports.resolveCytoscapePath = resolveCytoscapePath;
17957
18885
  exports.resolveDefaultBranchBase = resolveDefaultBranchBase;
17958
18886
  exports.resolveDeterministicDate = resolveDeterministicDate;
@@ -17989,6 +18917,7 @@ exports.scanWithTrivy = scanWithTrivy;
17989
18917
  exports.serializeSarifDocument = serializeSarifDocument;
17990
18918
  exports.slugify = slugify2;
17991
18919
  exports.stripVolatileReportMetadata = stripVolatileReportMetadata;
18920
+ exports.submitReviewReport = submitReviewReport;
17992
18921
  exports.syncPdacDigests = syncPdacDigests;
17993
18922
  exports.tokenizeTitle = tokenizeTitle;
17994
18923
  exports.updateCitationsInContent = updateCitationsInContent;