minimal-vibe-coding-kit 0.4.2 → 0.5.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 (133) hide show
  1. package/.agents/skills/claim/SKILL.md +82 -0
  2. package/.agents/skills/tutien/SKILL.md +74 -0
  3. package/.agents/skills/tutien/references/classification.md +64 -0
  4. package/.agents/skills/tutien/references/lore-sources.md +15 -0
  5. package/.agents/skills/tutien/references/privacy.md +33 -0
  6. package/.agents/skills/tutien/references/schema.md +75 -0
  7. package/.agents/skills/tutien/references/scoring-and-realms.md +37 -0
  8. package/.agents/skills/tutien/references/voice-and-mode.md +44 -0
  9. package/.agents/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  10. package/.agents/skills/tutien/scripts/adapters/git.mjs +48 -0
  11. package/.agents/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  12. package/.agents/skills/tutien/scripts/analyze-history.mjs +84 -0
  13. package/.agents/skills/tutien/scripts/catalog.mjs +130 -0
  14. package/.agents/skills/tutien/scripts/classify.mjs +311 -0
  15. package/.agents/skills/tutien/scripts/command.mjs +107 -0
  16. package/.agents/skills/tutien/scripts/compare.mjs +41 -0
  17. package/.agents/skills/tutien/scripts/metrics.mjs +306 -0
  18. package/.agents/skills/tutien/scripts/normalize-events.mjs +68 -0
  19. package/.agents/skills/tutien/scripts/redact.mjs +30 -0
  20. package/.agents/skills/tutien/scripts/render-report.mjs +423 -0
  21. package/.agents/skills/tutien/scripts/run-tutien.mjs +272 -0
  22. package/.agents/skills/tutien/scripts/score.mjs +97 -0
  23. package/.agents/skills/tutien/scripts/snapshot.mjs +76 -0
  24. package/.agents/skills/tutien/scripts/villains.mjs +196 -0
  25. package/.claude/skills/claim/SKILL.md +82 -0
  26. package/.claude/skills/tutien/SKILL.md +74 -0
  27. package/.claude/skills/tutien/references/classification.md +64 -0
  28. package/.claude/skills/tutien/references/lore-sources.md +15 -0
  29. package/.claude/skills/tutien/references/privacy.md +33 -0
  30. package/.claude/skills/tutien/references/schema.md +75 -0
  31. package/.claude/skills/tutien/references/scoring-and-realms.md +37 -0
  32. package/.claude/skills/tutien/references/voice-and-mode.md +44 -0
  33. package/.claude/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  34. package/.claude/skills/tutien/scripts/adapters/git.mjs +48 -0
  35. package/.claude/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  36. package/.claude/skills/tutien/scripts/analyze-history.mjs +84 -0
  37. package/.claude/skills/tutien/scripts/catalog.mjs +130 -0
  38. package/.claude/skills/tutien/scripts/classify.mjs +311 -0
  39. package/.claude/skills/tutien/scripts/command.mjs +107 -0
  40. package/.claude/skills/tutien/scripts/compare.mjs +41 -0
  41. package/.claude/skills/tutien/scripts/metrics.mjs +306 -0
  42. package/.claude/skills/tutien/scripts/normalize-events.mjs +68 -0
  43. package/.claude/skills/tutien/scripts/redact.mjs +30 -0
  44. package/.claude/skills/tutien/scripts/render-report.mjs +423 -0
  45. package/.claude/skills/tutien/scripts/run-tutien.mjs +272 -0
  46. package/.claude/skills/tutien/scripts/score.mjs +97 -0
  47. package/.claude/skills/tutien/scripts/snapshot.mjs +76 -0
  48. package/.claude/skills/tutien/scripts/villains.mjs +196 -0
  49. package/.codex-plugin/plugin.json +1 -1
  50. package/.cursor/skills/claim/SKILL.md +82 -0
  51. package/.cursor/skills/tutien/SKILL.md +74 -0
  52. package/.cursor/skills/tutien/references/classification.md +64 -0
  53. package/.cursor/skills/tutien/references/lore-sources.md +15 -0
  54. package/.cursor/skills/tutien/references/privacy.md +33 -0
  55. package/.cursor/skills/tutien/references/schema.md +75 -0
  56. package/.cursor/skills/tutien/references/scoring-and-realms.md +37 -0
  57. package/.cursor/skills/tutien/references/voice-and-mode.md +44 -0
  58. package/.cursor/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  59. package/.cursor/skills/tutien/scripts/adapters/git.mjs +48 -0
  60. package/.cursor/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  61. package/.cursor/skills/tutien/scripts/analyze-history.mjs +84 -0
  62. package/.cursor/skills/tutien/scripts/catalog.mjs +130 -0
  63. package/.cursor/skills/tutien/scripts/classify.mjs +311 -0
  64. package/.cursor/skills/tutien/scripts/command.mjs +107 -0
  65. package/.cursor/skills/tutien/scripts/compare.mjs +41 -0
  66. package/.cursor/skills/tutien/scripts/metrics.mjs +306 -0
  67. package/.cursor/skills/tutien/scripts/normalize-events.mjs +68 -0
  68. package/.cursor/skills/tutien/scripts/redact.mjs +30 -0
  69. package/.cursor/skills/tutien/scripts/render-report.mjs +423 -0
  70. package/.cursor/skills/tutien/scripts/run-tutien.mjs +272 -0
  71. package/.cursor/skills/tutien/scripts/score.mjs +97 -0
  72. package/.cursor/skills/tutien/scripts/snapshot.mjs +76 -0
  73. package/.cursor/skills/tutien/scripts/villains.mjs +196 -0
  74. package/.grok/skills/claim/SKILL.md +82 -0
  75. package/.grok/skills/tutien/SKILL.md +74 -0
  76. package/.grok/skills/tutien/references/classification.md +64 -0
  77. package/.grok/skills/tutien/references/lore-sources.md +15 -0
  78. package/.grok/skills/tutien/references/privacy.md +33 -0
  79. package/.grok/skills/tutien/references/schema.md +75 -0
  80. package/.grok/skills/tutien/references/scoring-and-realms.md +37 -0
  81. package/.grok/skills/tutien/references/voice-and-mode.md +44 -0
  82. package/.grok/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  83. package/.grok/skills/tutien/scripts/adapters/git.mjs +48 -0
  84. package/.grok/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  85. package/.grok/skills/tutien/scripts/analyze-history.mjs +84 -0
  86. package/.grok/skills/tutien/scripts/catalog.mjs +130 -0
  87. package/.grok/skills/tutien/scripts/classify.mjs +311 -0
  88. package/.grok/skills/tutien/scripts/command.mjs +107 -0
  89. package/.grok/skills/tutien/scripts/compare.mjs +41 -0
  90. package/.grok/skills/tutien/scripts/metrics.mjs +306 -0
  91. package/.grok/skills/tutien/scripts/normalize-events.mjs +68 -0
  92. package/.grok/skills/tutien/scripts/redact.mjs +30 -0
  93. package/.grok/skills/tutien/scripts/render-report.mjs +423 -0
  94. package/.grok/skills/tutien/scripts/run-tutien.mjs +272 -0
  95. package/.grok/skills/tutien/scripts/score.mjs +97 -0
  96. package/.grok/skills/tutien/scripts/snapshot.mjs +76 -0
  97. package/.grok/skills/tutien/scripts/villains.mjs +196 -0
  98. package/.vibekit/docs/BACKBONE_REFERENCE.md +2 -0
  99. package/.vibekit/docs/INSTALL.md +3 -1
  100. package/.vibekit/init/CLAUDE-template.md +2 -0
  101. package/.vibekit/scripts/mvck.mjs +5 -5
  102. package/.vibekit/scripts/pack-dry-run.mjs +38 -3
  103. package/.vibekit/scripts/validate-kit.mjs +34 -24
  104. package/.vibekit/skills/claim/SKILL.md +82 -0
  105. package/.vibekit/skills/skills-manifest.json +27 -0
  106. package/.vibekit/skills/tutien/SKILL.md +74 -0
  107. package/.vibekit/skills/tutien/references/classification.md +64 -0
  108. package/.vibekit/skills/tutien/references/lore-sources.md +15 -0
  109. package/.vibekit/skills/tutien/references/privacy.md +33 -0
  110. package/.vibekit/skills/tutien/references/schema.md +75 -0
  111. package/.vibekit/skills/tutien/references/scoring-and-realms.md +37 -0
  112. package/.vibekit/skills/tutien/references/voice-and-mode.md +44 -0
  113. package/.vibekit/skills/tutien/scripts/adapters/generic-jsonl.mjs +82 -0
  114. package/.vibekit/skills/tutien/scripts/adapters/git.mjs +48 -0
  115. package/.vibekit/skills/tutien/scripts/adapters/plain-transcript.mjs +37 -0
  116. package/.vibekit/skills/tutien/scripts/analyze-history.mjs +84 -0
  117. package/.vibekit/skills/tutien/scripts/catalog.mjs +130 -0
  118. package/.vibekit/skills/tutien/scripts/classify.mjs +311 -0
  119. package/.vibekit/skills/tutien/scripts/command.mjs +107 -0
  120. package/.vibekit/skills/tutien/scripts/compare.mjs +41 -0
  121. package/.vibekit/skills/tutien/scripts/metrics.mjs +306 -0
  122. package/.vibekit/skills/tutien/scripts/normalize-events.mjs +68 -0
  123. package/.vibekit/skills/tutien/scripts/redact.mjs +30 -0
  124. package/.vibekit/skills/tutien/scripts/render-report.mjs +423 -0
  125. package/.vibekit/skills/tutien/scripts/run-tutien.mjs +272 -0
  126. package/.vibekit/skills/tutien/scripts/score.mjs +97 -0
  127. package/.vibekit/skills/tutien/scripts/snapshot.mjs +76 -0
  128. package/.vibekit/skills/tutien/scripts/villains.mjs +196 -0
  129. package/CHANGELOG.md +30 -0
  130. package/README.md +51 -47
  131. package/docs/README.vi.md +12 -8
  132. package/docs/README.zh-CN.md +277 -0
  133. package/package.json +9 -3
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import process from 'node:process';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { parseJsonl } from './adapters/generic-jsonl.mjs';
7
+ import { parseTranscript } from './adapters/plain-transcript.mjs';
8
+ import { readGitEvents } from './adapters/git.mjs';
9
+ import { normalizeEvents } from './normalize-events.mjs';
10
+ import {
11
+ groupTasks,
12
+ repetitionMetrics,
13
+ conflictCandidates,
14
+ issueMetrics,
15
+ tokenMetrics,
16
+ coverageMetrics
17
+ } from './metrics.mjs';
18
+
19
+ // Phase 1 analyzer: deterministic, read-only, machine-readable JSON only.
20
+ // The output contains digests and event IDs, never prompt text.
21
+ export function analyze({ jsonlFiles = [], transcriptFiles = [], gitRoot = null, gapMinutes = 60 } = {}) {
22
+ const notes = [];
23
+ let raw = [];
24
+ // The source tag is forced per adapter batch here; export content cannot
25
+ // spoof it (the JSONL validator additionally rejects reserved fields).
26
+ for (const file of jsonlFiles) {
27
+ raw = raw.concat(
28
+ parseJsonl(fs.readFileSync(file, 'utf8'), path.basename(file)).map((e) => ({ ...e, __source: 'generic-jsonl' }))
29
+ );
30
+ }
31
+ for (const file of transcriptFiles) {
32
+ const { events, warnings } = parseTranscript(fs.readFileSync(file, 'utf8'));
33
+ raw = raw.concat(events.map((e) => ({ ...e, __source: 'transcript' })));
34
+ notes.push(...warnings.map((w) => `${path.basename(file)}: ${w}`));
35
+ }
36
+ if (gitRoot) raw = raw.concat(readGitEvents(gitRoot).map((e) => ({ ...e, __source: 'git' })));
37
+
38
+ const events = normalizeEvents(raw);
39
+ const tasks = groupTasks(events, { gapMinutes });
40
+ const taskKeyByEvent = new Map();
41
+ for (const t of tasks) for (const id of t.eventIds) taskKeyByEvent.set(id, t.taskId);
42
+ const tokens = tokenMetrics(events);
43
+ return {
44
+ schemaVersion: 1,
45
+ eventsAnalyzed: events.length,
46
+ coverage: coverageMetrics(events, tasks, tokens),
47
+ tokens,
48
+ tasks: tasks.map((t) => ({
49
+ taskId: t.taskId,
50
+ sessionId: t.sessionId,
51
+ grouping: t.grouping,
52
+ confidence: t.confidence,
53
+ eventCount: t.eventIds.length
54
+ })),
55
+ commitEventIds: events.filter((e) => e.eventType === 'commit').map((e) => e.eventId),
56
+ repetition: repetitionMetrics(events, tasks),
57
+ conflicts: conflictCandidates(events, tasks),
58
+ issues: issueMetrics(events, taskKeyByEvent),
59
+ notes
60
+ };
61
+ }
62
+
63
+ const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
64
+ if (isMain) {
65
+ const args = process.argv.slice(2);
66
+ const spec = { jsonlFiles: [], transcriptFiles: [], gitRoot: null, gapMinutes: 60 };
67
+ let out = null;
68
+ for (let i = 0; i < args.length; i++) {
69
+ const a = args[i];
70
+ if (a === '--jsonl') spec.jsonlFiles.push(args[++i]);
71
+ else if (a === '--transcript') spec.transcriptFiles.push(args[++i]);
72
+ else if (a === '--git') spec.gitRoot = args[++i];
73
+ else if (a === '--gap-minutes') spec.gapMinutes = Number(args[++i]);
74
+ else if (a === '--out') out = args[++i];
75
+ else {
76
+ console.error(`Unknown argument: ${a}`);
77
+ console.error('Usage: analyze-history.mjs [--jsonl f]... [--transcript f]... [--git dir] [--gap-minutes n] [--out f]');
78
+ process.exit(2);
79
+ }
80
+ }
81
+ const json = JSON.stringify(analyze(spec), null, 2);
82
+ if (out) fs.writeFileSync(out, `${json}\n`);
83
+ else console.log(json);
84
+ }
@@ -0,0 +1,130 @@
1
+ // Problem-to-practice catalog. Data-driven so new problem types can be added
2
+ // without touching the analyzer. Each entry carries an existing project skill
3
+ // or convention as the concrete counter-technique, plus a villain archetype
4
+ // that the Phase 3 engine may (optionally) surface. Detection is evidence-
5
+ // bound: a problem needs real event references and a confidence, never a
6
+ // single ambiguous signal.
7
+
8
+ export const CATALOG = {
9
+ 'repeated-failure': {
10
+ problemType: 'repeated-failure',
11
+ counterTechnique: { vi: 'Dừng sau lần thất bại thứ hai giống nhau; lập giả thuyết mới trước khi thử lại.', en: 'Stop after the second identical failure; form a new hypothesis before retrying.' },
12
+ projectHelp: 'sequential-thinking',
13
+ microQuest: { vi: 'Lần lặp kế tiếp: viết 1 giả thuyết mới trước khi chạy lại.', en: 'Next iteration: write one new hypothesis before re-running.' },
14
+ victory: { vi: 'Một task khép lại mà không có 3 lần thử giống nhau.', en: 'A task closes without three identical retries.' },
15
+ ifThen: { vi: 'Nếu cùng một lệnh thất bại hai lần, thì dừng thử lại và viết một giả thuyết mới.', en: 'If the same command fails twice, then stop retrying and write a new hypothesis.' },
16
+ villain: { name: 'Luân Hồi Lỗi Ma', gloss: 'Error-Cycle Wraith' }
17
+ },
18
+ 'too-many-prompts': {
19
+ problemType: 'too-many-prompts',
20
+ counterTechnique: { vi: 'Chia task thành các checkpoint, mỗi ranh giới có một kết quả kiểm chứng.', en: 'Split the task into checkpoints with a validation result at each boundary.' },
21
+ projectHelp: 'clearthought',
22
+ microQuest: { vi: 'Task tới: định nghĩa 2 checkpoint có tiêu chí "done".', en: 'Next task: define 2 checkpoints each with a done-criterion.' },
23
+ victory: { vi: 'Task hoàn thành trong số prompt dưới ngưỡng lịch sử.', en: 'A task completes under the historical prompt threshold.' },
24
+ ifThen: { vi: 'Nếu gửi prompt thứ ba cho cùng một task, thì đặt một checkpoint có tiêu chí "done" trước đã.', en: 'If you send a third prompt on one task, then define a checkpoint with a done-criterion first.' },
25
+ villain: { name: 'Cửu Hoàn Tâm Ma', gloss: 'Ninefold Loop Heart-Shadow' }
26
+ },
27
+ 'conflicting-instructions': {
28
+ problemType: 'conflicting-instructions',
29
+ counterTechnique: { vi: 'Lập sổ ưu tiên và ràng buộc; nêu rõ chỉ thị nào thay thế chỉ thị nào.', en: 'Build a precedence and constraint ledger; state which instruction supersedes which.' },
30
+ projectHelp: 'claim',
31
+ microQuest: { vi: 'Trước khi sửa: ghi 1 dòng "được phép / không được phép".', en: 'Before editing: write one allowed/forbidden line.' },
32
+ victory: { vi: 'Không còn cặp chỉ thị mâu thuẫn chưa giải quyết trong một task.', en: 'No unresolved contradictory instruction pair remains in a task.' },
33
+ ifThen: { vi: 'Nếu chỉ thị mới mâu thuẫn với chỉ thị trước, thì nêu rõ chỉ thị nào thắng trước khi sửa.', en: 'If a new instruction contradicts an earlier one, then state which one wins before editing.' },
34
+ villain: { name: 'Nghịch Lệnh Ma Quân', gloss: 'Lord of Clashing Edicts' }
35
+ },
36
+ 'unrecovered-failure': {
37
+ problemType: 'unrecovered-failure',
38
+ counterTechnique: { vi: 'Thêm cổng hoàn thành: chạy validation và đính kèm biên nhận kết quả.', en: 'Add a completion gate: run validation and attach a result receipt.' },
39
+ projectHelp: 'backbone.yml validate',
40
+ microQuest: { vi: 'Với mỗi lỗi còn treo: chạy lại đúng kiểm tra đó tới khi pass.', en: 'For each open failure: re-run that exact check until it passes.' },
41
+ victory: { vi: 'Mỗi thất bại có một lần pass tương ứng về sau.', en: 'Every failure has a later matching pass.' },
42
+ ifThen: { vi: 'Nếu một kiểm tra thất bại, thì chạy lại đúng kiểm tra đó cho tới khi pass trước khi làm việc mới.', en: 'If a check fails, then re-run that exact check until it passes before starting new work.' },
43
+ villain: { name: 'Vô Kiểm Ảnh Quân', gloss: 'Unverified Trial Wraith' }
44
+ },
45
+ 'work-without-proof': {
46
+ problemType: 'work-without-proof',
47
+ counterTechnique: { vi: 'Chạy lệnh validation của repo và gắn kết quả trước khi tuyên bố xong.', en: 'Run the repository validation and attach the result before declaring done.' },
48
+ projectHelp: 'backbone.yml validate',
49
+ microQuest: { vi: 'Commit tới: kèm 1 dòng kết quả validation.', en: 'Next commit: include one validation-result line.' },
50
+ victory: { vi: 'Mỗi vùng công việc có ít nhất một sự kiện kiểm chứng.', en: 'Every work window has at least one validation event.' },
51
+ ifThen: { vi: 'Nếu sắp tuyên bố "xong", thì chạy validation của repo và đính kèm kết quả trước.', en: "If you are about to say 'done', then run the repo validation and attach the result first." },
52
+ villain: { name: 'Vô Chứng Đan Ảnh', gloss: 'Proofless Elixir Shade' }
53
+ }
54
+ };
55
+
56
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
57
+ const round3 = (x) => Math.round(x * 1000) / 1000;
58
+
59
+ // Returns ranked, actionable problems. priority = impact × recurrence ×
60
+ // confidence × fixability. Only problems with confidence >= minConfidence and
61
+ // priority >= minPriority survive; at most `top` are returned.
62
+ export function detectProblems(analysis, { minConfidence = 0.5, minPriority = 0.12, top = 3 } = {}) {
63
+ const found = [];
64
+ const rep = analysis.repetition ?? {};
65
+ const issues = analysis.issues ?? {};
66
+ const failures = issues.failures ?? [];
67
+ const recoveries = issues.recoveries ?? [];
68
+
69
+ for (const loop of rep.retryLoopCandidates ?? []) {
70
+ // Only failures attributed to this loop's own task make it a failure loop;
71
+ // an unrelated failure elsewhere must not change the classification.
72
+ const isFailing = failures.some((f) => f.taskId != null && f.taskId === loop.taskId);
73
+ const id = isFailing ? 'repeated-failure' : 'too-many-prompts';
74
+ found.push({
75
+ problemId: id,
76
+ evidence: { taskId: loop.taskId, repeatCount: loop.count, eventIds: loop.eventIds },
77
+ confidence: loop.confidence,
78
+ impact: isFailing ? 0.7 : 0.5,
79
+ recurrence: clamp01(loop.count / 4),
80
+ fixability: 0.8
81
+ });
82
+ }
83
+
84
+ const conflicts = analysis.conflicts ?? [];
85
+ if (conflicts.length > 0) {
86
+ found.push({
87
+ problemId: 'conflicting-instructions',
88
+ evidence: { count: conflicts.length, eventIds: conflicts.flatMap((c) => c.eventIds) },
89
+ confidence: Math.max(...conflicts.map((c) => c.confidence)),
90
+ impact: 0.7,
91
+ recurrence: clamp01(conflicts.length / 2),
92
+ fixability: 0.7
93
+ });
94
+ }
95
+
96
+ const unrecovered = failures.filter((f) => !recoveries.some((r) => r.issueEventId === f.eventId));
97
+ if (unrecovered.length > 0) {
98
+ found.push({
99
+ problemId: 'unrecovered-failure',
100
+ evidence: { count: unrecovered.length, eventIds: unrecovered.map((f) => f.eventId) },
101
+ confidence: 0.7,
102
+ impact: 0.8,
103
+ recurrence: clamp01(unrecovered.length / 3),
104
+ fixability: 0.6
105
+ });
106
+ }
107
+
108
+ const commits = analysis.coverage?.commits ?? 0;
109
+ const validationEvents = (issues.passes ?? 0) + failures.length;
110
+ if (commits > 0 && validationEvents === 0) {
111
+ found.push({
112
+ problemId: 'work-without-proof',
113
+ evidence: { commits, validationEvents: 0 },
114
+ confidence: 0.6,
115
+ impact: 0.6,
116
+ recurrence: clamp01(commits / 5),
117
+ fixability: 0.7
118
+ });
119
+ }
120
+
121
+ return found
122
+ .map((p) => {
123
+ const meta = CATALOG[p.problemId];
124
+ const priority = round3(p.impact * p.recurrence * p.confidence * p.fixability);
125
+ return { ...p, priority, confidence: round3(p.confidence), meta };
126
+ })
127
+ .filter((p) => p.confidence >= minConfidence && p.priority >= minPriority)
128
+ .sort((a, b) => b.priority - a.priority || a.problemId.localeCompare(b.problemId))
129
+ .slice(0, top);
130
+ }
@@ -0,0 +1,311 @@
1
+ // Tu Tiên project-classification and progression system. Three orthogonal
2
+ // axes plus a knowledge taxonomy and seven progression metrics:
3
+ // - Dao faction = the PROJECT's ethical/risk posture;
4
+ // - affiliation = the cultivator's ORGANIZATIONAL mode (never ethics:
5
+ // Tán Tu is independence, not the opposite of Tà Tu);
6
+ // - paths = the project's TECHNICAL nature (multi-select).
7
+ //
8
+ // One fail-closed POLICY STATE governs the whole report. Only `clear` may
9
+ // enable lore, villains, recommendations, score, realm, and positive
10
+ // progression:
11
+ // - declared-stop : user declared Tà Đạo / Tà Tu — a stop signal;
12
+ // - needs-review : intent-to-harm signals — no Dao assignment,
13
+ // no gamification, ask for human review;
14
+ // - authorization-required : Ma Đạo without a valid authorization slug;
15
+ // - clear : lawful constructive work.
16
+ // The engine NEVER auto-assigns Tà Đạo / Tà Tu (intent to harm cannot be
17
+ // judged lexically; difficulty is not evil), and never labels harmful text
18
+ // "righteous" — harm produces an undetermined faction and needs-review.
19
+
20
+ import crypto from 'node:crypto';
21
+
22
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
23
+ const round3 = (x) => Math.round(x * 1000) / 1000;
24
+ const sha16 = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 16);
25
+
26
+ export const FACTIONS = {
27
+ 'chinh-dao': { name: 'Chính Đạo', gloss: { vi: 'chính phái — hợp pháp, minh bạch, tạo giá trị cho người dùng', en: 'Righteous Dao — lawful, transparent, constructive, user-beneficial' }, rank: 'normal' },
28
+ 'bang-mon': { name: 'Bàng Môn / Kỳ Đạo', gloss: { vi: 'phi truyền thống — thử nghiệm, sáng tạo, chuyên biệt, không gây hại', en: 'Heterodox Dao — unconventional, experimental, creative, specialized; not harmful' }, rank: 'normal' },
29
+ 'ma-dao': { name: 'Ma Đạo', gloss: { vi: 'kỹ thuật rủi ro cao / đối kháng — cần ủy quyền và giám sát rõ ràng', en: 'Demonic Dao — high-risk, adversarial, restricted technical work requiring explicit authorization and oversight' }, rank: 'restricted' },
30
+ 'ta-dao': { name: 'Tà Đạo', gloss: { vi: 'cố ý gây hại, bóc lột, phi pháp — không bao giờ là con đường tu luyện', en: 'Evil Dao — intentionally harmful, exploitative, unlawful — never a progression path' }, rank: 'forbidden' }
31
+ };
32
+ // Not a real faction — the result of refusing to classify harmful intent.
33
+ const UNDETERMINED_FACTION = { id: 'undetermined', name: 'Chưa phân định', gloss: { vi: 'chưa gán đạo — cần review con người', en: 'undetermined — needs human review' }, rank: 'review' };
34
+
35
+ export const AFFILIATIONS = {
36
+ 'tong-mon': { name: 'Tông Môn Đệ Tử', gloss: { vi: 'làm việc trong đội nhóm / tổ chức / quy trình có sẵn', en: 'works within a team, organization, or established process' } },
37
+ 'tan-tu': { name: 'Tán Tu', gloss: { vi: 'tu luyện độc lập, không thuộc tổ chức cố định', en: 'works independently, outside a fixed organization or tradition' } },
38
+ 'khach-khanh': { name: 'Khách Khanh', gloss: { vi: 'chuyên gia bên ngoài / cộng tác tạm thời', en: 'external expert or temporary contributor' } },
39
+ 'an-tu': { name: 'Ẩn Tu', gloss: { vi: 'nghiên cứu riêng tư, dài hạn, chuyên sâu', en: 'private, long-term, deeply focused research' } }
40
+ };
41
+
42
+ export const PATHS = {
43
+ kiem: { name: 'Kiếm Tu', gloss: { vi: 'triển khai phần mềm trực tiếp, giải quyết vấn đề nhanh', en: 'direct implementation and fast problem-solving' } },
44
+ tran: { name: 'Trận Tu', gloss: { vi: 'kiến trúc, DevOps, hạ tầng, mạng, điều phối hệ thống', en: 'architecture, DevOps, infrastructure, networking, orchestration' } },
45
+ phu: { name: 'Phù Tu', gloss: { vi: 'prompt, script, tự động hóa, workflow lặp lại được', en: 'prompts, scripts, automation, repeatable workflows' } },
46
+ khi: { name: 'Khí Tu', gloss: { vi: 'công cụ, thư viện, thành phần tái sử dụng, nền tảng', en: 'tools, libraries, reusable components, platform engineering' } },
47
+ dan: { name: 'Đan Tu', gloss: { vi: 'xử lý dữ liệu, tối ưu, biến đổi, tổng hợp tài nguyên', en: 'data processing, optimization, transformation, resource synthesis' } },
48
+ y: { name: 'Y Tu', gloss: { vi: 'debug, bảo trì, khắc phục sự cố, hỗ trợ kỹ thuật', en: 'debugging, maintenance, incident recovery, support' } },
49
+ huyen: { name: 'Huyễn Tu', gloss: { vi: 'UI/UX, animation, thiết kế, 3D, giao diện sáng tạo', en: 'UI/UX, animation, visual design, 3D, creative interfaces' } },
50
+ 'ngu-thu': { name: 'Ngự Thú Tu', gloss: { vi: 'điều phối AI agent, bot, đa mô hình', en: 'AI-agent, bot, or multi-model orchestration' } },
51
+ 'huyen-co': { name: 'Huyền Cơ Tu', gloss: { vi: 'mật mã, thuật toán khó, bài toán phân tích hóc búa', en: 'cryptography, advanced algorithms, hard analytical problems' } },
52
+ anh: { name: 'Ảnh Tu', gloss: { vi: 'an ninh mạng có ủy quyền, forensics, điều tra, OSINT, dịch ngược', en: 'authorized cybersecurity, forensics, investigation, OSINT, reverse engineering' } },
53
+ ta: { name: 'Tà Tu', gloss: { vi: 'phương pháp cố ý gây hại — không bao giờ gán chỉ vì dự án khó hay thuộc mảng bảo mật', en: 'intentionally harmful methods — never assigned merely because work is difficult or security-related' } }
54
+ };
55
+
56
+ export const KNOWLEDGE_KINDS = {
57
+ 'tam-phap': { name: 'Tâm Pháp', gloss: { vi: 'nguyên tắc tư duy cốt lõi', en: 'core reasoning principles and mindset' } },
58
+ 'cong-phap': { name: 'Công Pháp', gloss: { vi: 'chiến lược làm việc lặp lại được, dài hạn', en: 'repeatable strategies and long-term working methods' } },
59
+ 'thuat-phap': { name: 'Thuật Pháp', gloss: { vi: 'kỹ thuật / mẫu prompt đơn lẻ', en: 'individual prompt patterns or techniques' } },
60
+ 'bi-thuat': { name: 'Bí Thuật', gloss: { vi: 'kỹ thuật hiếm, chuyên sâu', en: 'rare, specialized, advanced techniques' } },
61
+ 'than-thong': { name: 'Thần Thông', gloss: { vi: 'năng lực đã thuần thục, tái sử dụng tin cậy', en: 'highly mastered, reliably reusable abilities' } },
62
+ 'phap-bao': { name: 'Pháp Bảo', gloss: { vi: 'công cụ, script, template, agent hỗ trợ (skill & command của kit)', en: 'tools, scripts, templates, agents (kit skills & commands)' } },
63
+ 'dao-dien': { name: 'Bí Tịch / Đạo Điển', gloss: { vi: 'playbook, skill file, tài liệu tích lũy', en: 'written playbooks, skill files, accumulated documentation' } }
64
+ };
65
+
66
+ // Word/phrase-boundary matcher: boundaries are non-alphanumeric, so "ui" does
67
+ // not match inside "build" and "api" does not match inside "rapid".
68
+ function hasKeyword(text, kw) {
69
+ const esc = kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
70
+ return new RegExp(`(^|[^a-z0-9])${esc}([^a-z0-9]|$)`, 'i').test(text);
71
+ }
72
+
73
+ const PATH_KEYWORDS = {
74
+ kiem: ['implementation', 'feature', 'application', 'app', 'api', 'backend', 'frontend', 'cli', 'bugfix', 'coding'],
75
+ tran: ['architecture', 'devops', 'infrastructure', 'kubernetes', 'docker', 'network', 'deploy', 'orchestration', 'ci/cd', 'terraform'],
76
+ phu: ['prompt', 'prompts', 'script', 'scripts', 'automation', 'workflow', 'skill file', 'slash command'],
77
+ khi: ['library', 'sdk', 'framework', 'platform', 'component', 'toolkit', 'kit', 'reusable'],
78
+ dan: ['data', 'etl', 'pipeline', 'optimization', 'transformation', 'database', 'analytics'],
79
+ y: ['debug', 'maintenance', 'incident', 'support', 'recovery', 'hotfix', 'triage'],
80
+ huyen: ['ui', 'ux', 'design', 'animation', '3d', 'visual', 'interface', 'creative'],
81
+ 'ngu-thu': ['agent', 'bot', 'llm', 'multi-model', 'mcp', 'ai orchestration', 'assistant'],
82
+ 'huyen-co': ['cryptography', 'cipher', 'algorithm', 'decryption', 'mathematical', 'proof'],
83
+ anh: ['security', 'pentest', 'forensics', 'osint', 'reverse engineering', 'vulnerability', 'ctf', 'audit', 'incident response', 'threat']
84
+ };
85
+
86
+ const BANG_MON_KEYWORDS = ['experimental', 'prototype', 'research', 'creative', 'art project', 'demo', 'playground', 'unconventional', 'exploratory'];
87
+ const ADVERSARIAL_KEYWORDS = ['pentest', 'red team', 'offensive security', 'exploit development', 'attack simulation', 'adversarial engagement', 'malware analysis'];
88
+ // Intent-to-harm-others signals. These route to needs-review (undetermined
89
+ // faction), NOT to an automatic Tà label. Curated to avoid dual-use overlap
90
+ // with authorized security work.
91
+ const HARM_KEYWORDS = [
92
+ 'steal', 'exfiltrate', 'malware', 'ransomware', 'phishing', 'spyware', 'keylogger', 'botnet',
93
+ 'defraud', 'fraud', 'scam', 'sabotage', 'backdoor', 'ddos', 'without consent', 'without authorization',
94
+ 'without permission', 'illegal', 'illegally', 'unlawful', 'harm competitor', 'harm competitors',
95
+ 'harm user', 'harm users', 'harm others', 'attack a bank', 'attack users', 'attack a company'
96
+ ];
97
+
98
+ // Authorization is a user-ASSERTED reference only, never verified. Accept a
99
+ // bounded safe slug; reject secret-shaped values, markup, URLs, and anything
100
+ // with '=' (which a `key=value` secret would carry).
101
+ const AUTH_SLUG = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
102
+ export function validateAuthorization(value) {
103
+ if (value == null) return { recorded: false, reference: null, rejected: false };
104
+ if (typeof value === 'string' && AUTH_SLUG.test(value)) return { recorded: true, reference: value, rejected: false };
105
+ return { recorded: false, reference: null, rejected: true };
106
+ }
107
+
108
+ const textOf = (profile) =>
109
+ [profile.description ?? '', ...(profile.domains ?? []), profile.projectType ?? '', profile.primaryLanguage ?? '']
110
+ .join(' ')
111
+ .toLowerCase();
112
+
113
+ export function validateDeclarations(declared = {}) {
114
+ const errors = [];
115
+ if (declared.faction && !FACTIONS[declared.faction]) errors.push(`unknown faction "${declared.faction}"; valid: ${Object.keys(FACTIONS).join(', ')}`);
116
+ if (declared.affiliation && !AFFILIATIONS[declared.affiliation]) errors.push(`unknown affiliation "${declared.affiliation}"; valid: ${Object.keys(AFFILIATIONS).join(', ')}`);
117
+ const paths = declared.paths ?? [];
118
+ for (const p of paths) {
119
+ if (!PATHS[p]) errors.push(`unknown path "${p}"; valid: ${Object.keys(PATHS).join(', ')}`);
120
+ }
121
+ // Tà Tu is an exclusive stop declaration; it must not be combined with real
122
+ // cultivation paths (fail closed rather than mixing lore with a stop state).
123
+ if (paths.includes('ta') && paths.length > 1) errors.push('path "ta" (Tà Tu) is an exclusive stop declaration and cannot be combined with other paths');
124
+ return errors;
125
+ }
126
+
127
+ export function classifyProject(profile = {}) {
128
+ const errors = validateDeclarations(profile.declared ?? {});
129
+ if (errors.length) throw new Error(errors.join('; '));
130
+ const declared = profile.declared ?? {};
131
+ const text = textOf(profile);
132
+ const harmSignals = HARM_KEYWORDS.filter((k) => hasKeyword(text, k));
133
+ const declaredStop = declared.faction === 'ta-dao' || (declared.paths ?? []).includes('ta');
134
+
135
+ // --- paths (multi-select), declared first (order preserved) ---
136
+ const paths = [];
137
+ for (const id of declared.paths ?? []) paths.push({ id, ...PATHS[id], confidence: 0.95, rationale: 'declared by the user', declared: true });
138
+ for (const [id, keywords] of Object.entries(PATH_KEYWORDS)) {
139
+ if (paths.some((p) => p.id === id)) continue;
140
+ const hits = keywords.filter((k) => hasKeyword(text, k));
141
+ if (hits.length) paths.push({ id, ...PATHS[id], confidence: clamp01(0.5 + hits.length * 0.15), rationale: `profile keywords: ${hits.join(', ')}`, declared: false, hitCount: hits.length });
142
+ }
143
+ const declaredPaths = paths.filter((p) => p.declared);
144
+ const detectedPaths = paths.filter((p) => !p.declared).sort((a, b) => b.confidence - a.confidence || b.hitCount - a.hitCount || a.id.localeCompare(b.id));
145
+ const orderedPaths = [...declaredPaths, ...detectedPaths];
146
+
147
+ // --- faction (precedence: declared-stop → harm → declared → detected) ---
148
+ let faction;
149
+ if (declaredStop) {
150
+ faction = { id: 'ta-dao', ...FACTIONS['ta-dao'], confidence: 0.95, rationale: 'declared by the user' };
151
+ } else if (harmSignals.length) {
152
+ faction = { id: 'undetermined', ...UNDETERMINED_FACTION, confidence: 0.9, rationale: `intent-to-harm signals: ${harmSignals.join(', ')}` };
153
+ } else if (declared.faction) {
154
+ faction = { id: declared.faction, ...FACTIONS[declared.faction], confidence: 0.95, rationale: 'declared by the user' };
155
+ } else {
156
+ const adversarial = ADVERSARIAL_KEYWORDS.filter((k) => hasKeyword(text, k));
157
+ const bangMon = BANG_MON_KEYWORDS.filter((k) => hasKeyword(text, k));
158
+ if (adversarial.length) faction = { id: 'ma-dao', ...FACTIONS['ma-dao'], confidence: clamp01(0.6 + adversarial.length * 0.1), rationale: `adversarial engagement signals: ${adversarial.join(', ')}` };
159
+ else if (bangMon.length) faction = { id: 'bang-mon', ...FACTIONS['bang-mon'], confidence: clamp01(0.55 + bangMon.length * 0.1), rationale: `experimental/creative signals: ${bangMon.join(', ')}` };
160
+ else faction = { id: 'chinh-dao', ...FACTIONS['chinh-dao'], confidence: 0.6, rationale: 'default for lawful constructive work; no adversarial or experimental signals' };
161
+ }
162
+
163
+ if (faction.id === 'ma-dao') faction.authorization = validateAuthorization(profile.authorization);
164
+
165
+ // --- output policy: single fail-closed projection ---
166
+ let policyState;
167
+ if (declaredStop) policyState = 'declared-stop';
168
+ else if (faction.id === 'undetermined') policyState = 'needs-review';
169
+ else if (faction.id === 'ma-dao' && !faction.authorization.recorded) policyState = 'authorization-required';
170
+ else policyState = 'clear';
171
+ const policy = { state: policyState, canGamify: policyState === 'clear', canRecommend: policyState === 'clear' };
172
+
173
+ // --- affiliation (organizational only — independent of ethics) ---
174
+ let affiliation;
175
+ if (declared.affiliation) affiliation = { id: declared.affiliation, ...AFFILIATIONS[declared.affiliation], confidence: 0.95, rationale: 'declared by the user' };
176
+ else if (Number.isFinite(profile.authorsCount) && profile.authorsCount > 1) affiliation = { id: 'tong-mon', ...AFFILIATIONS['tong-mon'], confidence: 0.55, rationale: `${profile.authorsCount} distinct commit-author identifiers (low-confidence hint; declare affiliation= to confirm)` };
177
+ else if (profile.authorsCount === 1) affiliation = { id: 'tan-tu', ...AFFILIATIONS['tan-tu'], confidence: 0.5, rationale: 'single commit-author identifier (low-confidence hint)' };
178
+ else affiliation = { id: 'tan-tu', ...AFFILIATIONS['tan-tu'], confidence: 0.4, rationale: 'no author evidence; defaulting — declare affiliation= to correct' };
179
+
180
+ // --- knowledge: primary = first declared path, else strongest detected ---
181
+ const primaryPath = declaredPaths[0]?.id ?? detectedPaths[0]?.id ?? 'kiem';
182
+ const knowledge = policy.canRecommend ? knowledgeFor(primaryPath) : null;
183
+
184
+ const dualUse = orderedPaths.some((p) => p.id === 'anh' || p.id === 'huyen-co');
185
+ const explanation = buildExplanation(faction, policy, dualUse);
186
+
187
+ return { faction, policy, affiliation, paths: orderedPaths, primaryPath, knowledge, explanation, dualUse, harmSignals, suppressGamification: !policy.canGamify };
188
+ }
189
+
190
+ const PATH_KNOWLEDGE = {
191
+ kiem: { tamPhap: { vi: 'Thay đổi nhỏ nhất mà đúng; kiểm chứng sau mỗi lần sửa.', en: 'Smallest correct change; validate after every edit.' }, congPhap: { vi: 'Vòng lặp checkpoint: sửa nhỏ → validation → xác nhận rồi mới đi tiếp.', en: 'Checkpoint loop: small edit → validation → confirm before moving on.' }, biThuat: { vi: 'Tách refactor lớn thành chuỗi diff nhỏ có thể đảo ngược.', en: 'Decompose a large refactor into a chain of small reversible diffs.' }, thanThong: { vi: 'Đọc-hiểu codebase lạ và định vị điểm sửa đúng ngay lần đầu.', en: 'Read an unfamiliar codebase and locate the right edit on the first pass.' }, phapBao: ['prompt-sharpener', 'sequential-thinking'] },
192
+ tran: { tamPhap: { vi: 'Vẽ ranh giới và hợp đồng giữa các thành phần trước khi nối chúng.', en: 'Draw component boundaries and contracts before wiring them.' }, congPhap: { vi: 'Mọi thay đổi hạ tầng đều có đường lùi được diễn tập.', en: 'Every infrastructure change ships with a rehearsed rollback.' }, biThuat: { vi: 'Mô phỏng sự cố có kiểm soát trước khi sự cố thật xảy ra.', en: 'Controlled failure rehearsal before the real incident.' }, thanThong: { vi: 'Thiết kế hệ thống chịu lỗi mà không giấu đi độ bất định.', en: 'Design fault-tolerant systems without hiding uncertainty.' }, phapBao: ['clearthought', 'path-sensitive-shell-safety'] },
193
+ phu: { tamPhap: { vi: 'Một quy trình lặp lại được đáng giá hơn mười lần làm tay.', en: 'One repeatable workflow beats ten manual runs.' }, congPhap: { vi: 'Chuẩn hóa prompt thành skill có tiêu chí done rõ ràng.', en: 'Formalize prompts into skills with explicit done-criteria.' }, biThuat: { vi: 'Guardrail tự kiểm: workflow tự phát hiện khi chính nó sai.', en: 'Self-checking guardrails: the workflow detects its own failure.' }, thanThong: { vi: 'Biến một việc thủ công lặp lại thành lệnh chạy một phát tin cậy.', en: 'Turn a repeated manual chore into a reliable one-shot command.' }, phapBao: ['prompt-sharpener', 'claim'] },
194
+ khi: { tamPhap: { vi: 'API là lời hứa; đặt tên và hành vi phải giữ được lời.', en: 'An API is a promise; naming and behavior must keep it.' }, congPhap: { vi: 'Registry trung tâm + kiểm parity để bản phân phối không trôi.', en: 'Central registry + parity checks so distribution never drifts.' }, biThuat: { vi: 'Fixture âm bản: cố tình làm hỏng để chứng minh validator bắt được.', en: 'Negative fixtures: break it on purpose to prove the validator catches it.' }, thanThong: { vi: 'Thiết kế thành phần tái sử dụng mà người khác dùng đúng ngay.', en: 'Design reusable components others use correctly on the first try.' }, phapBao: ['claim', 'daily-workflow-curator'] },
195
+ dan: { tamPhap: { vi: 'Số liệu tách bạch theo nguồn gốc: đo được, ước lượng, không rõ.', en: 'Numbers stay split by provenance: measured, estimated, unknown.' }, congPhap: { vi: 'Baseline trước, biến đổi sau, so sánh có log.', en: 'Baseline first, transform second, logged comparison always.' }, biThuat: { vi: 'Thiết kế pipeline chạy lại được từ bất kỳ điểm gãy nào.', en: 'Pipelines resumable from any break point.' }, thanThong: { vi: 'Chuyển dữ liệu thô hỗn độn thành dạng đáng tin, đo được.', en: 'Turn messy raw data into a trustworthy, measurable shape.' }, phapBao: ['autoresearch-coding', 'sequential-thinking'] },
196
+ y: { tamPhap: { vi: 'Chẩn bệnh trước, kê đơn sau: tái hiện lỗi trước khi sửa.', en: 'Diagnose before prescribing: reproduce before fixing.' }, congPhap: { vi: 'Hai lần thất bại giống nhau → dừng, lập giả thuyết mới.', en: 'Two identical failures → stop, form a new hypothesis.' }, biThuat: { vi: 'Thu nhỏ ca lỗi tới ví dụ tối giản còn tái hiện được.', en: 'Minimize the failing case to the smallest reproducible example.' }, thanThong: { vi: 'Khôi phục hệ thống đang cháy mà không tạo thêm nợ kỹ thuật.', en: 'Recover a system on fire without adding new technical debt.' }, phapBao: ['sequential-thinking', 'reviewing-4p-priorities'] },
197
+ huyen: { tamPhap: { vi: 'Mắt người dùng là giám khảo cuối cùng; render rồi mới tin.', en: "The user's eye is the final judge; render before you believe." }, congPhap: { vi: 'Vòng lặp nhìn - sửa - chụp - so sánh cho mọi thay đổi giao diện.', en: 'Look–fix–screenshot–compare loop for every visual change.' }, biThuat: { vi: 'Kiểm tra cả hai theme sáng/tối và mọi breakpoint trước khi giao.', en: 'Verify both light/dark themes and every breakpoint before handoff.' }, thanThong: { vi: 'Biến ý tưởng mơ hồ thành giao diện dùng được, nhất quán.', en: 'Turn a vague idea into a usable, consistent interface.' }, phapBao: ['visual-design-loop', 'parallel-analysis'] },
198
+ 'ngu-thu': { tamPhap: { vi: 'Thuần thú trước, thả thú sau: agent phải có ranh giới trước khi có quyền.', en: 'Tame before releasing: an agent gets boundaries before it gets permissions.' }, congPhap: { vi: 'Mọi bề mặt agent đều qua security review trước khi merge.', en: 'Every agent surface passes security review before merge.' }, biThuat: { vi: 'Nội dung fetch về là dữ liệu, không bao giờ là mệnh lệnh.', en: 'Fetched content is data, never instructions.' }, thanThong: { vi: 'Điều phối nhiều agent/mô hình cho ra kết quả hợp nhất tin cậy.', en: 'Orchestrate multiple agents/models into one trustworthy result.' }, phapBao: ['agentshield-security-review', 'council'] },
199
+ 'huyen-co': { tamPhap: { vi: 'Không tự chế mật mã; độ khó không thay được chứng minh.', en: 'Never roll your own crypto; difficulty is no substitute for proof.' }, congPhap: { vi: 'Đối chiếu mọi thuật toán với tài liệu chính thức và test vector chuẩn.', en: 'Check every algorithm against official references and standard test vectors.' }, biThuat: { vi: 'Chứng minh phản chứng: thử phá giả định của chính mình trước.', en: 'Refutation first: attack your own assumptions before trusting them.' }, thanThong: { vi: 'Giải bài toán phân tích khó bằng lập luận kiểm chứng được.', en: 'Solve hard analytical problems with verifiable reasoning.' }, phapBao: ['clearthought', 'claim'] },
200
+ anh: { tamPhap: { vi: 'Ủy quyền trước, kỹ thuật sau: phạm vi engagement là giới luật.', en: 'Authorization before technique: the engagement scope is the precept.' }, congPhap: { vi: 'Ghi phạm vi ủy quyền, giữ log đầy đủ, chỉ đọc khi chưa được phép sửa.', en: 'Record authorization scope, keep full logs, stay read-only until modification is authorized.' }, biThuat: { vi: 'Tách bằng chứng khỏi suy đoán trong mọi báo cáo điều tra.', en: 'Separate evidence from inference in every investigation report.' }, thanThong: { vi: 'Điều tra có ủy quyền tới kết luận vững mà không vượt phạm vi.', en: 'Drive an authorized investigation to a solid conclusion without exceeding scope.' }, phapBao: ['agentshield-security-review', 'security-scan'] }
201
+ };
202
+
203
+ export function knowledgeFor(pathId) {
204
+ const k = PATH_KNOWLEDGE[pathId] ?? PATH_KNOWLEDGE.kiem;
205
+ return {
206
+ tamPhap: k.tamPhap,
207
+ congPhap: k.congPhap,
208
+ biThuat: k.biThuat,
209
+ thanThong: k.thanThong,
210
+ phapBao: k.phapBao,
211
+ thuatPhap: { vi: 'Các Thuật Pháp cụ thể nằm ở mục "Tâm ma & vòng lặp": mỗi vấn đề kèm một cách hóa giải.', en: 'Concrete Thuật Pháp live in the "Heart demons & loops" section: each problem carries its counter-technique.' },
212
+ daoDien: { vi: 'Đạo Điển của repo: SKILL.md các skill trong .vibekit/skills/ và backbone.yml.', en: "This repo's Đạo Điển: the SKILL.md files under .vibekit/skills/ and backbone.yml." }
213
+ };
214
+ }
215
+
216
+ function buildExplanation(faction, policy, dualUse) {
217
+ const lines = { vi: [], en: [] };
218
+ if (faction.id === 'undetermined') {
219
+ lines.vi.push(`Chưa gán đạo: phát hiện dấu hiệu chủ đích gây hại (${faction.rationale}). Báo cáo dừng gamification và yêu cầu review con người. Đây KHÔNG phải là gán nhãn Tà Đạo tự động — chỉ là từ chối phân loại cho tới khi có review.`);
220
+ lines.en.push(`Faction undetermined: intent-to-harm signals detected (${faction.rationale}). The report withholds gamification and requests human review. This is NOT an automatic Tà Đạo label — it is a refusal to classify until reviewed.`);
221
+ return lines;
222
+ }
223
+ lines.vi.push(`Đạo: ${faction.name} — ${faction.gloss.vi} (độ tin cậy ${faction.confidence}). Căn cứ: ${faction.rationale}.`);
224
+ lines.en.push(`Faction: ${faction.name} — ${faction.gloss.en} (confidence ${faction.confidence}). Basis: ${faction.rationale}.`);
225
+ if (dualUse) {
226
+ lines.vi.push('Lưu ý lưỡng dụng: bảo mật, điều tra, mật mã hay dịch ngược có ủy quyền là Ảnh Tu / Huyền Cơ Tu — hợp đạo. Tà Tu chỉ dành cho chủ đích gây hại; độ khó kỹ thuật không phải là tà.');
227
+ lines.en.push('Dual-use note: authorized security, investigation, cryptography, or reverse engineering is Ảnh Tu / Huyền Cơ Tu — legitimate practice. Tà Tu is reserved for intent to harm; technical difficulty is not evil.');
228
+ }
229
+ if (faction.id === 'ma-dao') {
230
+ const a = faction.authorization;
231
+ if (a.recorded) { lines.vi.push(`Ủy quyền do người dùng khẳng định (chưa xác minh): "${a.reference}".`); lines.en.push(`User-asserted authorization reference (not verified): "${a.reference}".`); }
232
+ else if (a.rejected) { lines.vi.push('Tham chiếu ủy quyền bị từ chối (chứa ký tự không an toàn / giống secret). Cần một slug an toàn: authorization=<chữ-số-gạch>.'); lines.en.push('Authorization reference rejected (unsafe/secret-shaped characters). Provide a safe slug: authorization=<alnum-dash>.'); }
233
+ else { lines.vi.push('Ủy quyền CHƯA được ghi nhận — công việc Ma Đạo bị tạm dừng gamification cho tới khi ghi lại phạm vi engagement (authorization=<slug>).'); lines.en.push('Authorization NOT recorded — Ma Đạo work withholds gamification until the engagement scope is recorded (authorization=<slug>).'); }
234
+ }
235
+ if (policy.state === 'declared-stop') {
236
+ lines.vi.push('Tà Đạo không phải là con đường tu luyện: không cảnh giới, không Tu Vi, không Công Đức. Dừng lại và tìm review con người / ủy quyền hợp pháp.');
237
+ lines.en.push('Tà Đạo is not a cultivation path: no realm, no Tu Vi, no Công Đức. Stop and seek human review / lawful authorization.');
238
+ }
239
+ return lines;
240
+ }
241
+
242
+ export const PROGRESSION = {
243
+ tuVi: { name: 'Tu Vi', gloss: { vi: 'kinh nghiệm tích lũy', en: 'total accumulated experience' } },
244
+ daoHanh: { name: 'Đạo Hạnh', gloss: { vi: 'trải nghiệm thực chiến dài hạn', en: 'long-term practical experience' } },
245
+ ngoTinh: { name: 'Ngộ Tính', gloss: { vi: 'khả năng hiểu, thích nghi, cải thiện giải pháp', en: 'ability to understand, adapt, improve solutions' } },
246
+ doThuanThuc: { name: 'Độ Thuần Thục', gloss: { vi: 'mức thuần thục kỹ thuật', en: 'mastery of a specific technique or method' } },
247
+ tamCanh: { name: 'Tâm Cảnh', gloss: { vi: 'giữ vững hiệu quả trước bất định và bài toán khó', en: 'effectiveness under uncertainty and hard problems' } },
248
+ congDuc: { name: 'Công Đức', gloss: { vi: 'giá trị tích cực từ công việc hoàn thành', en: 'positive value generated by completed work' } },
249
+ nghiepLuc: { name: 'Nghiệp Lực', gloss: { vi: 'rủi ro, nợ kỹ thuật, hệ quả chưa giải quyết', en: 'risk, technical debt, unresolved consequences' } }
250
+ };
251
+
252
+ // Per-event progression contributions, each tied to a unique composite key so
253
+ // accumulation is idempotent: replaying the same evidence adds nothing, and a
254
+ // window with one new event adds only that event's contribution.
255
+ export function progressionContributions(analysis) {
256
+ const issues = analysis.issues ?? {};
257
+ const out = [];
258
+ for (const id of issues.passEventIds ?? []) out.push({ key: `pass:${id}`, tuVi: 1, congDuc: 1, nghiepLuc: 0 });
259
+ for (const r of issues.recoveries ?? []) out.push({ key: `recovery:${r.issueEventId}`, tuVi: 1, congDuc: 1, nghiepLuc: 0 });
260
+ (analysis.commitEventIds ?? []).slice(0, 10).forEach((id) => out.push({ key: `commit:${id}`, tuVi: 1, congDuc: 0, nghiepLuc: 0 }));
261
+ const recovered = new Set((issues.recoveries ?? []).map((r) => r.issueEventId));
262
+ for (const f of issues.failures ?? []) {
263
+ if (!recovered.has(f.eventId)) out.push({ key: `unrec:${f.eventId}`, tuVi: 0, congDuc: 0, nghiepLuc: 2 });
264
+ }
265
+ for (const c of analysis.conflicts ?? []) out.push({ key: `conflict:${(c.eventIds ?? []).join('-')}`, tuVi: 0, congDuc: 0, nghiepLuc: 1 });
266
+ for (const l of analysis.repetition?.retryLoopCandidates ?? []) out.push({ key: `loop:${l.taskId}`, tuVi: 0, congDuc: 0, nghiepLuc: 1 });
267
+ return out;
268
+ }
269
+
270
+ // Idempotent accumulator. `prior` carries lifetime totals plus a salted
271
+ // seen-ledger; only contributions whose salted key is unseen accrue. Positive
272
+ // gains (Tu Vi, Công Đức) and the state ratios are withheld unless the policy
273
+ // is `clear`; Nghiệp Lực (risk) always accrues.
274
+ export function progressionMetrics(analysis, { prior = null, canGamify = true, salt = '' } = {}) {
275
+ const contributions = progressionContributions(analysis);
276
+ const seen = new Set(prior?.seen ?? []);
277
+ const saltKey = (k) => sha16(`${salt}:${k}`);
278
+ const fresh = contributions.filter((c) => !seen.has(saltKey(c.key)));
279
+ const overlap = contributions.length - fresh.length;
280
+
281
+ const sum = (field) => fresh.reduce((n, c) => n + c[field], 0);
282
+ const windowTuVi = canGamify ? sum('tuVi') : 0;
283
+ const windowCongDuc = canGamify ? sum('congDuc') : 0;
284
+ const windowNghiepLuc = sum('nghiepLuc');
285
+ const hadFresh = fresh.length > 0;
286
+
287
+ const nextSeen = [...seen, ...fresh.map((c) => saltKey(c.key))].sort();
288
+
289
+ // State ratios (not accumulators) — withheld under a non-clear policy.
290
+ const issues = analysis.issues ?? {};
291
+ const passes = issues.passes ?? 0;
292
+ const failures = (issues.failures ?? []).length;
293
+ const recoveries = (issues.recoveries ?? []).length;
294
+ const userPrompts = analysis.coverage?.userPrompts ?? 0;
295
+ const retryPrompts = (analysis.repetition?.retryLoopCandidates ?? []).reduce((n, l) => n + l.count, 0);
296
+ const ratio = (v) => (canGamify ? round3(clamp01(v)) : null);
297
+
298
+ return {
299
+ tuVi: { window: windowTuVi, lifetime: (prior?.tuVi?.lifetime ?? 0) + windowTuVi },
300
+ daoHanh: { windows: (prior?.daoHanh?.windows ?? 0) + (hadFresh ? 1 : 0) },
301
+ ngoTinh: ratio(0.5 + 0.5 * (failures ? recoveries / failures : 0.5) - 0.3 * (userPrompts ? retryPrompts / userPrompts : 0)),
302
+ doThuanThuc: canGamify
303
+ ? { overall: round3(clamp01(passes + failures === 0 ? 0.3 : (passes + recoveries) / (passes + failures + 1))), note: { vi: 'V1 đo mức thuần thục tổng; thuần thục theo từng đạo tu cần bằng chứng gắn theo path.', en: 'V1 tracks overall mastery; per-path mastery needs path-tagged evidence.' } }
304
+ : null,
305
+ tamCanh: ratio(failures === 0 ? 0.7 : recoveries / failures),
306
+ congDuc: { window: windowCongDuc, lifetime: (prior?.congDuc?.lifetime ?? 0) + windowCongDuc },
307
+ nghiepLuc: { window: windowNghiepLuc, lifetime: (prior?.nghiepLuc?.lifetime ?? 0) + windowNghiepLuc },
308
+ seen: nextSeen,
309
+ overlap
310
+ };
311
+ }