@unclex/ken-task 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xiaoxing Hu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,6 @@
1
- # Temporary Holding Version
1
+ # @unclex/ken-task
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Plain-text tasks in one folder of a ken root, one file per task, the file's path as its
4
+ identity, a branch and worktree per task. Bundled in `@unclex/ken`, which runs it as `ken
5
+ task <command>`, with `KEN_ROOT` set to the root. Reads `task.folder` from the root's `.ken`, is
6
+ built on `ken which`, `ken path code` and `ken get -b`, and runs git for the rest. See `docs/ken-task.md` at the repo root.
package/dist/add.js ADDED
@@ -0,0 +1,105 @@
1
+ import { mkdirSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, join, relative } from 'node:path';
3
+ import { Document } from 'yaml';
4
+ import { inFolder, outside, real, resolveTask } from "./resolve.js";
5
+ // a part of a task's path is letters, digits and dashes, so its branch name is too
6
+ const PART = /^[\p{L}\p{N}][\p{L}\p{N}-]*$/u;
7
+ const EXT = /\.[\p{L}\p{N}]+$/u;
8
+ const KEY = /^[a-z0-9._-]+\/[a-z0-9._-]+\/[a-z0-9._-]+$/;
9
+ /** Whether `text` is a repo key, `<host>/<owner>/<repo>` in lowercase, as `ken path code` takes one. */
10
+ export const isKey = (text) => KEY.test(text) && text.split('/').every((p) => p !== '.' && p !== '..');
11
+ const stemOf = (name) => name.replace(/(.)\.[^.]*$/, '$1');
12
+ /**
13
+ * Where a new task named `arg` goes: a path into the task folder `folder`, a real path, read as
14
+ * `resolveTask` reads one, lowercased with spaces as dashes, a `.md`. Refused, naming what to
15
+ * run instead with `command` (`ken task add`, or `ken task rename <task>`): a path outside the
16
+ * folder, another extension, other punctuation, and a file, or another extension of its stem,
17
+ * that exists.
18
+ */
19
+ export function newPath(root, folder, cwd, arg, command) {
20
+ const [typed] = inFolder(root, folder, cwd, arg);
21
+ if (typed === undefined)
22
+ throw outside(root, folder, arg);
23
+ // the one normalisation: lowercase, spaces to dashes
24
+ const rel = typed.toLowerCase().replaceAll(' ', '-');
25
+ const ext = EXT.exec(rel)?.[0] ?? '';
26
+ if (ext && ext !== '.md') {
27
+ throw new Error(`${typed} is a ${ext}, but a task ken-task writes holds front matter, which ken-task reads only in a .md, so its fields would be lost: ` +
28
+ `run \`${command} ${join(folder, rel.slice(0, -ext.length))}\` for the .md. A file of another extension is a task with every default, written by hand.`);
29
+ }
30
+ const parts = rel.slice(0, rel.length - ext.length).split('/');
31
+ if (!parts.every((p) => PART.test(p))) {
32
+ const name = parts
33
+ .map((p) => p.replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, ''))
34
+ .join('/');
35
+ throw new Error(`${typed} has punctuation other than dashes, and a task's path is its branch name, so ken-task names tasks ` +
36
+ `with letters, digits and dashes only: run \`${command} ${join(folder, name + ext)}\`.`);
37
+ }
38
+ const path = join(folder, ext ? rel : `${rel}.md`);
39
+ // the normalised path may lead elsewhere than the typed one did, through a link
40
+ if (!inFolder(root, folder, folder, path).length)
41
+ throw outside(root, folder, path);
42
+ const dir = dirname(path);
43
+ const stem = stemOf(path.slice(dir.length + 1));
44
+ const taken = files(dir).find((e) => stemOf(e).toLowerCase() === stem);
45
+ if (taken) {
46
+ const existing = join(dir, taken);
47
+ throw new Error(existing === path
48
+ ? `${path} exists, and a task's path is its identity, so no other task can take it: read it with \`cat ${path}\`, ` +
49
+ `or run \`${command} <another path>\`.`
50
+ : `${existing} exists, and a task's branch is its path without the extension, so ${path} would share its branch: ` +
51
+ `run \`${command} <another path>\`.`);
52
+ }
53
+ if (typed === rel)
54
+ return { path };
55
+ const renamed = `${typed} is named ${relative(folder, path)}: a task's path is its branch name, so it is lowercase, with dashes for spaces.`;
56
+ return { path, renamed };
57
+ }
58
+ /**
59
+ * Add the task `arg` names, a path into the task folder `configured` as `newPath` takes it, in
60
+ * the canonical shape of docs/ken-task.md: `status: todo`, `created: <today>`, `repo` and
61
+ * `blocked-by` when given, then the heading. Everything is checked before anything is written;
62
+ * the file is made with the exclusive-create flag, so of two adds of one path exactly one wins.
63
+ */
64
+ export function addTask(root, configured, cwd, arg, opts) {
65
+ const { repo, blockedBy, today } = opts;
66
+ if (repo !== undefined && !isKey(repo)) {
67
+ throw new Error(`-r ${JSON.stringify(repo)} is not a repo key, so \`ken task claim\` could not find its clone: ` +
68
+ 'a key is <host>/<owner>/<repo> in lowercase, e.g. `-r github.com/acme/portal`, as `ken which` prints it inside the clone.');
69
+ }
70
+ const folder = real(configured);
71
+ const added = newPath(root, folder, cwd, arg, 'ken task add');
72
+ const { path } = added;
73
+ const dir = dirname(path);
74
+ const refs = blockedBy.map((b) => relative(dir, resolveTask(root, folder, cwd, b)));
75
+ const lines = ['---', 'status: todo', `created: ${today}`];
76
+ if (repo)
77
+ lines.push(`repo: ${repo}`);
78
+ if (refs.length) {
79
+ const list = new Document(refs);
80
+ list.contents.flow = true;
81
+ lines.push(`blocked-by: ${list.toString({ lineWidth: 0, flowCollectionPadding: false }).trim()}`);
82
+ }
83
+ lines.push('---', '', `# ${stemOf(basename(path)).replaceAll('-', ' ')}`, '');
84
+ mkdirSync(dir, { recursive: true });
85
+ try {
86
+ writeFileSync(path, lines.join('\n'), { flag: 'wx' });
87
+ }
88
+ catch (e) {
89
+ if (e.code !== 'EEXIST')
90
+ throw e;
91
+ throw new Error(`${path} exists, made since this add looked, most likely by another \`ken task add\`: read it with \`cat ${path}\`, or give this task another name.`);
92
+ }
93
+ return added;
94
+ }
95
+ /** The entries of `dir` other than folders; none if it does not exist. */
96
+ function files(dir) {
97
+ try {
98
+ return readdirSync(dir, { withFileTypes: true })
99
+ .filter((e) => !e.isDirectory())
100
+ .map((e) => e.name);
101
+ }
102
+ catch {
103
+ return [];
104
+ }
105
+ }
@@ -0,0 +1,140 @@
1
+ import { closeSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync } from 'node:fs';
2
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { branchOf, git, repos } from "./git.js";
4
+ import { localDate } from "./list.js";
5
+ import { readTask } from "./read.js";
6
+ import { real, resolveTask } from "./resolve.js";
7
+ /**
8
+ * `ken task archive`: move each task `args` name to `.archive/<its path in the folder>`, a
9
+ * relative link made anew so it reaches its file, after every one is checked: closed, not already archived, and with no branch left on this
10
+ * machine. A name already archived keeps its file; the new one takes the first free numeric
11
+ * suffix before its extension, which `renamed` says. Only the named files are touched:
12
+ * a reference still resolves, through the archive.
13
+ */
14
+ export function archiveTasks(root, configured, cwd, args) {
15
+ const folder = real(configured);
16
+ const archive = join(folder, '.archive');
17
+ const repo = repos();
18
+ const paths = [...new Set(args.map((arg) => resolveTask(root, configured, cwd, arg)))];
19
+ for (const path of paths) {
20
+ if (path.startsWith(`${archive}/`)) {
21
+ throw new Error(`${path} is already in the archive, so nothing is moved. Run \`ken task list\` for the live tasks; to bring it back, \`mv\` it to its path in ${folder}.`);
22
+ }
23
+ if (!regular(path)) {
24
+ throw new Error(`${path} is not a regular file, nor a link to one, so it cannot be read as closed and is not archived: \`ls -l ${path}\` shows what it is. ` +
25
+ 'Make it a file, or remove it by hand. Nothing was moved.');
26
+ }
27
+ const { fields, problems } = readTask(basename(path), readFileSync(path, 'utf8'));
28
+ if (problems.length || (fields.status !== 'done' && fields.status !== 'wontfix')) {
29
+ throw new Error(`${path} is open (${problems.length ? 'it could not be fully read' : `status ${fields.status}`}), ` +
30
+ 'and the archive holds closed tasks only: an archived task blocks nothing, so archiving open work would make its dependents ready. ' +
31
+ `If it is finished, run \`ken task set ${path} status done\`, then rerun. Nothing was moved.`);
32
+ }
33
+ const name = branchOf(folder, path);
34
+ if (fields.repo && repo(fields.repo)?.exists(name)) {
35
+ throw new Error(`${path} still has its branch ${name} in ${fields.repo}, and an archived task's branch would be left behind with nothing listing it. ` +
36
+ `Run \`ken task finish ${path}\` to remove its worktree and branch, then rerun. Nothing was moved.`);
37
+ }
38
+ }
39
+ return paths.map((path) => {
40
+ const rel = relative(folder, path);
41
+ const ext = extname(rel);
42
+ const link = lstatSync(path).isSymbolicLink() ? readlinkSync(path) : undefined;
43
+ mkdirSync(join(archive, dirname(rel)), { recursive: true });
44
+ // each name is taken by an exclusive create, so a concurrent archive never overwrites
45
+ // one: a link is made anew there, relative to its new folder so it still reaches its
46
+ // file; a file is renamed over the empty file that holds its name
47
+ let target = join(archive, rel);
48
+ for (let n = 2;; n++) {
49
+ try {
50
+ if (link === undefined)
51
+ closeSync(openSync(target, 'wx'));
52
+ else {
53
+ const to = isAbsolute(link)
54
+ ? link
55
+ : relative(dirname(target), resolve(dirname(path), link));
56
+ symlinkSync(to, target);
57
+ }
58
+ break;
59
+ }
60
+ catch (e) {
61
+ if (e.code !== 'EEXIST')
62
+ throw e;
63
+ }
64
+ target = join(archive, dirname(rel), `${basename(rel, ext)}-${n}${ext}`);
65
+ }
66
+ if (link === undefined)
67
+ renameSync(path, target);
68
+ else
69
+ rmSync(path);
70
+ const renamed = target === join(archive, rel)
71
+ ? undefined
72
+ : `${join(archive, rel)} was already archived, so ${path} is archived as ${target}; a reference to ${rel} still resolves to one of them.`;
73
+ return { path: target, renamed };
74
+ });
75
+ }
76
+ /** Whether `path` is a regular file or a link to one: a pipe or a device is never read. */
77
+ function regular(path) {
78
+ try {
79
+ return statSync(path).isFile();
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ /** Every regular file under `dir`, or link to one, at any depth; none if it cannot be read. */
86
+ function files(dir) {
87
+ try {
88
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
89
+ const path = join(dir, e.name);
90
+ return e.isDirectory() ? files(path) : regular(path) ? [path] : [];
91
+ });
92
+ }
93
+ catch {
94
+ return [];
95
+ }
96
+ }
97
+ /**
98
+ * `ken task purge`: delete each file in the archive whose `closed`, else its mtime, is
99
+ * before `today` less `days`, and say whether the folder is in a git work tree, which then
100
+ * holds what was committed of them; else nothing does.
101
+ */
102
+ export function purgeArchive(configured, days, today) {
103
+ const folder = real(configured);
104
+ const archive = join(folder, '.archive');
105
+ const cutoff = localDate(new Date(today.getTime() - days * 864e5));
106
+ // dates compare as text, so a cutoff must be a four-digit year
107
+ if (!/^\d{4}-/.test(cutoff)) {
108
+ throw new Error(`--older-than ${days} reaches before the year 1000, so no file can be that old and nothing was deleted. ` +
109
+ 'Run `ken task purge --older-than <days>` with a number of days that ends after that, e.g. `ken task purge --older-than 365`.');
110
+ }
111
+ const deleted = files(archive).filter((path) => {
112
+ let closed;
113
+ try {
114
+ closed = readTask(basename(path), readFileSync(path, 'utf8')).fields.closed;
115
+ }
116
+ catch { }
117
+ return (closed ?? localDate(statSync(path).mtime)) < cutoff;
118
+ });
119
+ for (const path of deleted)
120
+ rmSync(path);
121
+ if (!deleted.length) {
122
+ return {
123
+ deleted,
124
+ said: `Nothing in ${archive} was closed, else last modified, before ${cutoff}, so nothing was deleted.`
125
+ };
126
+ }
127
+ let top;
128
+ try {
129
+ top = git(folder, 'rev-parse', '--show-toplevel');
130
+ }
131
+ catch { }
132
+ const what = `Deleted ${deleted.length} archived task${deleted.length > 1 ? 's' : ''} closed, else last modified, before ${cutoff}.`;
133
+ return {
134
+ deleted,
135
+ said: top
136
+ ? `${what} ${folder} is in the git work tree ${top}, so its history holds what was committed of them: ` +
137
+ `\`git -C ${top} log --oneline -- ${archive}\` lists those commits, and \`git -C ${top} add -A ${archive}\` stages the deletion to commit.`
138
+ : `${what} ${folder} is in no git work tree, so nothing else holds a copy: they are gone.`
139
+ };
140
+ }
package/dist/claim.js ADDED
@@ -0,0 +1,106 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { branchOf, codePath, git, isClone } from "./git.js";
3
+ import { listTasks, readyTasks } from "./list.js";
4
+ import { real, resolveTask } from "./resolve.js";
5
+ /**
6
+ * `ken task claim [<task>]`: give the task `arg` names, or without it the first ready repo
7
+ * task whose repo is cloned here, its branch and worktree, and return the worktree. The
8
+ * branch is made first: git's ref lock on it is the claim, so of two callers only one wins;
9
+ * without a task, the loser goes on to the next.
10
+ */
11
+ export function claimTask(root, configured, cwd, arg, today) {
12
+ const folder = real(configured);
13
+ if (arg === undefined) {
14
+ for (const row of readyTasks(root, configured, today)) {
15
+ if (!row.repo || !isClone(codePath(row.repo)))
16
+ continue;
17
+ const worktree = claim(row.repo, branchOf(folder, row.path));
18
+ if (worktree)
19
+ return worktree;
20
+ }
21
+ throw new Error('No ready task with a repo cloned here is left to claim. ' +
22
+ 'Run `ken task list` to see what each task waits on; a ready task with no repo takes `ken task set <task> repo <key>`, one whose repo is not here `ken get <key>`.');
23
+ }
24
+ const path = resolveTask(root, configured, cwd, arg);
25
+ // its refusal says it when the task's repo is not cloned, so the listing does not
26
+ const row = listTasks(root, configured, today, { quiet: true }).find((r) => r.path === path);
27
+ const name = branchOf(folder, path);
28
+ const key = requireClaimable(path, name, row);
29
+ const worktree = claim(key, name);
30
+ if (worktree)
31
+ return worktree;
32
+ throw new Error(`${path} was claimed by another caller first: its branch ${name} now exists in ${key}. ` +
33
+ 'Run `ken task claim` for the next ready task.');
34
+ }
35
+ /** The repo key of the task at `path`, listed as `row`, or a throw saying why it cannot be claimed. */
36
+ function requireClaimable(path, name, row) {
37
+ const next = 'Run `ken task claim` for the next ready task, or `ken task list` to see each state.';
38
+ if (!row)
39
+ throw new Error(`${path} is archived, so it is closed and there is nothing to claim. ${next}`);
40
+ const { state, repo } = row;
41
+ if (state === 'claimed' && repo) {
42
+ throw new Error(`${path} is claimed: its branch ${name} exists in ${repo}. ` +
43
+ `Work in its worktree, \`cd "$(ken get ${repo} -b ${name})"\`, or run \`ken task claim\` for the next ready task.`);
44
+ }
45
+ if (state !== 'ready') {
46
+ const why = state === 'blocked'
47
+ ? `, waiting on ${row.unmet.map((u) => `${u.ref} (${u.reason})`).join(', ')}`
48
+ : state === 'later'
49
+ ? `, scheduled for ${row.scheduled}`
50
+ : state === 'problem'
51
+ ? `: ${row.notes.join('; ')}`
52
+ : '';
53
+ throw new Error(`${path} is ${state}${why}, and only a ready task can be claimed. ${next}`);
54
+ }
55
+ if (!repo) {
56
+ throw new Error(`${path} has no repo, so there is no clone to make its branch in. ` +
57
+ `Run \`ken task set ${path} repo <host>/<owner>/<repo>\`, then \`ken task claim ${path}\`.`);
58
+ }
59
+ const clone = codePath(repo);
60
+ if (!isClone(clone)) {
61
+ throw new Error(`${repo} is not cloned here (${clone}), so there is no clone to make the branch of ${path} in. ` +
62
+ `Run \`ken get ${repo}\`, which clones it or says what is in its place, then \`ken task claim ${path}\`.`);
63
+ }
64
+ return repo;
65
+ }
66
+ /** `ken get <args>`, its stderr passed through: its stdout, or a throw saying what to do after it. */
67
+ function kenGet(args, next) {
68
+ const r = spawnSync('ken', ['get', ...args], {
69
+ encoding: 'utf8',
70
+ stdio: ['inherit', 'pipe', 'inherit']
71
+ });
72
+ if (r.status !== 0) {
73
+ throw new Error(`${r.error ? `ken could not be run (${r.error.message}): ` : ''}${next}`);
74
+ }
75
+ return r.stdout.trim();
76
+ }
77
+ /**
78
+ * Make branch `name` in the clone of `key` from its default branch as it stands, no fetch,
79
+ * then its worktree with `ken get -b`, and return the worktree; undefined when the branch
80
+ * exists already, which means another caller won it. `ken get` checks the clone first, so a
81
+ * clone it would refuse, such as a link to a repo elsewhere, gets no branch.
82
+ */
83
+ function claim(key, name) {
84
+ const clone = kenGet([key], `\`ken get ${key}\` refused the clone of ${key}, as said above, so no branch was made for ${name}. Fix what it names, then rerun.`);
85
+ let main;
86
+ try {
87
+ main = git(clone, 'symbolic-ref', '-q', 'HEAD');
88
+ }
89
+ catch {
90
+ throw new Error(`${clone} has a detached HEAD, so its default branch, the one the clone holds, is unknown and there is nothing to branch ${name} from. ` +
91
+ `Check it out there, e.g. \`git -C ${clone} switch main\`, then rerun.`);
92
+ }
93
+ try {
94
+ // the full ref name: the short one turns ambiguous once a tag of the same name exists;
95
+ // `--` so a name from a file like -m.md is a name git refuses, never an option
96
+ git(clone, 'branch', '--', name, main);
97
+ }
98
+ catch (e) {
99
+ if (git(clone, 'branch', '--list', '--', name))
100
+ return undefined;
101
+ throw new Error(`could not create branch ${name}, the task's path in the folder without extension, in ${clone}: ${e.message}\n` +
102
+ 'If git refuses the name, move the task file to a name of letters, digits and dashes, then claim it again.');
103
+ }
104
+ return kenGet([key, '-b', name], `branch ${name} is made in ${clone}, so the task is claimed, but its worktree is not ready. ` +
105
+ `Finish by hand as said above, or fix the cause and run \`ken get ${key} -b ${name}\`, which prints the worktree.`);
106
+ }