Files
solution-erp/.claude/workflows/hmw.js
pqhuy1987 81b59f0389
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 5m23s
[CLAUDE] Workflow: adopt presence-not-age selector guardrail + rec-3 hmw.js STOP-HARD (S115)
Adopt AI_INFRA 2026-07-13 broadcast ab6c387e (presence-not-age selector,
type=update) + directed 6c32df89 rec-3, via /fable-clone 5-lane reviewer
ensemble (wf_b621aac4-f0b) -> spec -> /fable-real deep-pass (PASS-WITH-FIXES,
M1+M2 applied) -> HMW execute (em-main solo; governance single-writer D9).

D2 (hmw.js): unknown-role fail-soft-WARN -> up-front STOP-HARD throw (before
  parallel; preserves null/'' role-less inherit-lead path). node --check + stub
  7/7. Doc-sync 5 live lines (ultra-on/README/harness-11-engine/runbook).
D3 (memory-archive-gate.ps1): value_protect advisory-flag -> pre-selection
  HARD-SKIP (value-primary; heading-only spans; non-contiguous byte accum) +
  value-floor WARN. Fault-inject ALL PASS + real regression A7 242/242. DRY-RUN.
D1 (reinject-ledger.md): presence re-verify stamp + 3 honest-notes + BUILD-GAP.

Re-verify: reinject (i) + MFE age-band (iii) already COMPLIANT; only the
archive-gate age-trace needed hardening. D3 = defense-in-depth codify, NOT
leak-closure (9-token grep unchanged; em-main value-scan stays the guarantee).

adap-report + email AI_INFRA (8b9dc5165d5a); inbox STAGE-2 processed. No new
User-Mark (codify-only). #53 garble x1 (lane-4) recovered from disk, 0 loss.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 12:25:24 +07:00

173 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// hmw.js — HMW P2 (Execute) workflow cho SOLUTION_ERP. CHẠY bởi Workflow runtime (body wrap async →
// top-level await/return hợp lệ); KHÔNG node-runnable trực tiếp (`node hmw.js` sẽ lỗi await).
// Em main lo P0/P1/P3/P4 NGOÀI workflow; script này CHỈ lo P2 fan-out.
// Invoke bằng {scriptPath} (no hot-reload — restart/re-invoke sau khi sửa). Scope = repo SOLUTION_ERP ONLY (S1).
// ⚠️ Script chạy JS-sandbox KHÔNG filesystem → KHÔNG tự tạo folder/ghi file. Scaffold run-folder runs/<run-id>/ (TRACKED) = EM MAIN @P1 (Harness-10, supersedes Harness 2 B3 wave-folder).
export const meta = {
name: 'hmw',
description: 'HMW P2 execute (SOLUTION_ERP) — fan-out 9-agent roster có MEMORY-PACK slice (qua args vì script không đọc file) + return findings + checklistEvidence + memoryDelta (spawn-record 4-field). 2 MODE (Harness 2, 06-07): (A) DEFAULT return-delta-only — fan-out NHỎ (<3 task VÀ ≤5 phút), sub KHÔNG ghi file, git-diff verify. (B) RUN-TRACE mode (args.run, Harness-10) — 🔴 BẮT BUỘC khi run ≥3 task HOẶC ước >5 phút (sàn H22 S111; script no-fs KHÔNG tự ép — enforcement = em-main scaffold @P1 + set args.run) — workflow DÀI, em main scaffold .claude/workflows/runs/<run-id>/ TRACKED FLAT (run.md + sub-<role>-<i>.md + <stage>-synthesis.md phẳng cùng cấp) @P1, sub ghi full-detail vào CHỈ sub-<role>-<i>.md mình (B4/B6), harvest per-turn primary (C4) + H2 gom @session-end = backstop verify-idempotent. taskList thoải mái (queue theo slot, không cap cứng). memoryDelta KHÔNG tự ghi — em main VERIFY + APPEND-only @P3 (no-overwrite-unverified, B3). Model H8 all-inherit (Harness-8 2026-06-16): role-có-frontmatter inherit top-tier lead · role-less inherit · per-task tier:\'fable\'|\'opus\' escape-hatch. Scope = repo SOLUTION_ERP ONLY (S1 — KHÔNG fan-out repo/corpus khác).',
phases: [{ title: 'Execute', detail: 'fan-out memory-pack-injected agents, structured return' }],
}
// ─── args (em main bơm @P2 sau khi P1 chốt) ──────────────────────────────────
// args = {
// memoryPack: { 'investigator-codebase':'<slice>', 'implementer-backend':'...', reviewer:'...', ... }, // SLICE liên quan, KHÔNG full
// spec: '<acceptance-criteria / context chung>',
// checkpointApproved: true, // em main set SAU khi BÁO {số agent·vai·task} @inform (S2)
// taskList: [ { role:<VALID_ROLES|null>, label:'..', prompt:'..', tier:'fable'|'opus'? }, ... ] // tier = per-task model override (H4.5)
// run: { name:'<run-id>', dir:'.claude/workflows/runs/<run-id>' } // 🔴 BẮT BUỘC khi run ≥3 task HOẶC ước >5 phút (sàn H22 S111 — chết giữa run còn vật-liệu đĩa cho /tiep; dưới ngưỡng = tùy chọn) — bật RUN-TRACE mode (B, Harness-10 TRACKED). Folder + run.md em main ĐÃ scaffold @P1 (script no-fs). [legacy alias: args.wave]
// }
const VALID_ROLES = [
'investigator-codebase', 'investigator-api',
'implementer-backend', 'implementer-frontend',
'test-specialist', 'reviewer', 'cicd-monitor', 'frontend-designer',
'database-agent', // +S57 — S56 dùng 3× qua fail-soft WARN; read-advisory DB lens (DB1-DB11)
'office-document', // +S107 — Office document WRITE specialist (OD1-OD10; docx/xlsx/pptx/pdf + form-engine)
'tooling-auditor', 'harvest-curator', // +S110 anh-directed (H21 roster-parity lệnh-B ensemble; supersede
// điểm H6-design "monitor ngoài workflow" — monitor VẪN INFORM-only, lane RETURN-only nên không xung đột)
]
// ─── H8 all-inherit top-tier (Harness-8 adopt 2026-06-16 — thay thế two-tier H4.5) ──
// MỌI sub-agent có memory → frontmatter `model: inherit` = ăn top-tier lead (runtime PER-SESSION
// outage-driven — BƯỚC 0.6 probe mỗi phiên; flip-chain canonical → docs/STATUS.md §Sub-agents.
// KHÔNG hardcode model hiện-hành ở comment — lesson S108: comment stale làm 2/4 worker đọc sai runtime).
// KHÔNG còn demote-pin `claude-opus-4-8` (H4.5 đã gỡ).
// hmw KHÔNG set model cho role-có-frontmatter → return undefined, frontmatter (inherit) tự lo.
// Role-less (H6.2 governed-ultracode): default = inherit lead-model (top-tier) — KHÔNG pin rẻ làm default.
// H8.2 "workflow nhanh nhất" = song song tối đa + xuất nhanh, KHÔNG hạ model làm rẻ.
// Escape-hatch per-task tier:'opus' GIỮ cho sweep/cost (ngoại lệ có chủ đích); tier:'fable' CHỈ hợp lệ
// trong lượt lệnh engine-đắt anh gõ kèm vai (/fable-real|/fable-clone <vai> <đề-bài> — H21 S110);
// lead KHÔNG tự ý elevate theo phán-đoán riêng (MTv3 §1.3: đường DUY NHẤT nâng 1 vai lên hạng-nhất = lệnh owner).
function resolveModel(role, rawRole, tier, i) {
if (tier === 'fable' || tier === 'opus') return tier
if (tier) log(`⚠️ hmw: tier "${tier}" lạ (task #${i}) → bỏ qua, dùng mặc định H8 (inherit top-tier)`)
// Role-less (null) → inherit lead; invalid non-empty role đã THROW up-front (STOP-HARD, DIRECTED REC-3 2026-07-13)
// → nhánh này giờ CHỈ đạt bởi role-less thật (rawRole null/''); giữ làm defensive no-op.
if (!role && rawRole) return undefined
if (!role) { log(`hmw: task #${i} role-less → inherit lead-model (H6.2 governed-ultracode; per-task tier:'opus' = escape-hatch sweep/cost)`); return undefined }
return undefined // role có frontmatter: tất cả `inherit` (H8 all-inherit top-tier) — KHÔNG override
}
const SCHEMA = {
type: 'object',
required: ['findings', 'memoryDelta'],
properties: {
findings: { type: 'string', description: 'Kết quả chính. MỌI claim kèm evidence file:line. KHÔNG narrative suông.' },
checklistEvidence: { type: 'string', description: 'Bằng chứng cho acceptance-checklist P1 (số đo / PASS-FAIL / verdict).' },
subMdPath: { type: 'string', description: 'RUN-TRACE mode FLAT: đường-dẫn sub-<role>-<i>.md agent đã ghi (em main/H2 đọc on-demand). DEFAULT-mode: bỏ trống.' },
memoryDelta: {
type: 'object',
description: 'Spawn-record 4-field — RETURN-only để EM MAIN harvest @P3. Agent KHÔNG tự ghi ký ức (KHÔNG file MEMORY.md, KHÔNG store_memory/RAG). Em main VERIFY + APPEND-only (KHÔNG overwrite entry cũ nếu chưa kiểm tra — B3).',
required: ['task', 'verdict', 'learned', 'surprise'],
properties: {
task: { type: 'string', description: 'việc gì (1 dòng)' },
verdict: { type: 'string', description: 'kết luận / PASS-FAIL / root-cause' },
learned: { type: 'string', description: 'pattern / anti-pattern rút ra' },
surprise: { type: 'string', description: 'edge-case / bất ngờ (chống mất discovery)' },
},
},
},
}
// S4b — args có thể tới OBJECT hoặc JSON-STRING (harness đôi khi stringify object args) → normalize defensive
const A = (typeof args === 'string') ? JSON.parse(args) : (args || {})
if (!A || !Array.isArray(A.taskList) || A.taskList.length === 0) {
throw new Error('hmw: cần args.taskList (mảng {role,label,prompt}) — em main bơm @P1. (đã thử JSON.parse nếu args bị stringify.)')
}
// S2 mechanize: checkpoint TRƯỚC P2 = gate CỨNG, không chỉ prompt. Em main BÁO {số agent·vai·task} @inform
// (KHÔNG chờ confirm) → set args.checkpointApproved=true → fan-out. Flag GIỮ = anti-accidental-fire
// (call quên-set-flag → throw, chặn 515K-class accidental).
if (A.checkpointApproved !== true) {
throw new Error('hmw: checkpointApproved chưa set — em-main BÁO {số agent·vai·task} @inform rồi set args.checkpointApproved=true (guard = anti-accidental-fire).')
}
// S4 — số task THOẢI MÁI: harness chạy theo slot, dư tự queue, KHÔNG cap cứng (soft notice only).
if (A.taskList.length > 16) {
log(`hmw: taskList=${A.taskList.length} (>16) → harness queue theo slot (thoải mái, không cap cứng).`)
}
// ─── STOP-HARD role-whitelist (DIRECTED 6c32df89 REC-3, 2026-07-13 · S115) ────
// Vai ∉ VALID_ROLES (typo / rename-drift) = DỪNG HẲN + báo owner — KHÔNG fail-soft
// về default subagent (fail-soft = "đứt âm-thầm" đã gây lỗi thật hub-side; sim 5-ca).
// PHÂN-BIỆT (backward-compat H6.2): role null/omitted/'' = HỢP-LỆ role-less (inherit
// lead) → KHÔNG throw. CHỈ non-empty-string ∉ whitelist mới throw. Validate UP-FRONT
// (trước parallel) — halt KHÔNG phụ-thuộc semantics parallel()/.filter(Boolean) (per-lane
// throw có thể bị nuốt thành null = STOP-SILENT, tệ hơn). Mirror checkpointApproved tripwire.
const badRoles = A.taskList
.map((t, i) => ({ i, raw: t && t.role }))
.filter(x => x.raw != null && x.raw !== '' && !VALID_ROLES.includes(x.raw))
if (badRoles.length > 0) {
const detail = badRoles.map(x => `#${x.i}="${x.raw}"`).join(', ')
throw new Error(
`hmw: vai ∉ VALID_ROLES (${detail}) — DỪNG HẲN (STOP-HARD). ` +
`Sửa typo HOẶC báo owner thêm vai vào VALID_ROLES [${VALID_ROLES.join(', ')}]. ` +
`KHÔNG fail-soft về default subagent (DIRECTED 6c32df89 REC-3 2026-07-13).`)
}
const memoryPack = A.memoryPack || {}
const spec = A.spec || ''
// ─── RUN-TRACE mode (Harness-10, supersedes Harness-2 wave-mode B) ────────────
// run = { name, dir }. Folder runs/<run-id>/ (TRACKED) + run.md em main ĐÃ scaffold @P1 (script no-fs). Bật → sub ghi full-detail
// vào CHỈ sub-<role>-<i>.md phẳng mình + return memoryDelta. Containment: tracked-change NGOÀI run-folder + code-disjoint = vi-phạm
// (run-folder TRACKED → HIỆN trong git-diff = audit trực-tiếp; em main git-diff post-P2 + chunk-count RAG). [legacy alias args.wave]
const wave = (A.run && A.run.dir) ? A.run : ((A.wave && A.wave.dir) ? A.wave : null)
if (wave) log(`hmw: RUN-TRACE mode on → dir=${wave.dir} (TRACKED FLAT; sub ghi sub-<role>-<i>.md phẳng isolated; em main scaffold @P1; harvest per-turn primary C4, H2 gom @session-end = backstop).`)
phase('Execute')
log(`HMW P2: fan-out ${A.taskList.length} task (${wave ? 'RUN-TRACE' : 'return-delta-only'}, H8 all-inherit top-tier, memory-pack-injected, scope=SOLUTION_ERP repo only)`)
const results = await parallel(A.taskList.map((t, i) => () => {
const raw = t && t.role
// STOP-HARD validate up-front (DIRECTED REC-3 2026-07-13): raw ở đây CHỈ có thể ∈ VALID_ROLES HOẶC null/'' (role-less H6.2).
const role = VALID_ROLES.includes(raw) ? raw : undefined // role-less (null/'') → undefined → inherit lead
const mem = role && memoryPack[role] ? memoryPack[role] : ''
const subMd = wave ? `${wave.dir}/sub-${role || 'task'}-${i}.md` : null // Harness-10 FLAT (h10-refine 2026-06-18): sub-<role>-<i>.md phẳng cùng cấp dưới runs/<run-id>/ — KHÔNG sub-md/ subdir
// Write-guard TOOL-AWARE theo MODE (B6 isolation). SE read-only sub (KHÔNG Write tool): investigator-codebase/api,
// reviewer, cicd-monitor (+ monitor tooling-auditor/harvest-curator). Write sub: implementer-backend/frontend, test-specialist, frontend-designer.
const writeGuard = wave
? [
`## ✍️ RUN-TRACE ghi sub-<role>-<i>.md FLAT (Harness-10 h10-refine, supersedes subfolder sub-md/) — TOOL-AWARE (chống mojibake G-009):`,
`- Full-detail công-việc của mày → ĐÚNG 1 file: \`${subMd}\` (folder đã scaffold sẵn — KHÔNG tạo folder).`,
` • NẾU mày CÓ Write/Edit tool (implementer-backend/frontend, test-specialist, frontend-designer): GHI TRỰC TIẾP via Write/Edit. 🔴 KHÔNG Bash-write MD ($-expansion/mojibake).`,
` • NẾU mày CHỈ có Bash (read-only sub: investigator-codebase/api, reviewer, cicd-monitor — KHÔNG Write tool): 🔴 TUYỆT ĐỐI KHÔNG Bash-write MD → để full-detail trong "findings" + đặt subMdPath="${subMd}"; EM MAIN scribe @P3 (single-writer Write-tool, no-corruption).`,
`- 🔴 ISOLATION (B6→Harness-10, AUDIT): CHỈ ghi \`${subMd}\` (+ code-file-disjoint nếu task giao). TUYỆT ĐỐI KHÔNG ghi/sửa: agent-memory/* (MEMORY.md BẤT KỲ sub) · MD canonical (CLAUDE/README/STATUS/agents) · sub-MD agent khác. Em main git-status/diff audit sau P2 — tracked-file đổi NGOÀI run-folder (runs/<run-id>/) + code-disjoint = vi-phạm (run-folder TRACKED → HIỆN trong diff).`,
`- LUÔN return: findings (FULL) + checklistEvidence + memoryDelta (4-field) + subMdPath="${subMd}". Harvest per-turn primary (C4); H2 gom @session-end = backstop verify-idempotent → agent-memory/${role || 'sub'}.`,
`- 🔴 KHÔNG store_memory/RAG-write · KHÔNG Bash curl/HTTP Qdrant (:6333 = git-diff MÙ, chỉ chunk-count bắt) · KHÔNG ghi file NGOÀI repo/run-folder. RAG single-writer=em main; containment = git-diff(in-repo)+chunk-count(RAG) [G-015].`,
].join('\n')
: [
`## OUTPUT write-guard (DEFAULT return-delta-only):`,
`- ⚠️ KHÔNG ghi ký ức kênh nào: KHÔNG file MEMORY.md, KHÔNG store_memory/RAG-write (Qdrant). CHỈ return memoryDelta → em main VERIFY + APPEND-only @P3 (B3). KHÔNG overwrite file/chunk của sub khác.`,
`- ⚠️ Nếu task có WRITE file: CHỈ file-disjoint được giao (em main git-diff verify sau P2). KHÔNG đụng file ngoài phạm vi. Scope = repo SOLUTION_ERP only (S1).`,
].join('\n')
const prompt = [
mem ? `## MEMORY-PACK (${role}) — SLICE ký ức tích lũy của sub này, ĐỌC trước khi làm (KHÔNG phải full memory):\n${mem}\n` : '',
spec ? `## SPEC / acceptance-criteria (chung):\n${spec}\n` : '',
`## TASK:\n${(t && t.prompt) || '(thiếu prompt — lỗi taskList @P0)'}`,
[
'## OUTPUT (structured bắt buộc):',
'- findings: kết quả + evidence file:line (KHÔNG narrative suông).',
'- checklistEvidence: số đo / verdict cho acceptance-checklist.',
'- memoryDelta {task·verdict·learned·surprise}: để EM MAIN harvest @P3.',
wave ? '- subMdPath: đường-dẫn sub-MD mày đã ghi.' : '',
].filter(Boolean).join('\n'),
writeGuard,
].filter(Boolean).join('\n')
return agent(prompt, {
agentType: role || undefined,
schema: SCHEMA,
label: (t && t.label) || `hmw:${role || 'task'}-${i}`,
model: resolveModel(role, raw, t && t.tier, i), // H8 all-inherit (undefined = theo frontmatter = inherit)
})
}))
// trả mảng kết quả (lọc null nếu agent lỗi/null — invalid-role đã STOP-HARD up-front; .filter(Boolean) chỉ lọc null-lane do agent lỗi runtime)
// về em main → P3 VERIFY + harvest + P4 checklist
return results.filter(Boolean)