agentlock-harness 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +211 -2
- package/README.zh-CN.md +211 -0
- package/RELEASE_NOTES.md +35 -0
- package/bin/agentlock-harness.mjs +249 -0
- package/harness-templates/en-US/common/CLAUDE.md.tmpl +7 -0
- package/harness-templates/en-US/common/GEMINI.md.tmpl +7 -0
- package/harness-templates/en-US/common/agentlock-harness.json.tmpl +45 -0
- package/harness-templates/en-US/common/claude-settings.json +36 -0
- package/harness-templates/en-US/common/codex-config.toml.tmpl +11 -0
- package/harness-templates/en-US/common/copilot-instructions.md.tmpl +3 -0
- package/harness-templates/en-US/common/gemini-settings.json +42 -0
- package/harness-templates/en-US/common/git-hooks/pre-commit +24 -0
- package/harness-templates/en-US/common/git-hooks/pre-push +11 -0
- package/harness-templates/en-US/common/harness-gitignore +3 -0
- package/harness-templates/en-US/common/hooks/post-edit-check.mjs +57 -0
- package/harness-templates/en-US/common/hooks/pre-tool-guard.mjs +122 -0
- package/harness-templates/en-US/common/hooks/rules-drift-check.mjs +69 -0
- package/harness-templates/en-US/common/hooks/staged-guard.mjs +197 -0
- package/harness-templates/en-US/common/hooks/stop-gate.mjs +164 -0
- package/harness-templates/en-US/common/rules/00-testing-integrity.md +11 -0
- package/harness-templates/en-US/common/rules/01-security-boundaries.md +11 -0
- package/harness-templates/en-US/common/skills/atomic-tdd/SKILL.md +21 -0
- package/harness-templates/en-US/common/skills/brainstorming/SKILL.md +24 -0
- package/harness-templates/en-US/common/skills/code-grounding/SKILL.md +20 -0
- package/harness-templates/en-US/common/skills/cross-model-review/SKILL.md +22 -0
- package/harness-templates/en-US/common/skills/worktree-isolation/SKILL.md +19 -0
- package/harness-templates/en-US/dual-core/HARNESS_GUIDE.md +19 -0
- package/harness-templates/en-US/dual-core/scripts/cross-review.mjs +141 -0
- package/harness-templates/en-US/enterprise-platform/ci/agentlock-harness-gate.yml +32 -0
- package/harness-templates/en-US/enterprise-platform/governance/mcp-gateway.template.json +18 -0
- package/harness-templates/en-US/enterprise-platform/governance/policy.json +26 -0
- package/harness-templates/en-US/ralph-factory/PROMPT.loop.md.tmpl +12 -0
- package/harness-templates/en-US/ralph-factory/SPRINT_CONTRACT.md.tmpl +25 -0
- package/harness-templates/en-US/ralph-factory/sandbox/Dockerfile.sandbox +13 -0
- package/harness-templates/en-US/ralph-factory/sandbox/docker-compose.sandbox.yml +22 -0
- package/harness-templates/en-US/ralph-factory/sandbox/run-sandbox-loop.sh +8 -0
- package/harness-templates/zh-CN/common/CLAUDE.md.tmpl +7 -0
- package/harness-templates/zh-CN/common/GEMINI.md.tmpl +7 -0
- package/harness-templates/zh-CN/common/agentlock-harness.json.tmpl +45 -0
- package/harness-templates/zh-CN/common/claude-settings.json +36 -0
- package/harness-templates/zh-CN/common/codex-config.toml.tmpl +11 -0
- package/harness-templates/zh-CN/common/copilot-instructions.md.tmpl +3 -0
- package/harness-templates/zh-CN/common/gemini-settings.json +42 -0
- package/harness-templates/zh-CN/common/git-hooks/pre-commit +24 -0
- package/harness-templates/zh-CN/common/git-hooks/pre-push +11 -0
- package/harness-templates/zh-CN/common/harness-gitignore +3 -0
- package/harness-templates/zh-CN/common/hooks/post-edit-check.mjs +57 -0
- package/harness-templates/zh-CN/common/hooks/pre-tool-guard.mjs +122 -0
- package/harness-templates/zh-CN/common/hooks/rules-drift-check.mjs +69 -0
- package/harness-templates/zh-CN/common/hooks/staged-guard.mjs +197 -0
- package/harness-templates/zh-CN/common/hooks/stop-gate.mjs +164 -0
- package/harness-templates/zh-CN/common/rules/00-testing-integrity.md +11 -0
- package/harness-templates/zh-CN/common/rules/01-security-boundaries.md +11 -0
- package/harness-templates/zh-CN/common/skills/atomic-tdd/SKILL.md +21 -0
- package/harness-templates/zh-CN/common/skills/brainstorming/SKILL.md +24 -0
- package/harness-templates/zh-CN/common/skills/code-grounding/SKILL.md +20 -0
- package/harness-templates/zh-CN/common/skills/cross-model-review/SKILL.md +22 -0
- package/harness-templates/zh-CN/common/skills/worktree-isolation/SKILL.md +19 -0
- package/harness-templates/zh-CN/dual-core/HARNESS_GUIDE.md +19 -0
- package/harness-templates/zh-CN/dual-core/scripts/cross-review.mjs +141 -0
- package/harness-templates/zh-CN/enterprise-platform/ci/agentlock-harness-gate.yml +32 -0
- package/harness-templates/zh-CN/enterprise-platform/governance/mcp-gateway.template.json +18 -0
- package/harness-templates/zh-CN/enterprise-platform/governance/policy.json +26 -0
- package/harness-templates/zh-CN/ralph-factory/PROMPT.loop.md.tmpl +12 -0
- package/harness-templates/zh-CN/ralph-factory/SPRINT_CONTRACT.md.tmpl +25 -0
- package/harness-templates/zh-CN/ralph-factory/sandbox/Dockerfile.sandbox +13 -0
- package/harness-templates/zh-CN/ralph-factory/sandbox/docker-compose.sandbox.yml +22 -0
- package/harness-templates/zh-CN/ralph-factory/sandbox/run-sandbox-loop.sh +8 -0
- package/package.json +64 -4
- package/scripts/bootstrap.ps1 +13 -0
- package/scripts/bootstrap.sh +23 -0
- package/src/cli/colors.mjs +42 -0
- package/src/cli/commands/adopt.mjs +378 -0
- package/src/cli/commands/change.mjs +92 -0
- package/src/cli/commands/doctor.mjs +56 -0
- package/src/cli/commands/eval.mjs +193 -0
- package/src/cli/commands/hooks.mjs +97 -0
- package/src/cli/commands/init.mjs +231 -0
- package/src/cli/commands/passthrough.mjs +27 -0
- package/src/cli/commands/ralph.mjs +208 -0
- package/src/cli/commands/rules.mjs +73 -0
- package/src/cli/commands/stats.mjs +71 -0
- package/src/cli/commands/task.mjs +123 -0
- package/src/cli/commands/ui.mjs +84 -0
- package/src/cli/commands/verify.mjs +267 -0
- package/src/cli/prompt.mjs +55 -0
- package/src/core/adopt.mjs +807 -0
- package/src/core/agent-runner.mjs +118 -0
- package/src/core/audit.mjs +181 -0
- package/src/core/catalog.mjs +160 -0
- package/src/core/change-flow.mjs +344 -0
- package/src/core/detector.mjs +141 -0
- package/src/core/doc-drift.mjs +94 -0
- package/src/core/eval-fixtures.mjs +676 -0
- package/src/core/eval-frontier-fixtures.mjs +657 -0
- package/src/core/eval-hard-fixtures.mjs +923 -0
- package/src/core/eval-runner.mjs +754 -0
- package/src/core/eval-telemetry.mjs +338 -0
- package/src/core/harness-writer.mjs +286 -0
- package/src/core/installer.mjs +42 -0
- package/src/core/rules-compiler.mjs +356 -0
- package/src/core/task-ledger.mjs +327 -0
- package/src/core/version.mjs +10 -0
- package/src/ui/public/app.mjs +2199 -0
- package/src/ui/public/index.html +203 -0
- package/src/ui/public/styles.css +1200 -0
- package/src/ui/server.mjs +457 -0
- package/src/ui/service.mjs +860 -0
- package/templates/en-US/AGENTS.md +38 -0
- package/templates/en-US/DOCS_MAINTENANCE.md +65 -0
- package/templates/en-US/MIGRATION.md +46 -0
- package/templates/en-US/NEW_PROJECT_CHECKLIST.md +46 -0
- package/templates/en-US/README.md +41 -0
- package/templates/en-US/SESSION.md +29 -0
- package/templates/en-US/docs/00-context.md +38 -0
- package/templates/en-US/docs/01-vision/README.md +36 -0
- package/templates/en-US/docs/02-requirements/PRD.md +24 -0
- package/templates/en-US/docs/02-requirements/glossary.md +20 -0
- package/templates/en-US/docs/02-requirements/use-cases.md +36 -0
- package/templates/en-US/docs/03-architecture/composite-ai-framework.md +36 -0
- package/templates/en-US/docs/03-architecture/integration-architecture.md +36 -0
- package/templates/en-US/docs/03-architecture/system-architecture.md +16 -0
- package/templates/en-US/docs/04-design/README.md +21 -0
- package/templates/en-US/docs/04-design/a2a-integration-spec.md +36 -0
- package/templates/en-US/docs/04-design/agent-specs.md +36 -0
- package/templates/en-US/docs/04-design/data-model.md +18 -0
- package/templates/en-US/docs/04-design/external-api-spec.md +26 -0
- package/templates/en-US/docs/04-design/mcp-interface-spec.md +36 -0
- package/templates/en-US/docs/04-design/phase1-minimal-implementation-interfaces.md +36 -0
- package/templates/en-US/docs/04-design/responsibility-model.md +36 -0
- package/templates/en-US/docs/04-design/runtime-control-plane-spec.md +36 -0
- package/templates/en-US/docs/04-design/safety-governance.md +18 -0
- package/templates/en-US/docs/04-design/sample-scenarios-architecture-refinement.md +20 -0
- package/templates/en-US/docs/04-design/skill-syntax-spec.md +36 -0
- package/templates/en-US/docs/04-design/storage-schema.md +18 -0
- package/templates/en-US/docs/04-design/task-capability-architecture-and-evolution.md +36 -0
- package/templates/en-US/docs/05-project/adr/ADR-000-template.md +32 -0
- package/templates/en-US/docs/05-project/adr/README.md +15 -0
- package/templates/en-US/docs/05-project/doc-code-map.md +17 -0
- package/templates/en-US/docs/05-project/evolution-backlog.md +14 -0
- package/templates/en-US/docs/05-project/feature-registry.md +16 -0
- package/templates/en-US/docs/05-project/master-delivery-tracker.md +14 -0
- package/templates/en-US/docs/05-project/risk-register.md +36 -0
- package/templates/en-US/docs/05-project/roadmap.md +36 -0
- package/templates/en-US/docs/05-project/stage-view.md +14 -0
- package/templates/en-US/docs/05-project/tech-stack.md +36 -0
- package/templates/en-US/docs/06-dev-guide/SPEC.md +18 -0
- package/templates/en-US/docs/06-dev-guide/coding-standards.md +36 -0
- package/templates/en-US/docs/06-dev-guide/deployment-architecture.md +20 -0
- package/templates/en-US/docs/06-dev-guide/project-scaffold.md +16 -0
- package/templates/en-US/docs/06-dev-guide/testing-strategy.md +42 -0
- package/templates/en-US/docs/07-frontend/README.md +36 -0
- package/templates/en-US/docs/07-frontend/user-personas.md +36 -0
- package/templates/en-US/docs/08-process/README.md +27 -0
- package/templates/en-US/docs/08-process/ai-collaboration-protocol.md +28 -0
- package/templates/en-US/docs/08-process/autopilot.md +18 -0
- package/templates/en-US/docs/08-process/code-grounding.md +32 -0
- package/templates/en-US/docs/08-process/context-loading-strategy.md +35 -0
- package/templates/en-US/docs/08-process/conventions.md +75 -0
- package/templates/en-US/docs/08-process/debugging.md +25 -0
- package/templates/en-US/docs/08-process/design-gate.md +22 -0
- package/templates/en-US/docs/08-process/git-protocol.md +20 -0
- package/templates/en-US/docs/08-process/multi-agent-orchestration.md +27 -0
- package/templates/en-US/docs/08-process/planning.md +18 -0
- package/templates/en-US/docs/08-process/project-intake.md +47 -0
- package/templates/en-US/docs/08-process/reflection.md +18 -0
- package/templates/en-US/docs/08-process/review.md +30 -0
- package/templates/en-US/docs/08-process/session-handoff.md +27 -0
- package/templates/en-US/docs/08-process/tdd.md +24 -0
- package/templates/en-US/docs/08-process/tool-execution.md +32 -0
- package/templates/en-US/docs/08-process/workflow-contract.md +46 -0
- package/templates/en-US/docs/08-process/workflow.md +23 -0
- package/templates/en-US/docs/README.md +58 -0
- package/templates/en-US/docs/design-checklist.md +36 -0
- package/templates/en-US/docs/discussions/README.md +13 -0
- package/templates/en-US/docs/plans/README.md +13 -0
- package/templates/en-US/docs/proposed-design/README.md +13 -0
- package/templates/en-US/docs/temp-reference/README.md +11 -0
- package/templates/en-US/docs.config.json +46 -0
- package/templates/en-US/profiles/README.md +23 -0
- package/templates/en-US/profiles/agent-platform/README.md +23 -0
- package/templates/en-US/profiles/cli-tool/README.md +23 -0
- package/templates/en-US/profiles/library-sdk/README.md +23 -0
- package/templates/en-US/profiles/multi-agent/README.md +23 -0
- package/templates/en-US/profiles/profiles.json +31 -0
- package/templates/en-US/profiles/software-automation/README.md +23 -0
- package/templates/en-US/profiles/web-saas/README.md +23 -0
- package/templates/en-US/scripts/README.md +89 -0
- package/templates/en-US/scripts/doc-find.mjs +156 -0
- package/templates/en-US/scripts/doc-map.mjs +50 -0
- package/templates/en-US/scripts/doc-tools.mjs +311 -0
- package/templates/en-US/scripts/init-docs.mjs +214 -0
- package/templates/en-US/scripts/validate-docs.mjs +141 -0
- package/templates/zh-CN/AGENTS.md +38 -0
- package/templates/zh-CN/DOCS_MAINTENANCE.md +77 -0
- package/templates/zh-CN/MIGRATION.md +45 -0
- package/templates/zh-CN/NEW_PROJECT_CHECKLIST.md +54 -0
- package/templates/zh-CN/README.md +55 -0
- package/templates/zh-CN/SESSION.md +29 -0
- package/templates/zh-CN/docs/00-context.md +42 -0
- package/templates/zh-CN/docs/01-vision/README.md +33 -0
- package/templates/zh-CN/docs/02-requirements/PRD.md +26 -0
- package/templates/zh-CN/docs/02-requirements/glossary.md +35 -0
- package/templates/zh-CN/docs/02-requirements/use-cases.md +31 -0
- package/templates/zh-CN/docs/03-architecture/composite-ai-framework.md +27 -0
- package/templates/zh-CN/docs/03-architecture/integration-architecture.md +30 -0
- package/templates/zh-CN/docs/03-architecture/system-architecture.md +26 -0
- package/templates/zh-CN/docs/04-design/README.md +21 -0
- package/templates/zh-CN/docs/04-design/a2a-integration-spec.md +45 -0
- package/templates/zh-CN/docs/04-design/agent-specs.md +46 -0
- package/templates/zh-CN/docs/04-design/data-model.md +18 -0
- package/templates/zh-CN/docs/04-design/external-api-spec.md +34 -0
- package/templates/zh-CN/docs/04-design/mcp-interface-spec.md +44 -0
- package/templates/zh-CN/docs/04-design/phase1-minimal-implementation-interfaces.md +38 -0
- package/templates/zh-CN/docs/04-design/responsibility-model.md +37 -0
- package/templates/zh-CN/docs/04-design/runtime-control-plane-spec.md +47 -0
- package/templates/zh-CN/docs/04-design/safety-governance.md +18 -0
- package/templates/zh-CN/docs/04-design/sample-scenarios-architecture-refinement.md +38 -0
- package/templates/zh-CN/docs/04-design/skill-syntax-spec.md +43 -0
- package/templates/zh-CN/docs/04-design/storage-schema.md +18 -0
- package/templates/zh-CN/docs/04-design/task-capability-architecture-and-evolution.md +46 -0
- package/templates/zh-CN/docs/05-project/adr/ADR-000-template.md +34 -0
- package/templates/zh-CN/docs/05-project/adr/README.md +35 -0
- package/templates/zh-CN/docs/05-project/doc-code-map.md +19 -0
- package/templates/zh-CN/docs/05-project/evolution-backlog.md +14 -0
- package/templates/zh-CN/docs/05-project/feature-registry.md +16 -0
- package/templates/zh-CN/docs/05-project/master-delivery-tracker.md +14 -0
- package/templates/zh-CN/docs/05-project/risk-register.md +21 -0
- package/templates/zh-CN/docs/05-project/roadmap.md +31 -0
- package/templates/zh-CN/docs/05-project/stage-view.md +14 -0
- package/templates/zh-CN/docs/05-project/tech-stack.md +36 -0
- package/templates/zh-CN/docs/06-dev-guide/SPEC.md +24 -0
- package/templates/zh-CN/docs/06-dev-guide/coding-standards.md +29 -0
- package/templates/zh-CN/docs/06-dev-guide/deployment-architecture.md +22 -0
- package/templates/zh-CN/docs/06-dev-guide/project-scaffold.md +16 -0
- package/templates/zh-CN/docs/06-dev-guide/testing-strategy.md +46 -0
- package/templates/zh-CN/docs/07-frontend/README.md +29 -0
- package/templates/zh-CN/docs/07-frontend/user-personas.md +27 -0
- package/templates/zh-CN/docs/08-process/README.md +29 -0
- package/templates/zh-CN/docs/08-process/ai-collaboration-protocol.md +30 -0
- package/templates/zh-CN/docs/08-process/autopilot.md +18 -0
- package/templates/zh-CN/docs/08-process/code-grounding.md +40 -0
- package/templates/zh-CN/docs/08-process/context-loading-strategy.md +35 -0
- package/templates/zh-CN/docs/08-process/conventions.md +77 -0
- package/templates/zh-CN/docs/08-process/debugging.md +27 -0
- package/templates/zh-CN/docs/08-process/design-gate.md +22 -0
- package/templates/zh-CN/docs/08-process/git-protocol.md +20 -0
- package/templates/zh-CN/docs/08-process/multi-agent-orchestration.md +27 -0
- package/templates/zh-CN/docs/08-process/planning.md +18 -0
- package/templates/zh-CN/docs/08-process/project-intake.md +53 -0
- package/templates/zh-CN/docs/08-process/reflection.md +18 -0
- package/templates/zh-CN/docs/08-process/review.md +30 -0
- package/templates/zh-CN/docs/08-process/session-handoff.md +29 -0
- package/templates/zh-CN/docs/08-process/tdd.md +24 -0
- package/templates/zh-CN/docs/08-process/tool-execution.md +34 -0
- package/templates/zh-CN/docs/08-process/workflow-contract.md +48 -0
- package/templates/zh-CN/docs/08-process/workflow.md +23 -0
- package/templates/zh-CN/docs/README.md +62 -0
- package/templates/zh-CN/docs/design-checklist.md +18 -0
- package/templates/zh-CN/docs/discussions/README.md +36 -0
- package/templates/zh-CN/docs/plans/README.md +15 -0
- package/templates/zh-CN/docs/proposed-design/README.md +41 -0
- package/templates/zh-CN/docs/temp-reference/README.md +13 -0
- package/templates/zh-CN/docs.config.json +46 -0
- package/templates/zh-CN/profiles/README.md +23 -0
- package/templates/zh-CN/profiles/agent-platform/README.md +23 -0
- package/templates/zh-CN/profiles/cli-tool/README.md +23 -0
- package/templates/zh-CN/profiles/library-sdk/README.md +23 -0
- package/templates/zh-CN/profiles/multi-agent/README.md +23 -0
- package/templates/zh-CN/profiles/profiles.json +31 -0
- package/templates/zh-CN/profiles/software-automation/README.md +23 -0
- package/templates/zh-CN/profiles/web-saas/README.md +23 -0
- package/templates/zh-CN/scripts/README.md +97 -0
- package/templates/zh-CN/scripts/doc-find.mjs +156 -0
- package/templates/zh-CN/scripts/doc-map.mjs +50 -0
- package/templates/zh-CN/scripts/doc-tools.mjs +311 -0
- package/templates/zh-CN/scripts/init-docs.mjs +214 -0
- package/templates/zh-CN/scripts/validate-docs.mjs +141 -0
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentLock Harness v2.2 — Single-Source Path-Scoped Rules Compiler
|
|
3
|
+
*
|
|
4
|
+
* Source of truth: `.agentlock-harness/rules/*.md` (excluding INDEX.md)
|
|
5
|
+
* Compiles deterministically (zero timestamps, stable sort, atomic write, symlink-safe) to:
|
|
6
|
+
* - Claude Code: `.claude/rules/alh-<slug>.md` (with `paths:` YAML frontmatter when scoped; clean no-frontmatter when alwaysApply)
|
|
7
|
+
* - Cursor: `.cursor/rules/alh-<slug>.mdc` (with `description`, `globs`, `alwaysApply`)
|
|
8
|
+
* - GitHub Copilot: `.github/instructions/alh-<slug>.instructions.md` (with `applyTo:`)
|
|
9
|
+
* + `.github/copilot-instructions.md` (thin pointer)
|
|
10
|
+
* - Codex & Gemini: `.agentlock-harness/rules/INDEX.md` (compact bounded path-routing table)
|
|
11
|
+
*
|
|
12
|
+
* Ownership & Standalone Drift Safety:
|
|
13
|
+
* - Generated files carry `alh-` prefix and are tracked alongside source hashes in `.agentlock-harness/rules.manifest.json`.
|
|
14
|
+
* - `--clean` ONLY removes orphaned files previously recorded in `rules.manifest.json`, NEVER touching user-authored rules.
|
|
15
|
+
* - Standalone `.agentlock-harness/hooks/rules-drift-check.mjs` can verify drift in pre-commit & CI without installing the CLI.
|
|
16
|
+
*/
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
20
|
+
import { assertSafeDestination, HARNESS_DIR, HARNESS_CONFIG_FILE } from "./harness-writer.mjs";
|
|
21
|
+
import { VALID_HOSTS } from "./catalog.mjs";
|
|
22
|
+
|
|
23
|
+
export const RULES_SOURCE_DIR = `${HARNESS_DIR}/rules`;
|
|
24
|
+
export const RULES_MANIFEST_FILE = `${HARNESS_DIR}/rules.manifest.json`;
|
|
25
|
+
const GENERATED_MARKER = "<!-- GENERATED BY agentlock-harness rules compile. DO NOT EDIT DIRECTLY; edit .agentlock-harness/rules/ instead. -->";
|
|
26
|
+
|
|
27
|
+
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
28
|
+
const normalizeLF = (text) => text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
29
|
+
|
|
30
|
+
function atomicWrite(absPath, content) {
|
|
31
|
+
fs.mkdirSync(path.dirname(absPath), { recursive: true });
|
|
32
|
+
const tmpPath = `${absPath}.alh-${randomUUID()}`;
|
|
33
|
+
try {
|
|
34
|
+
fs.writeFileSync(tmpPath, content, { encoding: "utf-8", flag: "wx" });
|
|
35
|
+
fs.renameSync(tmpPath, absPath);
|
|
36
|
+
} finally {
|
|
37
|
+
if (fs.existsSync(tmpPath)) {
|
|
38
|
+
try {
|
|
39
|
+
fs.unlinkSync(tmpPath);
|
|
40
|
+
} catch {
|
|
41
|
+
// ignore cleanup
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function unquote(val) {
|
|
48
|
+
const s = val.trim();
|
|
49
|
+
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
|
50
|
+
return s.slice(1, -1);
|
|
51
|
+
}
|
|
52
|
+
return s;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Bounded zero-dependency YAML frontmatter parser for scoped rules.
|
|
57
|
+
* Supports scalar strings, booleans, inline JSON/YAML string arrays, and indented `- item` lists.
|
|
58
|
+
*/
|
|
59
|
+
export function parseRuleFile(rawText, relPath = "rule.md") {
|
|
60
|
+
const text = normalizeLF(rawText).replace(/^\uFEFF/, "");
|
|
61
|
+
const match = text.match(/^---\n([\s\S]*?)\n---(?:\n|$)/);
|
|
62
|
+
if (!match) {
|
|
63
|
+
throw new Error(`${relPath}: Missing YAML frontmatter (--- ... ---)`);
|
|
64
|
+
}
|
|
65
|
+
const fmBlock = match[1];
|
|
66
|
+
const body = text.slice(match[0].length).trim();
|
|
67
|
+
const meta = {};
|
|
68
|
+
const lines = fmBlock.split("\n");
|
|
69
|
+
|
|
70
|
+
for (let i = 0; i < lines.length; i++) {
|
|
71
|
+
const rawLine = lines[i];
|
|
72
|
+
if (!rawLine.trim() || rawLine.trim().startsWith("#")) continue;
|
|
73
|
+
const kv = rawLine.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
|
|
74
|
+
if (!kv) {
|
|
75
|
+
throw new Error(`${relPath}: Unsupported frontmatter syntax at line ${i + 2}: ${rawLine}`);
|
|
76
|
+
}
|
|
77
|
+
const key = kv[1];
|
|
78
|
+
const rest = kv[2].trim();
|
|
79
|
+
if (!rest) {
|
|
80
|
+
const items = [];
|
|
81
|
+
while (i + 1 < lines.length && /^\s+-\s+/.test(lines[i + 1])) {
|
|
82
|
+
i++;
|
|
83
|
+
const item = lines[i].replace(/^\s+-\s+/, "").trim();
|
|
84
|
+
if (item) items.push(unquote(item));
|
|
85
|
+
}
|
|
86
|
+
meta[key] = items;
|
|
87
|
+
} else if (rest.startsWith("[") && rest.endsWith("]")) {
|
|
88
|
+
try {
|
|
89
|
+
const parsedArr = JSON.parse(rest);
|
|
90
|
+
if (Array.isArray(parsedArr)) {
|
|
91
|
+
meta[key] = parsedArr.map((v) => String(v).trim()).filter(Boolean);
|
|
92
|
+
} else {
|
|
93
|
+
meta[key] = [];
|
|
94
|
+
}
|
|
95
|
+
} catch {
|
|
96
|
+
const inner = rest.slice(1, -1).trim();
|
|
97
|
+
meta[key] = inner ? inner.split(",").map((part) => unquote(part)).filter(Boolean) : [];
|
|
98
|
+
}
|
|
99
|
+
} else if (rest === "true" || rest === "false") {
|
|
100
|
+
meta[key] = rest === "true";
|
|
101
|
+
} else {
|
|
102
|
+
meta[key] = unquote(rest);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const slug = path.basename(relPath, ".md").replace(/[^A-Za-z0-9_-]/g, "-").toLowerCase();
|
|
107
|
+
const description = typeof meta.description === "string" && meta.description.trim()
|
|
108
|
+
? meta.description.trim()
|
|
109
|
+
: slug;
|
|
110
|
+
const globs = Array.isArray(meta.globs)
|
|
111
|
+
? meta.globs.map((g) => String(g).trim()).filter(Boolean)
|
|
112
|
+
: typeof meta.globs === "string" && meta.globs.trim()
|
|
113
|
+
? meta.globs.split(",").map((g) => g.trim()).filter(Boolean)
|
|
114
|
+
: [];
|
|
115
|
+
const alwaysApply = typeof meta.alwaysApply === "boolean" ? meta.alwaysApply : globs.length === 0;
|
|
116
|
+
const hosts = Array.isArray(meta.hosts) && meta.hosts.length > 0
|
|
117
|
+
? meta.hosts.map((h) => String(h).trim().toLowerCase()).filter((h) => VALID_HOSTS.includes(h))
|
|
118
|
+
: null;
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
slug,
|
|
122
|
+
sourcePath: relPath,
|
|
123
|
+
sourceHash: sha256(normalizeLF(rawText)),
|
|
124
|
+
description,
|
|
125
|
+
globs,
|
|
126
|
+
alwaysApply,
|
|
127
|
+
hosts,
|
|
128
|
+
body,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function loadSourceRules(targetRoot) {
|
|
133
|
+
const rulesDir = path.join(targetRoot, RULES_SOURCE_DIR);
|
|
134
|
+
if (!fs.existsSync(rulesDir)) return [];
|
|
135
|
+
const entries = fs
|
|
136
|
+
.readdirSync(rulesDir, { withFileTypes: true })
|
|
137
|
+
.filter((e) => e.isFile() && e.name.endsWith(".md") && e.name !== "INDEX.md")
|
|
138
|
+
.sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
139
|
+
|
|
140
|
+
return entries.map((entry) => {
|
|
141
|
+
const rel = `${RULES_SOURCE_DIR}/${entry.name}`;
|
|
142
|
+
const abs = assertSafeDestination(targetRoot, rel);
|
|
143
|
+
return parseRuleFile(fs.readFileSync(abs, "utf-8"), rel);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function yamlQuote(str) {
|
|
148
|
+
return JSON.stringify(String(str));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function renderClaudeRule(rule) {
|
|
152
|
+
if (!rule.alwaysApply && rule.globs.length > 0) {
|
|
153
|
+
const header = ["---", "paths:"];
|
|
154
|
+
for (const g of rule.globs) header.push(` - ${yamlQuote(g)}`);
|
|
155
|
+
header.push("---", "", GENERATED_MARKER, `<!-- source: ${rule.sourcePath} -->`, "");
|
|
156
|
+
return `${header.join("\n")}${rule.body}\n`;
|
|
157
|
+
}
|
|
158
|
+
// Global rule in .claude/rules/*.md needs no empty YAML frontmatter block
|
|
159
|
+
return `${GENERATED_MARKER}\n<!-- source: ${rule.sourcePath} -->\n\n${rule.body}\n`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function renderCursorRule(rule) {
|
|
163
|
+
const header = [
|
|
164
|
+
"---",
|
|
165
|
+
`description: ${yamlQuote(rule.description)}`,
|
|
166
|
+
`globs: ${yamlQuote(rule.alwaysApply ? "" : rule.globs.join(", "))}`,
|
|
167
|
+
`alwaysApply: ${rule.alwaysApply ? "true" : "false"}`,
|
|
168
|
+
"---",
|
|
169
|
+
"",
|
|
170
|
+
GENERATED_MARKER,
|
|
171
|
+
`<!-- source: ${rule.sourcePath} -->`,
|
|
172
|
+
"",
|
|
173
|
+
];
|
|
174
|
+
return `${header.join("\n")}${rule.body}\n`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function renderCopilotInstruction(rule) {
|
|
178
|
+
const applyTo = rule.alwaysApply || rule.globs.length === 0 ? "**" : rule.globs.join(",");
|
|
179
|
+
const header = [
|
|
180
|
+
"---",
|
|
181
|
+
`applyTo: ${yamlQuote(applyTo)}`,
|
|
182
|
+
"---",
|
|
183
|
+
"",
|
|
184
|
+
GENERATED_MARKER,
|
|
185
|
+
`<!-- source: ${rule.sourcePath} -->`,
|
|
186
|
+
"",
|
|
187
|
+
];
|
|
188
|
+
return `${header.join("\n")}${rule.body}\n`;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function renderRulesIndex(rules, hosts) {
|
|
192
|
+
const lines = [
|
|
193
|
+
"# Path-Scoped Rules Routing Index (Codex / Gemini / Antigravity)",
|
|
194
|
+
"",
|
|
195
|
+
GENERATED_MARKER,
|
|
196
|
+
"",
|
|
197
|
+
`Active target hosts: \`${hosts.join(", ")}\``,
|
|
198
|
+
"",
|
|
199
|
+
"| Rule | Scope (`globs`) | Mode | Description | Source |",
|
|
200
|
+
"| :--- | :--- | :--- | :--- | :--- |",
|
|
201
|
+
];
|
|
202
|
+
for (const r of rules) {
|
|
203
|
+
const scope = r.alwaysApply || r.globs.length === 0 ? "`*` (always)" : r.globs.map((g) => `\`${g}\``).join(", ");
|
|
204
|
+
const mode = r.alwaysApply ? "always" : "path-scoped";
|
|
205
|
+
lines.push(`| \`${r.slug}\` | ${scope} | ${mode} | ${r.description.replace(/\|/g, "\\|")} | \`${r.sourcePath}\` |`);
|
|
206
|
+
}
|
|
207
|
+
lines.push("");
|
|
208
|
+
return lines.join("\n");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function resolveEnabledHosts(targetRoot, explicitHosts) {
|
|
212
|
+
if (Array.isArray(explicitHosts) && explicitHosts.length > 0) return explicitHosts;
|
|
213
|
+
const cfgPath = path.join(targetRoot, HARNESS_CONFIG_FILE);
|
|
214
|
+
if (fs.existsSync(cfgPath)) {
|
|
215
|
+
try {
|
|
216
|
+
const cfg = JSON.parse(fs.readFileSync(cfgPath, "utf-8"));
|
|
217
|
+
if (Array.isArray(cfg.hosts) && cfg.hosts.length > 0) return cfg.hosts;
|
|
218
|
+
} catch {
|
|
219
|
+
// fallback
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return [...VALID_HOSTS];
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function planRulesCompilation(targetRoot, { hosts = null } = {}) {
|
|
226
|
+
const absRoot = path.resolve(targetRoot);
|
|
227
|
+
const enabledHosts = resolveEnabledHosts(absRoot, hosts);
|
|
228
|
+
const hostSet = new Set(enabledHosts);
|
|
229
|
+
const rules = loadSourceRules(absRoot);
|
|
230
|
+
const outputs = new Map();
|
|
231
|
+
|
|
232
|
+
if (rules.length === 0) {
|
|
233
|
+
return { hosts: enabledHosts, rules, outputs };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
for (const rule of rules) {
|
|
237
|
+
const ruleHostSet = rule.hosts ? new Set(rule.hosts) : hostSet;
|
|
238
|
+
if (hostSet.has("claude") && ruleHostSet.has("claude")) {
|
|
239
|
+
outputs.set(`.claude/rules/alh-${rule.slug}.md`, renderClaudeRule(rule));
|
|
240
|
+
}
|
|
241
|
+
if (hostSet.has("cursor") && ruleHostSet.has("cursor")) {
|
|
242
|
+
outputs.set(`.cursor/rules/alh-${rule.slug}.mdc`, renderCursorRule(rule));
|
|
243
|
+
}
|
|
244
|
+
if (hostSet.has("copilot") && ruleHostSet.has("copilot")) {
|
|
245
|
+
outputs.set(`.github/instructions/alh-${rule.slug}.instructions.md`, renderCopilotInstruction(rule));
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (hostSet.has("codex") || hostSet.has("gemini")) {
|
|
250
|
+
outputs.set(`${RULES_SOURCE_DIR}/INDEX.md`, renderRulesIndex(rules, enabledHosts));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return { hosts: enabledHosts, rules, outputs };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function compileRules(targetRoot, { hosts = null, write = true, clean = true } = {}) {
|
|
257
|
+
const absRoot = path.resolve(targetRoot);
|
|
258
|
+
const { hosts: enabledHosts, rules, outputs } = planRulesCompilation(absRoot, { hosts });
|
|
259
|
+
|
|
260
|
+
const manifestAbs = path.join(absRoot, RULES_MANIFEST_FILE);
|
|
261
|
+
const prevManifest = fs.existsSync(manifestAbs) ? JSON.parse(fs.readFileSync(manifestAbs, "utf-8")) : { files: {} };
|
|
262
|
+
|
|
263
|
+
const written = [];
|
|
264
|
+
const unchanged = [];
|
|
265
|
+
const removed = [];
|
|
266
|
+
const nextManifestFiles = {};
|
|
267
|
+
const nextSourceHashes = {};
|
|
268
|
+
|
|
269
|
+
for (const r of rules) {
|
|
270
|
+
nextSourceHashes[r.sourcePath] = r.sourceHash;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
for (const [relPath, content] of outputs.entries()) {
|
|
274
|
+
const absPath = assertSafeDestination(absRoot, relPath);
|
|
275
|
+
const hash = sha256(content);
|
|
276
|
+
nextManifestFiles[relPath] = hash;
|
|
277
|
+
if (fs.existsSync(absPath) && sha256(fs.readFileSync(absPath, "utf-8")) === hash) {
|
|
278
|
+
unchanged.push(relPath);
|
|
279
|
+
} else {
|
|
280
|
+
if (write) atomicWrite(absPath, content);
|
|
281
|
+
written.push(relPath);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (clean && prevManifest?.files) {
|
|
286
|
+
for (const oldRel of Object.keys(prevManifest.files)) {
|
|
287
|
+
if (!outputs.has(oldRel)) {
|
|
288
|
+
const oldAbs = assertSafeDestination(absRoot, oldRel);
|
|
289
|
+
if (fs.existsSync(oldAbs)) {
|
|
290
|
+
if (write) fs.unlinkSync(oldAbs);
|
|
291
|
+
removed.push(oldRel);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (write && (rules.length > 0 || removed.length > 0)) {
|
|
298
|
+
const manifestObj = {
|
|
299
|
+
version: 2,
|
|
300
|
+
hosts: enabledHosts,
|
|
301
|
+
sources: Object.fromEntries(Object.entries(nextSourceHashes).sort(([a], [b]) => (a < b ? -1 : 1))),
|
|
302
|
+
files: Object.fromEntries(Object.entries(nextManifestFiles).sort(([a], [b]) => (a < b ? -1 : 1))),
|
|
303
|
+
};
|
|
304
|
+
const manifestStr = JSON.stringify(manifestObj, null, 2) + "\n";
|
|
305
|
+
const safeManifest = assertSafeDestination(absRoot, RULES_MANIFEST_FILE);
|
|
306
|
+
if (!fs.existsSync(safeManifest) || fs.readFileSync(safeManifest, "utf-8") !== manifestStr) {
|
|
307
|
+
atomicWrite(safeManifest, manifestStr);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
ok: true,
|
|
313
|
+
hosts: enabledHosts,
|
|
314
|
+
ruleCount: rules.length,
|
|
315
|
+
written,
|
|
316
|
+
unchanged,
|
|
317
|
+
removed,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export function checkRulesDrift(targetRoot, { hosts = null } = {}) {
|
|
322
|
+
const absRoot = path.resolve(targetRoot);
|
|
323
|
+
const { hosts: enabledHosts, rules, outputs } = planRulesCompilation(absRoot, { hosts });
|
|
324
|
+
const manifestAbs = path.join(absRoot, RULES_MANIFEST_FILE);
|
|
325
|
+
const prevManifest = fs.existsSync(manifestAbs) ? JSON.parse(fs.readFileSync(manifestAbs, "utf-8")) : { files: {} };
|
|
326
|
+
|
|
327
|
+
const missing = [];
|
|
328
|
+
const drifted = [];
|
|
329
|
+
const stale = [];
|
|
330
|
+
|
|
331
|
+
for (const [relPath, expectedContent] of outputs.entries()) {
|
|
332
|
+
const absPath = assertSafeDestination(absRoot, relPath);
|
|
333
|
+
if (!fs.existsSync(absPath)) {
|
|
334
|
+
missing.push(relPath);
|
|
335
|
+
} else if (sha256(fs.readFileSync(absPath, "utf-8")) !== sha256(expectedContent)) {
|
|
336
|
+
drifted.push(relPath);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
for (const oldRel of Object.keys(prevManifest.files || {})) {
|
|
341
|
+
if (!outputs.has(oldRel)) {
|
|
342
|
+
const oldAbs = assertSafeDestination(absRoot, oldRel);
|
|
343
|
+
if (fs.existsSync(oldAbs)) stale.push(oldRel);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
return {
|
|
348
|
+
ok: missing.length === 0 && drifted.length === 0 && stale.length === 0,
|
|
349
|
+
hosts: enabledHosts,
|
|
350
|
+
ruleCount: rules.length,
|
|
351
|
+
expectedCount: outputs.size,
|
|
352
|
+
missing,
|
|
353
|
+
drifted,
|
|
354
|
+
stale,
|
|
355
|
+
};
|
|
356
|
+
}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentLock Harness v2.3 — Zero-Dependency DAG Task Ledger with Atomic File Locking
|
|
3
|
+
*
|
|
4
|
+
* Inspired by Beads' ready/claim model, implemented with zero external databases:
|
|
5
|
+
* - Git-friendly JSON ledger: `.agentlock-harness/tasks.json`
|
|
6
|
+
* - True OS-level exclusive lock file (`flag: 'wx'` -> O_CREAT | O_EXCL): `.agentlock-harness/.tasks.lock`
|
|
7
|
+
* - Stale lock recovery (TTL 30s), strict DAG cycle detection (DFS), and lease-based task claiming
|
|
8
|
+
* so concurrent Git Worktrees or multi-agent sessions cannot double-claim the same task.
|
|
9
|
+
*/
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { assertSafeDestination, HARNESS_DIR } from "./harness-writer.mjs";
|
|
14
|
+
import { recordEvent } from "./audit.mjs";
|
|
15
|
+
|
|
16
|
+
export const TASKS_REL = `${HARNESS_DIR}/tasks.json`;
|
|
17
|
+
export const TASKS_LOCK_REL = `${HARNESS_DIR}/.tasks.lock`;
|
|
18
|
+
|
|
19
|
+
const PRIORITY_ORDER = { P0: 0, P1: 1, P2: 2 };
|
|
20
|
+
const VALID_PRIORITIES = new Set(["P0", "P1", "P2"]);
|
|
21
|
+
const STALE_LOCK_MS = 30_000;
|
|
22
|
+
|
|
23
|
+
function sleepSync(ms) {
|
|
24
|
+
const arr = new Int32Array(new SharedArrayBuffer(4));
|
|
25
|
+
Atomics.wait(arr, 0, 0, ms);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function withTaskLock(targetRoot, fn, { retries = 25, retryDelayMs = 20 } = {}) {
|
|
29
|
+
const absRoot = path.resolve(targetRoot);
|
|
30
|
+
const lockPath = assertSafeDestination(absRoot, TASKS_LOCK_REL);
|
|
31
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
32
|
+
|
|
33
|
+
let fd = null;
|
|
34
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
35
|
+
try {
|
|
36
|
+
fd = fs.openSync(lockPath, "wx");
|
|
37
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, ts: new Date().toISOString() }) + "\n");
|
|
38
|
+
break;
|
|
39
|
+
} catch (err) {
|
|
40
|
+
if (err.code !== "EEXIST") throw err;
|
|
41
|
+
// Check stale lock TTL
|
|
42
|
+
try {
|
|
43
|
+
const stat = fs.statSync(lockPath);
|
|
44
|
+
if (Date.now() - stat.mtimeMs > STALE_LOCK_MS) {
|
|
45
|
+
fs.unlinkSync(lockPath);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
} catch {
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (attempt === retries) {
|
|
52
|
+
throw new Error(`Task ledger lock busy (${TASKS_LOCK_REL}). Another agent may be updating tasks; retry shortly.`);
|
|
53
|
+
}
|
|
54
|
+
sleepSync(retryDelayMs);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
return fn();
|
|
60
|
+
} finally {
|
|
61
|
+
if (fd !== null) {
|
|
62
|
+
try {
|
|
63
|
+
fs.closeSync(fd);
|
|
64
|
+
} catch {
|
|
65
|
+
// ignore
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
if (fs.existsSync(lockPath)) fs.unlinkSync(lockPath);
|
|
70
|
+
} catch {
|
|
71
|
+
// ignore
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function readLedger(targetRoot) {
|
|
77
|
+
const absRoot = path.resolve(targetRoot);
|
|
78
|
+
const ledgerPath = assertSafeDestination(absRoot, TASKS_REL);
|
|
79
|
+
if (!fs.existsSync(ledgerPath)) {
|
|
80
|
+
return { schemaVersion: 1, nextSeq: 1, tasks: [] };
|
|
81
|
+
}
|
|
82
|
+
const parsed = JSON.parse(fs.readFileSync(ledgerPath, "utf-8"));
|
|
83
|
+
return {
|
|
84
|
+
schemaVersion: parsed.schemaVersion || 1,
|
|
85
|
+
nextSeq: Number.isInteger(parsed.nextSeq) ? parsed.nextSeq : (parsed.tasks?.length || 0) + 1,
|
|
86
|
+
tasks: Array.isArray(parsed.tasks) ? parsed.tasks : [],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function writeLedgerAtomic(targetRoot, ledger) {
|
|
91
|
+
const absRoot = path.resolve(targetRoot);
|
|
92
|
+
const ledgerPath = assertSafeDestination(absRoot, TASKS_REL);
|
|
93
|
+
fs.mkdirSync(path.dirname(ledgerPath), { recursive: true });
|
|
94
|
+
const tmpPath = `${ledgerPath}.alh-${randomUUID()}`;
|
|
95
|
+
const text = JSON.stringify(ledger, null, 2) + "\n";
|
|
96
|
+
try {
|
|
97
|
+
fs.writeFileSync(tmpPath, text, { encoding: "utf-8", flag: "wx" });
|
|
98
|
+
fs.renameSync(tmpPath, ledgerPath);
|
|
99
|
+
} finally {
|
|
100
|
+
if (fs.existsSync(tmpPath)) {
|
|
101
|
+
try {
|
|
102
|
+
fs.unlinkSync(tmpPath);
|
|
103
|
+
} catch {
|
|
104
|
+
// ignore
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function hasDependencyCycle(tasks, candidateId, candidateDeps) {
|
|
111
|
+
const adj = new Map();
|
|
112
|
+
for (const t of tasks) adj.set(t.id, [...(t.dependsOn || [])]);
|
|
113
|
+
adj.set(candidateId, [...candidateDeps]);
|
|
114
|
+
|
|
115
|
+
const visiting = new Set();
|
|
116
|
+
const visited = new Set();
|
|
117
|
+
|
|
118
|
+
function dfs(node) {
|
|
119
|
+
if (visiting.has(node)) return true;
|
|
120
|
+
if (visited.has(node)) return false;
|
|
121
|
+
visiting.add(node);
|
|
122
|
+
for (const next of adj.get(node) || []) {
|
|
123
|
+
if (dfs(next)) return true;
|
|
124
|
+
}
|
|
125
|
+
visiting.delete(node);
|
|
126
|
+
visited.add(node);
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
for (const id of adj.keys()) {
|
|
131
|
+
if (dfs(id)) return true;
|
|
132
|
+
}
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function isLeaseExpired(task, nowMs = Date.now()) {
|
|
137
|
+
if (task.status !== "claimed") return false;
|
|
138
|
+
if (!task.leaseUntil) return false;
|
|
139
|
+
const exp = Date.parse(task.leaseUntil);
|
|
140
|
+
return Number.isFinite(exp) && exp <= nowMs;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function computeReadyTasks(tasks, nowMs = Date.now()) {
|
|
144
|
+
const doneSet = new Set(tasks.filter((t) => t.status === "done").map((t) => t.id));
|
|
145
|
+
return tasks
|
|
146
|
+
.filter((t) => {
|
|
147
|
+
const claimable = t.status === "open" || isLeaseExpired(t, nowMs);
|
|
148
|
+
if (!claimable) return false;
|
|
149
|
+
return (t.dependsOn || []).every((dep) => doneSet.has(dep));
|
|
150
|
+
})
|
|
151
|
+
.sort((a, b) => {
|
|
152
|
+
const pa = PRIORITY_ORDER[a.priority] ?? 1;
|
|
153
|
+
const pb = PRIORITY_ORDER[b.priority] ?? 1;
|
|
154
|
+
if (pa !== pb) return pa - pb;
|
|
155
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function addTask(targetRoot, { title, priority = "P1", dependsOn = [], change = null, id = null } = {}) {
|
|
160
|
+
const cleanTitle = String(title || "").trim();
|
|
161
|
+
if (!cleanTitle) throw new Error("Task title is required.");
|
|
162
|
+
const normPriority = VALID_PRIORITIES.has(String(priority).toUpperCase()) ? String(priority).toUpperCase() : "P1";
|
|
163
|
+
const deps = [...new Set((Array.isArray(dependsOn) ? dependsOn : String(dependsOn || "").split(",")).map((s) => s.trim()).filter(Boolean))];
|
|
164
|
+
|
|
165
|
+
return withTaskLock(targetRoot, () => {
|
|
166
|
+
const ledger = readLedger(targetRoot);
|
|
167
|
+
const existingIds = new Set(ledger.tasks.map((t) => t.id));
|
|
168
|
+
|
|
169
|
+
const taskId = id ? String(id).trim() : `T-${String(ledger.nextSeq).padStart(3, "0")}`;
|
|
170
|
+
if (existingIds.has(taskId)) throw new Error(`Task ID already exists: ${taskId}`);
|
|
171
|
+
for (const dep of deps) {
|
|
172
|
+
if (!existingIds.has(dep)) throw new Error(`Unknown dependency task ID: ${dep}`);
|
|
173
|
+
}
|
|
174
|
+
if (deps.includes(taskId) || hasDependencyCycle(ledger.tasks, taskId, deps)) {
|
|
175
|
+
throw new Error(`Dependency cycle detected when adding ${taskId} -> [${deps.join(", ")}]`);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const now = new Date().toISOString();
|
|
179
|
+
const task = {
|
|
180
|
+
id: taskId,
|
|
181
|
+
title: cleanTitle,
|
|
182
|
+
status: "open",
|
|
183
|
+
priority: normPriority,
|
|
184
|
+
dependsOn: deps,
|
|
185
|
+
...(change ? { change: String(change).trim() } : {}),
|
|
186
|
+
owner: null,
|
|
187
|
+
claimedAt: null,
|
|
188
|
+
leaseUntil: null,
|
|
189
|
+
evidence: null,
|
|
190
|
+
blockedReason: null,
|
|
191
|
+
createdAt: now,
|
|
192
|
+
updatedAt: now,
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
ledger.tasks.push(task);
|
|
196
|
+
if (!id) ledger.nextSeq += 1;
|
|
197
|
+
else ledger.nextSeq = Math.max(ledger.nextSeq, ledger.tasks.length + 1);
|
|
198
|
+
writeLedgerAtomic(targetRoot, ledger);
|
|
199
|
+
recordEvent(targetRoot, { source: "task", action: "add", rule: task.priority, detail: `${task.id}: ${task.title}` });
|
|
200
|
+
return task;
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function claimTask(targetRoot, id, { owner = "agent", leaseMinutes = 60, force = false } = {}) {
|
|
205
|
+
const cleanOwner = String(owner || "").trim() || "agent";
|
|
206
|
+
const mins = Number.isFinite(Number(leaseMinutes)) && Number(leaseMinutes) > 0 ? Number(leaseMinutes) : 60;
|
|
207
|
+
|
|
208
|
+
return withTaskLock(targetRoot, () => {
|
|
209
|
+
const ledger = readLedger(targetRoot);
|
|
210
|
+
const task = ledger.tasks.find((t) => t.id === id);
|
|
211
|
+
if (!task) throw new Error(`Task not found: ${id}`);
|
|
212
|
+
if (task.status === "done") throw new Error(`Task ${id} is already done.`);
|
|
213
|
+
|
|
214
|
+
const doneSet = new Set(ledger.tasks.filter((t) => t.status === "done").map((t) => t.id));
|
|
215
|
+
const unmetDeps = (task.dependsOn || []).filter((d) => !doneSet.has(d));
|
|
216
|
+
if (unmetDeps.length > 0 && !force) {
|
|
217
|
+
throw new Error(`Task ${id} is waiting on incomplete dependencies: ${unmetDeps.join(", ")}`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const nowMs = Date.now();
|
|
221
|
+
if (task.status === "blocked" && !force) {
|
|
222
|
+
throw new Error(`Task ${id} is blocked (${task.blockedReason || "no reason"}). Release or pass --force.`);
|
|
223
|
+
}
|
|
224
|
+
if (task.status === "claimed" && task.owner !== cleanOwner && !isLeaseExpired(task, nowMs) && !force) {
|
|
225
|
+
throw new Error(`Task ${id} is currently claimed by "${task.owner}" until ${task.leaseUntil}.`);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const nowIso = new Date(nowMs).toISOString();
|
|
229
|
+
task.status = "claimed";
|
|
230
|
+
task.owner = cleanOwner;
|
|
231
|
+
task.claimedAt = nowIso;
|
|
232
|
+
task.leaseUntil = new Date(nowMs + mins * 60 * 1000).toISOString();
|
|
233
|
+
task.blockedReason = null;
|
|
234
|
+
task.updatedAt = nowIso;
|
|
235
|
+
|
|
236
|
+
writeLedgerAtomic(targetRoot, ledger);
|
|
237
|
+
recordEvent(targetRoot, { source: "task", action: "claim", rule: cleanOwner, detail: `${task.id} claimed` });
|
|
238
|
+
return task;
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function releaseTask(targetRoot, id) {
|
|
243
|
+
return withTaskLock(targetRoot, () => {
|
|
244
|
+
const ledger = readLedger(targetRoot);
|
|
245
|
+
const task = ledger.tasks.find((t) => t.id === id);
|
|
246
|
+
if (!task) throw new Error(`Task not found: ${id}`);
|
|
247
|
+
if (task.status === "done") throw new Error(`Cannot release already-completed task ${id}.`);
|
|
248
|
+
|
|
249
|
+
task.status = "open";
|
|
250
|
+
task.owner = null;
|
|
251
|
+
task.claimedAt = null;
|
|
252
|
+
task.leaseUntil = null;
|
|
253
|
+
task.blockedReason = null;
|
|
254
|
+
task.updatedAt = new Date().toISOString();
|
|
255
|
+
|
|
256
|
+
writeLedgerAtomic(targetRoot, ledger);
|
|
257
|
+
recordEvent(targetRoot, { source: "task", action: "release", detail: `${task.id} returned to open` });
|
|
258
|
+
return task;
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export function blockTask(targetRoot, id, { reason = "" } = {}) {
|
|
263
|
+
const cleanReason = String(reason || "").trim();
|
|
264
|
+
if (!cleanReason) throw new Error("Blocking a task requires --reason.");
|
|
265
|
+
|
|
266
|
+
return withTaskLock(targetRoot, () => {
|
|
267
|
+
const ledger = readLedger(targetRoot);
|
|
268
|
+
const task = ledger.tasks.find((t) => t.id === id);
|
|
269
|
+
if (!task) throw new Error(`Task not found: ${id}`);
|
|
270
|
+
if (task.status === "done") throw new Error(`Cannot block completed task ${id}.`);
|
|
271
|
+
|
|
272
|
+
task.status = "blocked";
|
|
273
|
+
task.blockedReason = cleanReason;
|
|
274
|
+
task.leaseUntil = null;
|
|
275
|
+
task.updatedAt = new Date().toISOString();
|
|
276
|
+
|
|
277
|
+
writeLedgerAtomic(targetRoot, ledger);
|
|
278
|
+
recordEvent(targetRoot, { source: "task", action: "block", rule: "task-blocked", detail: `${task.id}: ${cleanReason}` });
|
|
279
|
+
return task;
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export function completeTask(targetRoot, id, { evidence = "" } = {}) {
|
|
284
|
+
const cleanEvidence = String(evidence || "").trim();
|
|
285
|
+
|
|
286
|
+
return withTaskLock(targetRoot, () => {
|
|
287
|
+
const ledger = readLedger(targetRoot);
|
|
288
|
+
const task = ledger.tasks.find((t) => t.id === id);
|
|
289
|
+
if (!task) throw new Error(`Task not found: ${id}`);
|
|
290
|
+
|
|
291
|
+
const doneSet = new Set(ledger.tasks.filter((t) => t.status === "done").map((t) => t.id));
|
|
292
|
+
const unmetDeps = (task.dependsOn || []).filter((d) => !doneSet.has(d));
|
|
293
|
+
if (unmetDeps.length > 0) {
|
|
294
|
+
throw new Error(`Cannot mark ${id} done while upstream dependencies remain incomplete: ${unmetDeps.join(", ")}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
task.status = "done";
|
|
298
|
+
task.leaseUntil = null;
|
|
299
|
+
task.blockedReason = null;
|
|
300
|
+
task.evidence = cleanEvidence || "unverified-manual-close";
|
|
301
|
+
task.updatedAt = new Date().toISOString();
|
|
302
|
+
|
|
303
|
+
writeLedgerAtomic(targetRoot, ledger);
|
|
304
|
+
recordEvent(targetRoot, { source: "task", action: "done", rule: cleanEvidence ? "with-evidence" : "manual", detail: `${task.id} done` });
|
|
305
|
+
return task;
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export function renderTaskGraph(tasks, nowMs = Date.now()) {
|
|
310
|
+
if (!tasks.length) return "(No tasks in ledger)";
|
|
311
|
+
const readyIds = new Set(computeReadyTasks(tasks, nowMs).map((t) => t.id));
|
|
312
|
+
const lines = [];
|
|
313
|
+
for (const t of tasks) {
|
|
314
|
+
let icon = "[-]";
|
|
315
|
+
if (t.status === "done") icon = "[x]";
|
|
316
|
+
else if (t.status === "blocked") icon = "[!]";
|
|
317
|
+
else if (readyIds.has(t.id)) icon = "[ ]";
|
|
318
|
+
else if (t.status === "claimed") icon = "[~]";
|
|
319
|
+
|
|
320
|
+
const deps = t.dependsOn?.length ? ` <- (${t.dependsOn.join(", ")})` : "";
|
|
321
|
+
const owner = t.status === "claimed" && t.owner ? ` @${t.owner}` : "";
|
|
322
|
+
const ch = t.change ? ` {change:${t.change}}` : "";
|
|
323
|
+
const blk = t.status === "blocked" && t.blockedReason ? ` — BLOCKED: ${t.blockedReason}` : "";
|
|
324
|
+
lines.push(`${icon} ${t.id} [${t.priority}] ${t.title}${deps}${owner}${ch}${blk}`);
|
|
325
|
+
}
|
|
326
|
+
return lines.join("\n");
|
|
327
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
const PKG_PATH = path.resolve(__dirname, "../../package.json");
|
|
7
|
+
const PKG = JSON.parse(fs.readFileSync(PKG_PATH, "utf-8"));
|
|
8
|
+
|
|
9
|
+
export const PKG_NAME = PKG.name;
|
|
10
|
+
export const PKG_VERSION = PKG.version;
|