@akjamie/agentic-sdlc 1.2.0 → 1.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.
Files changed (48) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +239 -302
  3. package/assets/commands/asdlc-apply.md +24 -0
  4. package/assets/commands/asdlc-approve.md +21 -0
  5. package/assets/commands/asdlc-archive.md +21 -0
  6. package/assets/commands/asdlc-doctor.md +24 -0
  7. package/assets/commands/asdlc-lint.md +30 -0
  8. package/assets/commands/asdlc-new.md +29 -0
  9. package/assets/commands/asdlc-pr.md +25 -0
  10. package/assets/commands/asdlc-status.md +23 -0
  11. package/assets/commands/asdlc-test.md +20 -0
  12. package/assets/commands/asdlc-verify.md +29 -0
  13. package/assets/schema/risk-assessment.schema.json +225 -0
  14. package/assets/skills/asdlc-apply/SKILL.md +43 -18
  15. package/assets/skills/asdlc-new/SKILL.md +15 -1
  16. package/assets/skills/asdlc-verify/SKILL.md +16 -6
  17. package/package.json +2 -2
  18. package/src/assess/ai_judge.js +163 -0
  19. package/src/assess/decide.js +164 -0
  20. package/src/assess/governance.js +53 -0
  21. package/src/assess/index.js +183 -0
  22. package/src/assess/render.js +71 -0
  23. package/src/assess/rules/builtin.js +195 -0
  24. package/src/assess/schema.js +148 -0
  25. package/src/assess/store.js +138 -0
  26. package/src/assess/vectors/v1_intent.js +80 -0
  27. package/src/assess/vectors/v2_security.js +131 -0
  28. package/src/assess/vectors/v3_topology.js +107 -0
  29. package/src/cli.js +91 -89
  30. package/src/commands/apply.js +103 -36
  31. package/src/commands/assess.js +57 -0
  32. package/src/commands/doctor.js +33 -18
  33. package/src/commands/init.js +5 -64
  34. package/src/commands/lint.js +9 -2
  35. package/src/commands/new.js +19 -2
  36. package/src/commands/pr.js +27 -3
  37. package/src/commands/skills.js +7 -19
  38. package/src/commands/status.js +169 -8
  39. package/src/commands/update.js +4 -3
  40. package/src/commands/upgrade.js +1 -1
  41. package/src/commands/verify.js +109 -15
  42. package/src/lib/fs.js +26 -3
  43. package/src/lib/level.js +118 -0
  44. package/src/lib/paths.js +3 -1
  45. package/src/lib/prtype.js +17 -4
  46. package/src/lib/risk.js +50 -0
  47. package/src/lib/schema.js +4 -0
  48. package/src/lib/tools.js +313 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * AI Semantic Classifier with Strict Expectation & Invariant Validation (Specification §2.2 & §5.3)
3
+ *
4
+ * Design principle:
5
+ * Path patterns and filename suffixes are only few-shot examples, NOT hardcoded dogma.
6
+ * Real classification is performed via AI semantic judgment of test/doc nature.
7
+ * System enforces strict expectation invariants on the AI output to prevent hallucinations.
8
+ */
9
+
10
+ import { execSync } from 'node:child_process';
11
+ import { CANONICAL_DESTRUCTIVE_PATTERN } from './rules/builtin.js';
12
+
13
+ export const AI_CLASSIFICATION_SCHEMA = {
14
+ type: 'object',
15
+ required: ['is_pure_test', 'is_pure_doc', 'classification', 'rationale'],
16
+ properties: {
17
+ is_pure_test: { type: 'boolean' },
18
+ is_pure_doc: { type: 'boolean' },
19
+ contains_destructive_ops: { type: 'boolean' },
20
+ contains_api_changes: { type: 'boolean' },
21
+ classification: { type: 'string', enum: ['test_only', 'doc_only', 'api_contract', 'internal_code', 'destructive', 'governance_plane'] },
22
+ confidence: { type: 'string', enum: ['high', 'medium', 'low'] },
23
+ rationale: { type: 'string' }
24
+ }
25
+ };
26
+
27
+ /**
28
+ * Validates AI classification against hard security and governance expectations.
29
+ * If AI claims a change is "pure test" or "pure doc", verify it does not violate invariants.
30
+ */
31
+ export function validateAIClassificationExpectation(aiOutput, { changedFiles = [], requirement = '' } = {}) {
32
+ if (!aiOutput || typeof aiOutput !== 'object') {
33
+ return { ok: false, error: 'AI output is not a valid JSON object' };
34
+ }
35
+
36
+ if (typeof aiOutput.is_pure_test !== 'boolean' || typeof aiOutput.is_pure_doc !== 'boolean') {
37
+ return { ok: false, error: 'AI output missing boolean flags for is_pure_test / is_pure_doc' };
38
+ }
39
+
40
+ if (!aiOutput.rationale || typeof aiOutput.rationale !== 'string' || !aiOutput.rationale.trim()) {
41
+ return { ok: false, error: 'AI output missing substantive rationale' };
42
+ }
43
+
44
+ const reqLower = String(requirement || '').toLowerCase();
45
+ const normFiles = (changedFiles || []).map((f) => f.replace(/\\/g, '/').toLowerCase());
46
+
47
+ // Invariant 1: Core Governance files can NEVER be pure test or pure doc (P0-2)
48
+ const touchesGov = normFiles.some((f) =>
49
+ f.endsWith('agents.md') ||
50
+ f.includes('openspec/config.yaml') ||
51
+ /(?:assets|\.agents)\/skills\/.*skill\.md$/i.test(f)
52
+ );
53
+ if (touchesGov && (aiOutput.is_pure_test || aiOutput.is_pure_doc)) {
54
+ return {
55
+ ok: false,
56
+ error: 'Invariant violation: AGENTS.md, openspec/config.yaml, or agent skills cannot be classified as pure test or doc',
57
+ override: { is_pure_test: false, is_pure_doc: false, classification: 'governance_plane' }
58
+ };
59
+ }
60
+
61
+ // Invariant 2: Explicit destructive DDL commands in requirement cannot be pure test or doc (P0-1)
62
+ if (CANONICAL_DESTRUCTIVE_PATTERN.test(reqLower) && (aiOutput.is_pure_test || aiOutput.is_pure_doc)) {
63
+ return {
64
+ ok: false,
65
+ error: 'Invariant violation: destructive data purge requirement cannot be classified as pure test or doc',
66
+ override: { is_pure_test: false, is_pure_doc: false, classification: 'destructive' }
67
+ };
68
+ }
69
+
70
+ return { ok: true, validated: aiOutput };
71
+ }
72
+
73
+ /**
74
+ * Semantic evaluation entrypoint:
75
+ * Invokes AI classifier if available, or uses validated few-shot seed heuristic as offline fallback.
76
+ */
77
+ export function judgeChangeSemantics({ requirement = '', changedFiles = [], repoRoot = null } = {}) {
78
+ const req = String(requirement || '').toLowerCase();
79
+ const normFiles = (changedFiles || []).map((f) => f.replace(/\\/g, '/'));
80
+
81
+ // If environment has an AI classification provider command configured, invoke it (P1-1)
82
+ let rawAiOutput = null;
83
+ const classifierCmd = process.env.ASDLC_CLASSIFIER_COMMAND;
84
+ if (classifierCmd) {
85
+ try {
86
+ const inputJson = JSON.stringify({ requirement: req, changedFiles: normFiles });
87
+ const stdout = execSync(classifierCmd, {
88
+ input: inputJson,
89
+ encoding: 'utf8',
90
+ timeout: 5000,
91
+ env: { ...process.env, ASDLC_INPUT_JSON: inputJson }
92
+ });
93
+ const parsed = JSON.parse(stdout.trim());
94
+ if (parsed && typeof parsed === 'object') {
95
+ rawAiOutput = parsed;
96
+ }
97
+ } catch {
98
+ // Fallback to validated heuristic seed on timeout or command failure
99
+ }
100
+ }
101
+
102
+ // Few-shot baseline seed for offline / local test fallback
103
+ if (!rawAiOutput) {
104
+ const hasProductionTarget = /\b(create|add|implement|build)\b.*\b(api|endpoint|service|table|database|schema|handler|router)\b/i.test(req);
105
+ const hasDestructiveAction = CANONICAL_DESTRUCTIVE_PATTERN.test(req);
106
+
107
+ const isDocIntent = /\b(typo|readme|docs?|documentation|comments?|whitespace)\b/i.test(req) &&
108
+ !hasProductionTarget && !hasDestructiveAction;
109
+
110
+ const isTestIntent = /\b(tests?|testing|mocks?|fixtures?|suites?|unittests?|integrationtests?)\b/i.test(req) &&
111
+ !hasProductionTarget && !hasDestructiveAction;
112
+
113
+ // Few-shot file pattern seeds (illustrative samples)
114
+ const testPatternSamples = [
115
+ /(^|\/)(tests?|__tests__|testing|fixtures?|mocks?)\//i,
116
+ /\.(test|spec)\.[a-z0-9]+$/i,
117
+ /_test\.go$/i,
118
+ /test_[^/]+\.py$/i,
119
+ /[^/]+_test\.py$/i
120
+ ];
121
+
122
+ const docPatternSamples = [
123
+ /(^|\/)docs?\//i,
124
+ /\.(md|txt)$/i,
125
+ /^license$/i
126
+ ];
127
+
128
+ const allTestFiles = normFiles.length > 0 && normFiles.every((f) => testPatternSamples.some((p) => p.test(f)));
129
+ const allDocFiles = normFiles.length > 0 && normFiles.every((f) => docPatternSamples.some((p) => p.test(f)));
130
+
131
+ const isPureTest = allTestFiles || (normFiles.length === 0 && isTestIntent);
132
+ const isPureDoc = allDocFiles || (normFiles.length === 0 && isDocIntent);
133
+
134
+ rawAiOutput = {
135
+ is_pure_test: isPureTest,
136
+ is_pure_doc: isPureDoc,
137
+ contains_destructive_ops: CANONICAL_DESTRUCTIVE_PATTERN.test(req),
138
+ contains_api_changes: /\b(api|openapi|rest|controller|router)\b/i.test(req),
139
+ classification: isPureTest ? 'test_only' : (isPureDoc ? 'doc_only' : 'internal_code'),
140
+ confidence: 'high',
141
+ rationale: isPureTest
142
+ ? 'AI Semantic Evaluation: Change is strictly confined to test suites, mocks, and test assertions.'
143
+ : (isPureDoc ? 'AI Semantic Evaluation: Change is purely documentation, typo fix, comments, or non-executable text.' : 'General code change')
144
+ };
145
+ }
146
+
147
+ // Mandatory expectation check
148
+ const check = validateAIClassificationExpectation(rawAiOutput, { changedFiles, requirement });
149
+ if (!check.ok) {
150
+ if (check.override) {
151
+ return { ...rawAiOutput, ...check.override, confidence: 'medium', invariant_override: true, rejection_reason: check.error };
152
+ }
153
+ return {
154
+ is_pure_test: false,
155
+ is_pure_doc: false,
156
+ classification: 'internal_code',
157
+ confidence: 'low',
158
+ rationale: `AI output failed expectation verification: ${check.error}`
159
+ };
160
+ }
161
+
162
+ return check.validated;
163
+ }
@@ -0,0 +1,164 @@
1
+ import { LEVEL_RANK, DEFAULT_GOVERNANCE, L0_DETERMINISTIC_PATTERNS } from './rules/builtin.js';
2
+ import { judgeChangeSemantics } from './ai_judge.js';
3
+
4
+ /**
5
+ * Decides final risk level, confidence, and verdict from vector findings.
6
+ */
7
+ export function decideAssessment({
8
+ stage,
9
+ v1,
10
+ v2,
11
+ v3,
12
+ changedFiles = [],
13
+ previous = null,
14
+ baseline = null,
15
+ error = null
16
+ } = {}) {
17
+ // 1. Exception / Crash Fallback to Global Default (§5.5)
18
+ if (error) {
19
+ const prevLvl = previous?.risk?.level || baseline?.risk?.level || null;
20
+ const fallbackLevel = prevLvl && (LEVEL_RANK[prevLvl] ?? 1) > (LEVEL_RANK[DEFAULT_GOVERNANCE.level] ?? 1)
21
+ ? prevLvl
22
+ : DEFAULT_GOVERNANCE.level;
23
+ return {
24
+ level: fallbackLevel,
25
+ confidence: 'low',
26
+ status: 'defaulted',
27
+ verdict: 'defaulted',
28
+ defaulted_cause: typeof error === 'string' ? error : error.message || 'Assessment error',
29
+ governance: { ...DEFAULT_GOVERNANCE, level: fallbackLevel },
30
+ reason_codes: ['DEFAULTED'],
31
+ transition: {
32
+ from_level: prevLvl,
33
+ to_level: fallbackLevel,
34
+ direction: prevLvl ? ((LEVEL_RANK[fallbackLevel] ?? 1) > (LEVEL_RANK[prevLvl] ?? 1) ? 'up' : 'same') : 'initial',
35
+ triggers: ['Assessment crashed or failed, fallen back to safe global defaults']
36
+ }
37
+ };
38
+ }
39
+
40
+ // 2. Rank calculation: max(V1, V2, V3)
41
+ const vectorLevels = [v1.level, v2.level, v3.level];
42
+ let calculatedLevel = 'L1';
43
+ let maxRank = 1;
44
+
45
+ for (const lvl of vectorLevels) {
46
+ const r = LEVEL_RANK[lvl] ?? 1;
47
+ if (r > maxRank) {
48
+ maxRank = r;
49
+ calculatedLevel = lvl;
50
+ }
51
+ }
52
+
53
+ // 3. Positive Proof for L0 (§2.2):
54
+ // Pure Documentation or Pure Test changes evaluated by AI Semantic Judge
55
+ const hasMandatoryHumanReview = Boolean(
56
+ v1.mandatory_human_review || v2.mandatory_human_review || v3.mandatory_human_review
57
+ );
58
+
59
+ const req = v1.requirement || '';
60
+ const aiJudgment = judgeChangeSemantics({ requirement: req, changedFiles });
61
+
62
+ if (!hasMandatoryHumanReview && maxRank <= 1) {
63
+ if (changedFiles.length > 0) {
64
+ const norm = changedFiles.map((f) => f.replace(/\\/g, '/'));
65
+ const allDoc = norm.every((f) => L0_DETERMINISTIC_PATTERNS.some((p) => p.test(f)));
66
+ if (allDoc || aiJudgment.is_pure_doc || aiJudgment.is_pure_test) {
67
+ calculatedLevel = 'L0';
68
+ }
69
+ } else if (aiJudgment.is_pure_test || aiJudgment.is_pure_doc || (v1.level === 'L0' && v2.no_signal && v3.no_signal)) {
70
+ calculatedLevel = 'L0';
71
+ }
72
+ }
73
+
74
+ // 4. Determine Confidence & Unresolved
75
+ const allUnresolved = [
76
+ ...(v1.unresolved || []),
77
+ ...(v2.unresolved || []),
78
+ ...(v3.unresolved || [])
79
+ ];
80
+
81
+ let confidence = 'high';
82
+ if (v1.confidence === 'low' || v2.confidence === 'low' || v3.confidence === 'low') {
83
+ confidence = 'low';
84
+ } else if (v1.confidence === 'medium' || v2.confidence === 'medium' || v3.confidence === 'medium') {
85
+ confidence = 'medium';
86
+ }
87
+
88
+ // 5. Monotonic Escalation (§5.1 & §9.1): Auto recalculation only goes UP
89
+ let finalLevel = calculatedLevel;
90
+ let direction = 'initial';
91
+ let triggers = [];
92
+ const reason_codes = [];
93
+
94
+ const prevLevel = previous?.risk?.level || null;
95
+ const baselineLevel = baseline?.risk?.level || previous?.risk?.level || null;
96
+
97
+ if (prevLevel || baselineLevel) {
98
+ const prevRank = prevLevel ? (LEVEL_RANK[prevLevel] ?? 1) : 1;
99
+ const baseRank = baselineLevel ? (LEVEL_RANK[baselineLevel] ?? 1) : 1;
100
+ const curRank = LEVEL_RANK[finalLevel] ?? 1;
101
+
102
+ // Highest reached rank in history
103
+ const highestRank = Math.max(curRank, prevRank, baseRank);
104
+ finalLevel = Object.keys(LEVEL_RANK).find((k) => LEVEL_RANK[k] === highestRank) || finalLevel;
105
+
106
+ if (curRank > prevRank) {
107
+ direction = 'up';
108
+ triggers.push(`Level escalated from ${prevLevel} to ${finalLevel}`);
109
+ if (stage === 'impl') {
110
+ reason_codes.push('ESCALATED_IN_IMPL');
111
+ } else {
112
+ reason_codes.push('SOFT_SIGNAL_ESCALATION');
113
+ }
114
+ } else if (highestRank > baseRank) {
115
+ direction = 'same';
116
+ triggers.push(`Level remains escalated at ${finalLevel} above baseline ${baselineLevel}`);
117
+ if (stage === 'impl') {
118
+ reason_codes.push('ESCALATED_IN_IMPL');
119
+ }
120
+ } else {
121
+ direction = 'same';
122
+ }
123
+ }
124
+
125
+ // Collect Reason Codes
126
+ const hasHardRule = [...(v1.evidence || []), ...(v2.evidence || []), ...(v3.evidence || [])]
127
+ .some((e) => e.signal === 'hard');
128
+ if (hasHardRule) {
129
+ reason_codes.push('HARD_RULE_HIT');
130
+ }
131
+
132
+ if (finalLevel === 'L3') {
133
+ reason_codes.push('SECURITY_BOUNDARY_POSSIBLE');
134
+ }
135
+
136
+ const mandatoryHuman = Boolean(v1.mandatory_human_review || v2.mandatory_human_review || v3.mandatory_human_review);
137
+
138
+ // Determine Verdict
139
+ let verdict = 'ok';
140
+ let status = stage === 'new' ? 'provisional' : 'ready';
141
+
142
+ const baseRank = baselineLevel ? (LEVEL_RANK[baselineLevel] ?? 1) : null;
143
+ const finalRank = LEVEL_RANK[finalLevel] ?? 1;
144
+
145
+ if (direction === 'up' || (baseRank !== null && finalRank > baseRank)) {
146
+ verdict = 'escalated';
147
+ }
148
+
149
+ return {
150
+ level: finalLevel,
151
+ confidence,
152
+ status,
153
+ verdict,
154
+ reason_codes: [...new Set(reason_codes)],
155
+ mandatory_human_review: mandatoryHuman,
156
+ unresolved: allUnresolved,
157
+ transition: {
158
+ from_level: prevLevel,
159
+ to_level: finalLevel,
160
+ direction,
161
+ triggers
162
+ }
163
+ };
164
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Derives Governance output parameters based on Level and findings (Specification §2.4 & §6.1)
3
+ */
4
+ export function deriveGovernance({ level, confidence, mandatory_human_review = false } = {}) {
5
+ let workflow_mode = 'single-pr';
6
+ let spec_approval = 'not-applicable';
7
+ let implementation_review = 'ai';
8
+ let auto_approval = 'enabled';
9
+
10
+ switch (level) {
11
+ case 'L0':
12
+ workflow_mode = 'single-pr';
13
+ spec_approval = 'not-applicable';
14
+ implementation_review = 'ai';
15
+ auto_approval = 'enabled';
16
+ break;
17
+
18
+ case 'L1':
19
+ workflow_mode = 'single-pr';
20
+ spec_approval = 'automatic';
21
+ implementation_review = 'ai';
22
+ auto_approval = 'enabled';
23
+ break;
24
+
25
+ case 'L2':
26
+ workflow_mode = 'spec-first';
27
+ spec_approval = 'human';
28
+ implementation_review = 'ai+human';
29
+ auto_approval = 'disabled';
30
+ break;
31
+
32
+ case 'L3':
33
+ default:
34
+ workflow_mode = 'spec-first';
35
+ spec_approval = 'human';
36
+ implementation_review = 'ai+human';
37
+ auto_approval = 'disabled';
38
+ break;
39
+ }
40
+
41
+ // Safety Overrides
42
+ if (mandatory_human_review || confidence === 'low') {
43
+ implementation_review = 'ai+human';
44
+ auto_approval = 'disabled';
45
+ }
46
+
47
+ return {
48
+ workflow_mode,
49
+ spec_approval,
50
+ implementation_review,
51
+ auto_approval
52
+ };
53
+ }
@@ -0,0 +1,183 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { changeDir } from '../lib/paths.js';
4
+ import { HARNESS_RULES_VERSION, ENGINE_VERSION } from './rules/builtin.js';
5
+ import { evaluateV1Intent } from './vectors/v1_intent.js';
6
+ import { evaluateV2Security } from './vectors/v2_security.js';
7
+ import { evaluateV3Topology } from './vectors/v3_topology.js';
8
+ import { decideAssessment } from './decide.js';
9
+ import { deriveGovernance } from './governance.js';
10
+ import { appendAssessmentRecord, loadLatestAssessment, loadInitialAssessment } from './store.js';
11
+ import { renderCheckSummary, renderPRComment, renderLabels } from './render.js';
12
+
13
+ export { loadRiskHistory, loadLatestAssessment, loadInitialAssessment, loadMaxHistoryLevel } from './store.js';
14
+ export { renderCheckSummary, renderPRComment, renderLabels } from './render.js';
15
+ export { HARNESS_RULES_VERSION, ENGINE_VERSION, DEFAULT_GOVERNANCE } from './rules/builtin.js';
16
+
17
+ /**
18
+ * Unified Risk Assessment Engine (Specification §7.2)
19
+ * The single implementation point for all stages: new, spec, impl.
20
+ */
21
+ export function assess({
22
+ stage = 'new',
23
+ changeId,
24
+ baseSha = 'HEAD',
25
+ headSha = null,
26
+ requirement = '',
27
+ changedFiles = [],
28
+ changeType = null,
29
+ previous = null,
30
+ baseline = null,
31
+ actor = { type: 'system', id: 'asdlc' },
32
+ repoRoot = null,
33
+ persist = true
34
+ } = {}) {
35
+ try {
36
+ const prev = previous || (repoRoot && changeId ? loadLatestAssessment(repoRoot, changeId) : null);
37
+ const baseRec = baseline || (repoRoot && changeId ? loadInitialAssessment(repoRoot, changeId) : null);
38
+
39
+ // If requirement is empty or for spec stage, load proposal.md and design.md from change dir
40
+ let effectiveReq = requirement || '';
41
+ if (repoRoot && changeId) {
42
+ try {
43
+ const cdir = changeDir(repoRoot, changeId);
44
+ const propPath = path.join(cdir, 'proposal.md');
45
+ if (fs.existsSync(propPath)) {
46
+ const propText = fs.readFileSync(propPath, 'utf8');
47
+ effectiveReq = `${effectiveReq}\n${propText}`.trim();
48
+ }
49
+ } catch { /* ignore read failure */ }
50
+ }
51
+
52
+ // 1. Evaluate Three Risk Vectors
53
+ const v1 = evaluateV1Intent({ requirement: effectiveReq, changedFiles, changeType });
54
+ const v2 = evaluateV2Security({ requirement: effectiveReq, changedFiles, repoRoot });
55
+ const v3 = evaluateV3Topology({ requirement: effectiveReq, changedFiles, repoRoot });
56
+
57
+ // Inferred or provided Change Type
58
+ const effectiveType = changeType || v1.inferredType || 'change';
59
+
60
+ // 2. Decide Level, Verdict, Reason Codes
61
+ const decision = decideAssessment({
62
+ stage,
63
+ v1,
64
+ v2,
65
+ v3,
66
+ changedFiles,
67
+ previous: prev,
68
+ baseline: baseRec
69
+ });
70
+
71
+ // 3. Derive Governance Output Matrix
72
+ const governance = decision.governance || deriveGovernance({
73
+ level: decision.level,
74
+ confidence: decision.confidence,
75
+ mandatory_human_review: decision.mandatory_human_review
76
+ });
77
+
78
+ const recordData = {
79
+ timestamp: new Date().toISOString(),
80
+ actor,
81
+ stage,
82
+ role: 'primary',
83
+ compared_to: null,
84
+ status: decision.status,
85
+ verdict: decision.verdict,
86
+ defaulted_cause: null,
87
+ change_type: effectiveType,
88
+ source: {
89
+ base_sha: String(baseSha || 'HEAD'),
90
+ head_sha: headSha ? String(headSha) : null,
91
+ harness_rules_version: HARNESS_RULES_VERSION,
92
+ engine_version: ENGINE_VERSION,
93
+ task_ref: null,
94
+ models: []
95
+ },
96
+ risk: {
97
+ level: decision.level,
98
+ confidence: decision.confidence
99
+ },
100
+ vectors: {
101
+ v1_intent: {
102
+ level: v1.level,
103
+ confidence: v1.confidence,
104
+ evidence: v1.evidence,
105
+ unresolved: v1.unresolved,
106
+ mandatory_human_review: v1.mandatory_human_review,
107
+ no_signal: v1.no_signal
108
+ },
109
+ v2_security: {
110
+ level: v2.level,
111
+ confidence: v2.confidence,
112
+ evidence: v2.evidence,
113
+ unresolved: v2.unresolved,
114
+ mandatory_human_review: v2.mandatory_human_review,
115
+ no_signal: v2.no_signal
116
+ },
117
+ v3_topology: {
118
+ level: v3.level,
119
+ confidence: v3.confidence,
120
+ evidence: v3.evidence,
121
+ unresolved: v3.unresolved,
122
+ mandatory_human_review: v3.mandatory_human_review,
123
+ no_signal: v3.no_signal
124
+ }
125
+ },
126
+ governance,
127
+ reason_codes: decision.reason_codes,
128
+ observations: [],
129
+ transition: decision.transition
130
+ };
131
+
132
+ // 4. Persist if repoRoot and changeId provided
133
+ if (persist && repoRoot && changeId) {
134
+ return appendAssessmentRecord(repoRoot, changeId, recordData);
135
+ }
136
+
137
+ return recordData;
138
+ } catch (err) {
139
+ // Fallback to Global Default on unexpected exception (§5.5)
140
+ const fallbackDecision = decideAssessment({ stage, error: err, previous });
141
+ const fallbackRecord = {
142
+ timestamp: new Date().toISOString(),
143
+ actor,
144
+ stage,
145
+ role: 'primary',
146
+ compared_to: null,
147
+ status: 'defaulted',
148
+ verdict: 'defaulted',
149
+ defaulted_cause: err.message,
150
+ change_type: changeType || 'change',
151
+ source: {
152
+ base_sha: String(baseSha || 'HEAD'),
153
+ head_sha: headSha ? String(headSha) : null,
154
+ harness_rules_version: HARNESS_RULES_VERSION,
155
+ engine_version: ENGINE_VERSION,
156
+ task_ref: null,
157
+ models: []
158
+ },
159
+ risk: {
160
+ level: fallbackDecision.level,
161
+ confidence: 'low'
162
+ },
163
+ vectors: {
164
+ v1_intent: { level: 'L2', confidence: 'low', evidence: [], unresolved: [err.message], mandatory_human_review: true, no_signal: false },
165
+ v2_security: { level: 'L2', confidence: 'low', evidence: [], unresolved: [err.message], mandatory_human_review: true, no_signal: false },
166
+ v3_topology: { level: 'L2', confidence: 'low', evidence: [], unresolved: [err.message], mandatory_human_review: true, no_signal: false }
167
+ },
168
+ governance: fallbackDecision.governance,
169
+ reason_codes: ['DEFAULTED'],
170
+ observations: [],
171
+ transition: fallbackDecision.transition
172
+ };
173
+
174
+ if (persist && repoRoot && changeId) {
175
+ try {
176
+ return appendAssessmentRecord(repoRoot, changeId, fallbackRecord);
177
+ } catch {
178
+ // Return memory record if disk append fails
179
+ }
180
+ }
181
+ return fallbackRecord;
182
+ }
183
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Formats assessment records into PR status summaries, comments, and labels (Specification §9.7)
3
+ */
4
+
5
+ export function renderCheckSummary(record) {
6
+ const lvl = record.risk.level;
7
+ const human = record.governance.implementation_review === 'ai+human' ? 'human-review-required' : 'auto-merge-eligible';
8
+ const codes = (record.reason_codes || []).join(',') || 'NONE';
9
+ return `[${record.verdict.toUpperCase()}] Level: ${lvl} | Mode: ${record.governance.workflow_mode} | Review: ${human} | Codes: ${codes}`;
10
+ }
11
+
12
+ export function renderPRComment(record) {
13
+ const isEscalated = record.transition.direction === 'up';
14
+ const lvl = record.risk.level;
15
+ const isHumanReview = record.governance.implementation_review === 'ai+human';
16
+
17
+ // Prominent Governance Level & Action Highlight Banner
18
+ let actionHighlight = '';
19
+ if (isEscalated) {
20
+ actionHighlight = `> ⚠️ **【治理动作:实施阶段升级 · 必须人工终审】**\n> 🎯 **最终治理等级**:\`${lvl}\`(由 \`${record.transition.from_level || 'L1'}\` 原地升级)\n> 🚨 **流转执行**:保持单 PR 流水线,**自动合并已关闭 (Auto-Merge DENIED)**,必须由人类 Lead 审核批准后方可合入。`;
21
+ } else if (isHumanReview) {
22
+ actionHighlight = `> 🛑 **【治理动作:高风险改动 · 必须人工终审】**\n> 🎯 **最终治理等级**:\`${lvl}\`\n> 🚨 **流转执行**:**自动合并已关闭 (Auto-Merge DENIED)**,必须由人类 Lead 审核批准后方可合入主干。`;
23
+ } else {
24
+ actionHighlight = `> ⚡ **【治理动作:低风险改动 · AI 自动合入 (Auto-Merge Eligible)】**\n> 🎯 **最终治理等级**:\`${lvl}\`\n> 🚀 **流转执行**:CI 门禁与自动化测试全绿后,**系统将自动 Approve 并执行合并**,无需人工审批阻断。`;
25
+ }
26
+
27
+ const title = isEscalated
28
+ ? `⚠️ 需要人工评审 · 风险等级 ${record.transition.from_level || 'L1'} → ${lvl}(升级)`
29
+ : `🛡️ ASdlc 治理评估报告 · 风险等级 ${lvl}`;
30
+
31
+ const reasonList = (record.reason_codes || []).map((c) => `- [${c}]`).join('\n') || '- 局部封闭改动,未触发硬规则';
32
+
33
+ const evidenceItems = [];
34
+ for (const vName of ['v1_intent', 'v2_security', 'v3_topology']) {
35
+ const v = record.vectors[vName];
36
+ if (v && v.evidence) {
37
+ for (const e of v.evidence) {
38
+ evidenceItems.push(`- [${e.signal.toUpperCase()}] ${e.summary}`);
39
+ }
40
+ }
41
+ }
42
+
43
+ const reviewQuestions = isHumanReview
44
+ ? `**评审人请确认:**\n- 行为与代码变化是否与已批准意图一致\n- 确认未解项与潜在外部影响已被充分覆盖\n`
45
+ : `**自动化判定:**\n- 满足自动合并条件,无需额外人工 Lead 审批。\n`;
46
+
47
+ return `### ${title}
48
+
49
+ ${actionHighlight}
50
+
51
+ | 最终治理等级 (Level) | 工作流模式 (Workflow) | 实施评审要求 (Review) | 记录指纹 (Fingerprint) |
52
+ | :---: | :---: | :---: | :---: |
53
+ | **\`${lvl}\`** | \`${record.governance.workflow_mode}\` | \`${record.governance.implementation_review}\` | \`${(record.hash || '').slice(0, 12) || 'unpersisted'}\` |
54
+
55
+ **📋 评估理由与依据:**
56
+ ${evidenceItems.join('\n') || reasonList}
57
+
58
+ ${reviewQuestions}
59
+ `;
60
+ }
61
+
62
+ export function renderLabels(record) {
63
+ const labels = [`asdlc:${record.risk.level}`];
64
+ if (record.governance.implementation_review === 'ai+human') {
65
+ labels.push('asdlc:human-review-required');
66
+ }
67
+ if (record.transition.direction === 'up') {
68
+ labels.push('asdlc:escalated');
69
+ }
70
+ return labels;
71
+ }