From a9e087ea135cb6c7774bd7670a1cbfc25c0f34ad Mon Sep 17 00:00:00 2001 From: "glm-5.1" Date: Mon, 27 Apr 2026 20:57:03 +0000 Subject: [PATCH] Add README, dual MIT/Apache-2.0 license, and project docs to AGENTS.md --- AGENTS.md | 51 +++++++++- LICENSE-APACHE | 190 ++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 21 ++++ README.md | 257 +++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 +- 5 files changed, 519 insertions(+), 2 deletions(-) create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md diff --git a/AGENTS.md b/AGENTS.md index 2529fdd..b5b529d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,4 +56,53 @@ You have access to the `worktree` tool for git worktree management and session c - `worktree({action: "notify", args: {message: "...", level: "info|blocking"}})` — Report to coordinator - `worktree({action: "status"})` — Show worktree git status -The plugin auto-injects `workdir` for bash commands when the session is mapped to a worktree. \ No newline at end of file +The plugin auto-injects `workdir` for bash commands when the session is mapped to a worktree. + +## Project: @alkdev/taskgraph + +Pure TypeScript library for DAG task graph analysis, risk scoring, cost-benefit math, and YAML frontmatter parsing. Built on graphology. Dual-licensed MIT / Apache-2.0. + +### Commands + +- `npm run build` — Build with tsup (ESM + CJS + declarations) +- `npm run lint` — Type-check with `tsc --noEmit` +- `npm test` — Run tests with vitest +- `npm run test:watch` — Watch mode +- `npm run test:coverage` — Coverage report (v8) + +### Architecture + +See `docs/architecture/` for the full SDD. Key points: + +- **Public API boundary**: `src/index.ts` is the sole entry point. Internal graphology details are not re-exported. Only add exports to `index.ts` — never import from internal paths. +- **Edge convention**: prerequisite → dependent (if B depends on A, edge is A → B). +- **Edge keys**: deterministic `${source}->${target}` per ADR-006. +- **Schemas**: TypeBox via `@alkdev/typebox`. All runtime schemas and types are defined in `src/schema/`. No Zod. +- **Validation**: throws on construction errors (duplicates, missing nodes). `validate*()` methods return error arrays instead of throwing. +- **No comments in source**: Do not add comments to code unless explicitly asked. + +### Source Layout + +``` +src/ + index.ts — Public API surface (all exports) + graph/ + construction.ts — TaskGraph class + queries.ts — Internal query helpers + mutation.ts — Internal mutation helpers + validation.ts — Internal validation helpers + analysis/ + critical-path.ts, bottleneck.ts, parallel-groups.ts + risk.ts, cost-benefit.ts, decompose.ts, defaults.ts + frontmatter/ + parse.ts, serialize.ts, file-io.ts (Node.js only) + schema/ + enums.ts, task.ts, graph.ts, results.ts + error/ + index.ts — Error classes + validation types +``` + +### Dependencies + +Runtime: `graphology`, `graphology-*`, `yaml`, `@alkdev/typebox`. No native addons. +Dev: `tsup`, `typescript`, `vitest`, `@vitest/coverage-v8`. \ No newline at end of file diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..9d896bd --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,190 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2026 Alkimiadev + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..37c8c20 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Alkimiadev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e4f972a --- /dev/null +++ b/README.md @@ -0,0 +1,257 @@ +# @alkdev/taskgraph + +Directed acyclic graph analysis, risk scoring, and YAML frontmatter parsing for task management. + +Built on [graphology](https://github.com/graphology/graphology) — pure TypeScript, no native addons, works in Node.js / Deno / Bun. + +## Install + +```sh +npm install @alkdev/taskgraph +``` + +## Quick Start + +```ts +import { TaskGraph, parallelGroups, criticalPath } from '@alkdev/taskgraph'; + +const graph = TaskGraph.fromTasks([ + { id: 'design', name: 'Design API', dependsOn: [], risk: 'low', scope: 'narrow' }, + { id: 'impl', name: 'Implement', dependsOn: ['design'], risk: 'medium', scope: 'moderate' }, + { id: 'test', name: 'Write tests', dependsOn: ['impl'], risk: 'low', scope: 'narrow' }, + { id: 'docs', name: 'Write docs', dependsOn: ['design'], risk: 'trivial', scope: 'narrow' }, +]); + +const groups = parallelGroups(graph); +// [['design'], ['impl', 'docs'], ['test']] + +const path = criticalPath(graph); +// ['design', 'impl', 'test'] +``` + +## TaskGraph + +The primary data structure. Wraps a graphology `DirectedGraph` with validation and typed access. + +### Construction + +```ts +// From task inputs (convenience — edges created from dependsOn) +const g1 = TaskGraph.fromTasks([...tasks]); + +// From explicit tasks + edges (per-edge qualityRetention) +const g2 = TaskGraph.fromRecords([...tasks], [...edges]); + +// From serialized data (round-trip with export()) +const data = g1.export(); +const g3 = TaskGraph.fromJSON(data); + +// Incremental building +const g4 = new TaskGraph(); +g4.addTask('a', { name: 'Task A' }); +g4.addTask('b', { name: 'Task B' }); +g4.addDependency('a', 'b'); // a → b (a is prerequisite) +``` + +### Queries + +```ts +graph.topologicalOrder(); // string[] — prerequisite → dependent order +graph.dependencies('impl'); // ['design'] — prerequisites of impl +graph.dependents('design'); // ['impl', 'docs'] — dependents of design +graph.hasCycles(); // boolean +graph.findCycles(); // string[][] — cycle paths +graph.taskCount(); // number +graph.getTask('design'); // TaskGraphNodeAttributes | undefined +``` + +### Validation + +```ts +graph.validate(); // AnyValidationError[] — combined schema + graph +graph.validateSchema(); // ValidationError[] — per-field TypeBox validation +graph.validateGraph(); // GraphValidationError[] — cycles, dangling refs +``` + +### Mutation + +```ts +graph.removeTask('id'); +graph.removeDependency('prereq', 'dependent'); +graph.updateTask('id', { risk: 'high' }); +graph.updateEdgeAttributes('prereq', 'dependent', { qualityRetention: 0.8 }); +``` + +### Export + +```ts +const data = graph.export(); // TaskGraphSerialized (graphology JSON) +const json = JSON.stringify(graph); // uses toJSON() alias +``` + +## Analysis Functions + +All analysis functions take a `TaskGraph` instance as their first argument. + +### Critical Path + +```ts +import { criticalPath, weightedCriticalPath } from '@alkdev/taskgraph'; + +criticalPath(graph); // longest path by edge count + +weightedCriticalPath(graph, (id, attrs) => { + // custom weight per node + return riskWeight(attrs.risk ?? 'medium') * impactWeight(attrs.impact ?? 'isolated'); +}); +``` + +### Parallel Groups + +```ts +import { parallelGroups } from '@alkdev/taskgraph'; + +parallelGroups(graph); // string[][] — tasks at each topological depth +``` + +### Bottleneck Analysis + +```ts +import { bottlenecks } from '@alkdev/taskgraph'; + +const scores = bottlenecks(graph); +// [{ taskId: 'design', score: 0.83 }, ...] — sorted descending +``` + +### Risk Analysis + +```ts +import { riskPath, riskDistribution } from '@alkdev/taskgraph'; + +riskPath(graph); +// { path: ['design', 'impl', 'test'], totalRisk: 4.2 } + +riskDistribution(graph); +// { trivial: [...], low: [...], medium: [...], high: [...], critical: [...], unspecified: [...] } +``` + +### Expected Value & Workflow Cost + +```ts +import { calculateTaskEv, workflowCost } from '@alkdev/taskgraph'; + +calculateTaskEv(0.8, 3.0, 1.5); +// { ev: 4.2, pSuccess: 0.8, expectedRetries: 0.25 } + +const result = workflowCost(graph, { + propagationMode: 'dag-propagate', // or 'independent' + defaultQualityRetention: 0.9, + includeCompleted: false, +}); +// result.tasks — per-task EV entries +// result.totalEv — aggregate +// result.averageEv +``` + +### Decomposition + +```ts +import { shouldDecomposeTask } from '@alkdev/taskgraph'; + +shouldDecomposeTask({ name: 'Refactor', risk: 'high', scope: 'broad' }); +// { shouldDecompose: true, reasons: ['risk: high — ...', 'scope: broad — ...'] } +``` + +### Categorical Numeric Methods + +```ts +import { + scopeCostEstimate, scopeTokenEstimate, + riskSuccessProbability, riskWeight, + impactWeight, resolveDefaults, +} from '@alkdev/taskgraph'; + +scopeCostEstimate('moderate'); // 3.0 +scopeTokenEstimate('broad'); // 6000 +riskSuccessProbability('high'); // 0.65 +riskWeight('high'); // 0.35 +impactWeight('project'); // 3.0 + +resolveDefaults({ name: 'Task', risk: 'high' }); +// { scope: 'narrow', risk: 'high', ..., costEstimate: 2.0, ... } +``` + +## Frontmatter + +Parse and serialize YAML frontmatter in markdown files. + +```ts +import { + parseFrontmatter, serializeFrontmatter, + parseTaskFile, parseTaskDirectory, +} from '@alkdev/taskgraph'; + +// Parse a markdown string with --- frontmatter +const task = parseFrontmatter(`--- +id: my-task +name: My Task +dependsOn: [] +risk: medium +--- +Task body here`); + +// Serialize back to markdown +const md = serializeFrontmatter(task, 'Task body here'); + +// File I/O (Node.js only) +const task2 = await parseTaskFile('/path/to/task.md'); +const tasks = await parseTaskDirectory('/path/to/tasks/'); +``` + +## Schemas & Types + +All schemas are TypeBox schemas and all types are inferred from them. + +```ts +import type { + TaskInput, DependencyEdge, + TaskGraphNodeAttributes, TaskGraphEdgeAttributes, TaskGraphSerialized, + RiskPathResult, DecomposeResult, WorkflowCostOptions, WorkflowCostResult, + EvConfig, EvResult, RiskDistributionResult, ResolvedTaskAttributes, +} from '@alkdev/taskgraph'; + +import type { + TaskScope, TaskRisk, TaskImpact, TaskLevel, TaskPriority, TaskStatus, +} from '@alkdev/taskgraph'; +``` + +### Enums + +```ts +// Type values (also usable as TypeScript types) +type Scope = 'single' | 'narrow' | 'moderate' | 'broad' | 'system'; +type Risk = 'trivial' | 'low' | 'medium' | 'high' | 'critical'; +type Impact = 'isolated' | 'component' | 'phase' | 'project'; +type Level = 'planning' | 'decomposition' | 'implementation' | 'review' | 'research'; +type Priority = 'low' | 'medium' | 'high' | 'critical'; +type Status = 'pending' | 'in-progress' | 'completed' | 'failed' | 'blocked'; +``` + +## Error Classes + +```ts +import { + TaskgraphError, // base class + TaskNotFoundError, // .taskId + CircularDependencyError, // .cycles: string[][] + InvalidInputError, // .field, .message + DuplicateNodeError, // .taskId + DuplicateEdgeError, // .prerequisite, .dependent +} from '@alkdev/taskgraph'; +``` + +## License + +Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT License](LICENSE-MIT) at your option. + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. \ No newline at end of file diff --git a/package.json b/package.json index fd7f941..135a39d 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,7 @@ "risk-analysis", "graphology" ], - "license": "MIT", + "license": "MIT OR Apache-2.0", "dependencies": { "@alkdev/typebox": "^0.34.49", "graphology": "^0.26.0",