estimetry 0.1.0 → 0.1.2

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/CHANGELOG.md CHANGED
@@ -4,6 +4,16 @@ All notable changes to estimetry. Versions follow [semantic versioning](https://
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.1.2 — 2026-11-12
8
+
9
+ - The hooks `init` writes run the installation of estimetry that ran it, by the paths of its Node.js and entry point, and fall back to `estimetry` on `PATH`. A version manager (asdf, nvm) that picks another Node.js for a project, or one without estimetry, no longer stops the Claude Code hooks or the `post-commit` hook. Settings and hooks the project commits keep the plain `estimetry hook …`. Run `emt upgrade` once to rewrite the hooks.
10
+
11
+ ## 0.1.1 — 2026-11-12
12
+
13
+ - The npm page shows the English README: the Russian one is now `README-ru.md`, which npm does not pack.
14
+ - macOS: a directory spelled in another case than at `init` is the same project, for the CLI and the hooks; paths are compared as the disk keeps them, and paths registered before are matched too.
15
+ - A commit from a program without your shell's `PATH` (an IDE started from the Dock on macOS) is recorded: the personal `post-commit` hook falls back to the Node.js and estimetry `init` ran with. Run `emt upgrade` once to update the hook.
16
+
7
17
  ## 0.1.0 — 2026-11-12
8
18
 
9
19
  The first public version: estimates of AI-agent development work compared with the actual effort, and that experience reused in the next estimate. Claude Code is the only supported AI tool.
@@ -16,5 +26,5 @@ The first public version: estimates of AI-agent development work compared with t
16
26
  - Estimates from past tasks: `emt similar` and `emt calibrate`, used by `/emt-estimate`.
17
27
  - Work in git worktrees: a worktree belongs to the project of its main working copy, and the plan, checkpoints and code volume of a task are read in the working copy that holds its changes, also when the session runs in the main working copy. `emt attach --session` counts the first task of a session from the start of the task.
18
28
  - `emt upgrade`: after updating estimetry, sets it up again in every project on this machine with one command, after showing the plan and asking. The session start tells the agent to suggest it when a project was set up by an older version.
19
- - The README in English and Russian, with a reference of every command and flag ([README.ru.md](https://github.com/aleksei-shvets/estimetry/blob/main/README.ru.md)).
29
+ - The README in English and Russian, with a reference of every command and flag ([README-ru.md](https://github.com/aleksei-shvets/estimetry/blob/main/README-ru.md)).
20
30
  - Requires Node.js 22.12 or newer.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # estimetry
2
2
 
3
- **English** | [Русский](https://github.com/aleksei-shvets/estimetry/blob/main/README.ru.md)
3
+ **English** | [Русский](https://github.com/aleksei-shvets/estimetry/blob/main/README-ru.md)
4
4
 
5
5
  Compares work estimates with the actual effort in AI-agent development and reuses that experience in the next estimate.
6
6
 
@@ -18,7 +18,7 @@ npm install -g estimetry
18
18
  emt --version
19
19
  ```
20
20
 
21
- Install it globally: the hooks of Claude Code call `estimetry` from `PATH`.
21
+ Install it globally. The hooks `init` writes run this installation by its paths, so neither a version manager (asdf, nvm) that picks another Node.js for a project nor a program without your shell's `PATH` stops them.
22
22
 
23
23
  To update later: `npm install -g estimetry@latest`, then `emt upgrade` once (see [After upgrading estimetry](#after-upgrading-estimetry)).
24
24
 
@@ -61,13 +61,13 @@ In a terminal it asks a few questions:
61
61
 
62
62
  | What | Where | Who gets it |
63
63
  |---|---|---|
64
- | Hooks for 12 Claude Code events, each running `estimetry hook claude-code <event>` | `.claude/settings.local.json` | you |
64
+ | Hooks for 12 Claude Code events, each running this installation (`<node> <estimetry> hook claude-code <event>`, else `estimetry hook claude-code <event>` from `PATH`) | `.claude/settings.local.json` | you |
65
65
  | Skills `estimetry`, `emt-estimate`, `emt-start`, `emt-extra`, `emt-parallel`, `emt-manual`, `emt-close`, `emt-retro` (also the `/emt-…` commands) | `~/.claude/skills/` (or `$CLAUDE_CONFIG_DIR/skills/`) | you, in every project |
66
66
  | Project id and development process | `.estimetry/config.yaml` | the team; commit it so clones of the repository are one project |
67
67
 
68
68
  With `--shared-hooks` the hooks go to `.claude/settings.json` and the skills to `.claude/skills/` of the project. A reminder to run `/emt-estimate` before naming a deadline is added to `CLAUDE.md`, between `<!-- estimetry:start -->` and `<!-- estimetry:end -->`. These are files the project commits, so the whole team gets them.
69
69
 
70
- With `--track-commits` a `post-commit` hook is installed into the repository's hooks directory. This respects `core.hooksPath`, worktrees and husky (`.husky/post-commit`). An existing hook keeps its content: estimetry adds its own block between `# >>> estimetry >>>` and `# <<< estimetry <<<`. The hook runs estimetry in the background, so commits never wait for it. Colleagues without estimetry see nothing.
70
+ With `--track-commits` a `post-commit` hook is installed into the repository's hooks directory. This respects `core.hooksPath`, worktrees and husky (`.husky/post-commit`). An existing hook keeps its content: estimetry adds its own block between `# >>> estimetry >>>` and `# <<< estimetry <<<`. The hook runs estimetry in the background, so commits never wait for it. Colleagues without estimetry see nothing. A personal hook (in `.git`, or a hooks directory outside the repository) runs this installation by its paths, like the Claude Code hooks, so a commit from an IDE started from the Dock is recorded too. A hook the project commits (husky, `core.hooksPath` inside the repository) holds no paths of your machine and needs `estimetry` on `PATH`.
71
71
 
72
72
  No task data ever goes into the repository. Tasks, estimates and the event journal live in `~/.local/share/estimetry/`, or in `ESTIMETRY_HOME` if set.
73
73
 
@@ -89,9 +89,9 @@ A repeated run keeps what is installed: once the git hook or the shared install
89
89
  ### Good to know
90
90
 
91
91
  - **Your edits to generated skills are kept.** Every generated skill carries `metadata.generatedBy` and a hash of its content. If you edit one, init keeps your version and reports it as `skipped`; `--force` overwrites it. A file of the same name that estimetry did not create is never touched.
92
- - **A rewritten hook is yours.** estimetry recognises its hooks by the command prefix `estimetry hook claude-code`. If you change that command, init treats the hook as yours and adds its own next to it.
92
+ - **A rewritten hook is yours.** estimetry recognises its hooks by the command it writes: the paths of the installation that fall back to `estimetry hook claude-code`, or that prefix alone. If you change that command, init treats the hook as yours and adds its own next to it.
93
93
  - **`settings.local.json` may not be ignored by git.** Claude Code adds `**/.claude/settings.local.json` to your global git excludes only when it writes that file itself. If init creates it and git does not ignore it, init offers to add the same line. With `--no-interactive` it only warns.
94
- - **Hooks need `estimetry` on `PATH`.** When run through `npx`, the hooks will not find it, and init warns about that.
94
+ - **Hooks run the installation that ran `init`.** `npm install -g` under the same Node.js replaces it in place. After installing estimetry under another Node.js, or removing the one that ran `init`, run `emt upgrade`: until then the hooks run the old installation or fall back to `estimetry` on `PATH`. Run through `npx`, or on Windows, init writes no paths, and the hooks need `estimetry` on `PATH`. The hooks also keep the data directory of that `init` unless `ESTIMETRY_HOME` is set where they run: an `init` with a temporary `ESTIMETRY_HOME` sends the hooks of the project there too.
95
95
 
96
96
  ## Estimating a task
97
97
 
@@ -307,7 +307,7 @@ The journal keeps when things happened, not what was said or done: no prompt tex
307
307
 
308
308
  Run `emt upgrade` once, from any directory. It sets estimetry up again in every working copy of every registered project on this machine (worktrees included), each with the choices it already has: tools, flow, a personal or shared install, the commit hook. It shows what will change and asks first; without a terminal it needs `--yes`. A copy where estimetry was never set up is skipped, and so is one that is not on this machine. With a shared install the plan warns that the files it changes are committed by the project. To update a single project instead, run `emt init` inside it.
309
309
 
310
- Until then the hooks keep working: they run the new `estimetry` from `PATH`; only what `init` wrote is old — the hook settings in each project, the skills and, with a shared install, the reminder in `CLAUDE.md`. At the start of a session in a project set up by an older version, the agent is told to suggest `emt upgrade`; it never runs it on its own.
310
+ Until then the hooks keep working: an update under the same Node.js replaces the installation they run; only what `init` wrote is old — the hook settings in each project, the skills and, with a shared install, the reminder in `CLAUDE.md`. At the start of a session in a project set up by an older version, the agent is told to suggest `emt upgrade`; it never runs it on its own.
311
311
 
312
312
  Update every installed copy of estimetry at once. Cards written by an older version are rebuilt from the journals on the next closing, `emt task show` or `emt rebuild`. A newer card stops an older estimetry from rewriting `calibration.json` and is reported instead; versions before this check skip such cards silently, so close no task with them.
313
313
 
@@ -0,0 +1,34 @@
1
+ /** The first word of a command with the paths of an installation. */
2
+ const RUNNER_MARKER = 'estimetry_home=';
3
+ /**
4
+ * A POSIX shell command that runs `estimetry <args>` (estimetry-command, one
5
+ * rule for every hook): this installation by its paths while they exist, else
6
+ * `estimetry` from PATH. ESTIMETRY_HOME set by the user wins over the one of `init`.
7
+ */
8
+ export function estimetryCommand(runner, args) {
9
+ const fromPath = `estimetry ${args}`;
10
+ if (runner === undefined) {
11
+ return fromPath;
12
+ }
13
+ const node = quoted(runner.node);
14
+ const main = quoted(runner.main);
15
+ return (`${RUNNER_MARKER}${quoted(runner.home)}; ` +
16
+ `if [ -x ${node} ] && [ -f ${main} ]; then ESTIMETRY_HOME="\${ESTIMETRY_HOME:-$estimetry_home}" ${node} ${main} ${args}; ` +
17
+ `else ${fromPath}; fi`);
18
+ }
19
+ /**
20
+ * Whether a command is one `estimetryCommand` writes for these arguments, in
21
+ * either form, or a command of an older version (`estimetry <args> …`): hooks
22
+ * are recognised on reinstall by the same rule that writes them.
23
+ */
24
+ export function isEstimetryCommand(command, argsPrefix) {
25
+ const fromPath = `estimetry ${argsPrefix}`;
26
+ const plain = command === fromPath || command.startsWith(`${fromPath} `);
27
+ const withPaths = command.startsWith(RUNNER_MARKER) && command.includes(`; else ${fromPath} `) && command.endsWith('; fi');
28
+ return plain || withPaths;
29
+ }
30
+ /** A path for a POSIX shell in single quotes: spaces and quotes in it stay one word. */
31
+ function quoted(path) {
32
+ return `'${path.replaceAll("'", `'\\''`)}'`;
33
+ }
34
+ //# sourceMappingURL=estimetry-command.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=estimetry-runner.js.map
@@ -63,7 +63,8 @@ export class InitProject {
63
63
  if (this.deps.sharing.mode() !== share) {
64
64
  this.deps.sharing.save(share);
65
65
  }
66
- if (!this.deps.commands.has(HOOK_COMMAND)) {
66
+ // Personal hooks run this installation by its paths; shared ones, and all without paths (npx, Windows), need PATH.
67
+ if ((shared || this.deps.installation.runner === undefined) && !this.deps.commands.has(HOOK_COMMAND)) {
67
68
  warnings.push(`${HOOK_COMMAND} is not on PATH, so the hooks will not run until the package is installed globally (npm install -g estimetry)`);
68
69
  }
69
70
  return {
@@ -16,9 +16,11 @@ export class InstallCopy {
16
16
  }
17
17
  plan(choices) {
18
18
  const { root } = choices;
19
+ const { version, runner } = this.deps.installation;
20
+ const context = { projectRoot: root, files: this.deps.files, shared: choices.shared, force: choices.force, version };
19
21
  const plan = mergePlans([
20
- ...choices.tools.map((tool) => tool.plan({ projectRoot: root, files: this.deps.files, shared: choices.shared, force: choices.force, version: this.deps.version })),
21
- this.deps.git.commitHook.plan(root, choices.trackCommits),
22
+ ...choices.tools.map((tool) => tool.plan(runner === undefined ? context : { ...context, runner })),
23
+ this.deps.git.commitHook.plan(root, choices.trackCommits, runner),
22
24
  { changes: [this.projectConfig.plan(root, { project: choices.project, flow: choices.flow.id })], skipped: [], warnings: [] },
23
25
  choices.shared ? EMPTY_PLAN : this.excludePersonalFiles(root, choices.tools, choices.excludePersonalFiles),
24
26
  ]);
@@ -51,7 +53,7 @@ export class InstallCopy {
51
53
  this.deps.files.write(change.path, change.content, change.executable ? { executable: true } : {});
52
54
  }
53
55
  }
54
- this.versions.record(plan.root, this.deps.version);
56
+ this.versions.record(plan.root, this.deps.installation.version);
55
57
  }
56
58
  statusOf(change) {
57
59
  const current = this.deps.files.read(change.path);
@@ -45,7 +45,7 @@ export class UpgradePlanner {
45
45
  copies.push({ ...result, files, warnings });
46
46
  }
47
47
  }
48
- return { version: this.deps.version, copies, skipped };
48
+ return { version: this.deps.installation.version, copies, skipped };
49
49
  }
50
50
  copy(project, root) {
51
51
  const id = project.id.value;
@@ -1,5 +1,7 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
1
3
  import { homedir, userInfo } from 'node:os';
2
- import { join } from 'node:path';
4
+ import { basename, dirname, join, sep } from 'node:path';
3
5
  import { StorageLayout } from '../infrastructure/fs/storage-layout.js';
4
6
  import { FileErrorReporter } from '../infrastructure/system/file-error-reporter.js';
5
7
  export function processEnvironment() {
@@ -7,6 +9,25 @@ export function processEnvironment() {
7
9
  }
8
10
  import { packageVersion } from './package-version.js';
9
11
  export { packageVersion };
12
+ /**
13
+ * How hooks start this installation (estimetry-command): the entry point beside
14
+ * this file, the node of its npm prefix when it is a global npm install (a
15
+ * stable link such as Homebrew's `/opt/homebrew/bin/node`, which survives an
16
+ * upgrade of Node.js), else the running node, and the data directory. None on
17
+ * Windows, where Claude Code may run hooks without a POSIX shell, and none from
18
+ * the cache of `npx`, which is cleared: hooks then call `estimetry` from PATH.
19
+ */
20
+ function estimetryRunner(layout) {
21
+ const main = fileURLToPath(new URL('./main.js', import.meta.url));
22
+ if (process.platform === 'win32' || main.includes(`${sep}_npx${sep}`)) {
23
+ return undefined;
24
+ }
25
+ // <prefix>/lib/node_modules/estimetry/dist/bootstrap/main.js → <prefix>/bin/node, only for that layout.
26
+ const pkg = dirname(dirname(dirname(main)));
27
+ const globalNpm = basename(pkg) === 'estimetry' && basename(dirname(pkg)) === 'node_modules' && basename(dirname(dirname(pkg))) === 'lib';
28
+ const prefixed = join(dirname(dirname(dirname(pkg))), 'bin', 'node');
29
+ return { node: globalNpm && existsSync(prefixed) ? prefixed : process.execPath, main, home: layout.root };
30
+ }
10
31
  /** Claude Code keeps personal skills in `$CLAUDE_CONFIG_DIR`, else `~/.claude`. */
11
32
  function claudeConfigDir(environment) {
12
33
  const configured = environment.env['CLAUDE_CONFIG_DIR'];
@@ -35,7 +56,7 @@ async function toolRegistry(environment) {
35
56
  ]);
36
57
  return new ToolAdapterRegistry().register(new ClaudeCodeAdapter(claudeConfigDir(environment)));
37
58
  }
38
- async function installDependencies(environment, sharing) {
59
+ async function installDependencies(environment, sharing, layout) {
39
60
  const [tools, { FlowRegistry }, { openSpecFlow }, { noneFlow }, { StackDetectorRegistry }, { nodeDetector }, { dartDetector }, { mavenDetector, gradleDetector }, { pythonDetector }, { goDetector }, { composeDetector }, { NodeProjectFiles }, { GitCommitHookInstaller }, { GitExcludesFile }, { PathCommandLocator },] = await Promise.all([
40
61
  toolRegistry(environment),
41
62
  import('../integrations/flows/registry.js'),
@@ -53,6 +74,7 @@ async function installDependencies(environment, sharing) {
53
74
  import('../infrastructure/git/git-excludes-file.js'),
54
75
  import('../infrastructure/system/path-command-locator.js'),
55
76
  ]);
77
+ const runner = estimetryRunner(layout);
56
78
  return {
57
79
  files: new NodeProjectFiles(),
58
80
  registries: {
@@ -61,10 +83,13 @@ async function installDependencies(environment, sharing) {
61
83
  flows: new FlowRegistry().register(openSpecFlow).register(noneFlow),
62
84
  detectors: [nodeDetector, dartDetector, mavenDetector, gradleDetector, pythonDetector, goDetector, composeDetector].reduce((registry, detector) => registry.register(detector), new StackDetectorRegistry()),
63
85
  },
64
- git: { commitHook: new GitCommitHookInstaller(), excludes: new GitExcludesFile(environment.env, environment.homeDir) },
86
+ git: {
87
+ commitHook: new GitCommitHookInstaller(),
88
+ excludes: new GitExcludesFile(environment.env, environment.homeDir),
89
+ },
65
90
  sharing,
66
91
  commands: new PathCommandLocator(environment.env),
67
- version: packageVersion(),
92
+ installation: { version: packageVersion(), ...(runner === undefined ? {} : { runner }) },
68
93
  };
69
94
  }
70
95
  async function buildApp(layout, environment, errors) {
@@ -89,7 +114,7 @@ async function buildApp(layout, environment, errors) {
89
114
  const config = new YamlConfigStore(layout, () => git.userEmail() ?? userInfo().username);
90
115
  const projects = new FileProjectRepository(layout);
91
116
  const projectConfig = new YamlProjectConfigFile();
92
- const install = await installDependencies(environment, config);
117
+ const install = await installDependencies(environment, config, layout);
93
118
  return createEstimetry({
94
119
  tasks: new FileTaskRepository(layout),
95
120
  projects,
@@ -1,6 +1,6 @@
1
1
  import { sep } from 'node:path';
2
2
  import { readYaml } from './atomic-yaml.js';
3
- import { mainWorktree, realPath } from './worktree.js';
3
+ import { mainWorktree, realPath, registeredPath } from './worktree.js';
4
4
  import { ProjectId } from '../../domain/project/project-id.js';
5
5
  /**
6
6
  * Finds the registered project of a directory without running git: real
@@ -17,8 +17,15 @@ export class FsProjectLocator {
17
17
  if (real === undefined) {
18
18
  return undefined;
19
19
  }
20
+ const main = mainWorktree(real) ?? real;
20
21
  const registered = this.registered();
21
- return longestOwner(registered, real) ?? longestOwner(registered, mainWorktree(real) ?? real);
22
+ const found = longestOwner(registered, real) ?? longestOwner(registered, main);
23
+ if (found !== undefined) {
24
+ return found;
25
+ }
26
+ // A path registered before paths were made real (a symlink, another case on macOS): only on a miss the disk is asked.
27
+ const madeReal = registered.map(({ id, path }) => ({ id, path: registeredPath(path) }));
28
+ return longestOwner(madeReal, real) ?? longestOwner(madeReal, main);
22
29
  }
23
30
  registered() {
24
31
  let document;
@@ -35,7 +42,9 @@ export class FsProjectLocator {
35
42
  return projects.flatMap((p) => {
36
43
  const project = p;
37
44
  return typeof project.id === 'string' && isProjectId(project.id) && Array.isArray(project.paths)
38
- ? project.paths.filter((path) => typeof path === 'string').map((path) => ({ id: project.id, path }))
45
+ ? project.paths
46
+ .filter((path) => typeof path === 'string')
47
+ .map((path) => ({ id: project.id, path }))
39
48
  : [];
40
49
  });
41
50
  }
@@ -31,13 +31,48 @@ export function mainWorktree(directory) {
31
31
  }
32
32
  }
33
33
  }
34
- /** The real path, or undefined when it does not exist. */
34
+ /**
35
+ * The real path, or undefined when it does not exist: symlinks resolved and,
36
+ * on a file system that ignores case (macOS), the case the disk keeps — so a
37
+ * directory spelled otherwise is the same path in the registry. The one place
38
+ * paths are made real. Where the native call fails for another reason (a
39
+ * virtual file system, Linux without `/proc`) the JS one resolves symlinks.
40
+ */
35
41
  export function realPath(path) {
36
42
  try {
37
- return realpathSync(path);
43
+ return realpathSync.native(path);
38
44
  }
39
- catch {
40
- return undefined;
45
+ catch (error) {
46
+ if (isMissing(error)) {
47
+ return undefined;
48
+ }
49
+ try {
50
+ return realpathSync(path);
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
41
55
  }
42
56
  }
57
+ /** The real path of a file that may not exist yet: its nearest existing directory made real, the rest as written. */
58
+ export function realPathAhead(path) {
59
+ const real = realPath(path);
60
+ if (real !== undefined) {
61
+ return real;
62
+ }
63
+ const parent = dirname(path);
64
+ return parent === path ? path : join(realPathAhead(parent), basename(path));
65
+ }
66
+ /**
67
+ * A registered path as it is compared: the real path while it exists here, else
68
+ * as written. A path registered before paths were made real (through a symlink,
69
+ * another case on macOS) still matches; one of another machine stays as it is.
70
+ */
71
+ export function registeredPath(path) {
72
+ return realPath(path) ?? path;
73
+ }
74
+ function isMissing(error) {
75
+ const code = error?.code;
76
+ return code === 'ENOENT' || code === 'ENOTDIR';
77
+ }
43
78
  //# sourceMappingURL=worktree.js.map
@@ -1,6 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { realpathSync } from 'node:fs';
3
- import { mainWorktree } from '../fs/worktree.js';
2
+ import { mainWorktree, realPath } from '../fs/worktree.js';
4
3
  /** Talks to the `git` executable directly (no shell), so it also works on Windows. */
5
4
  export class GitCli {
6
5
  cwd;
@@ -9,7 +8,10 @@ export class GitCli {
9
8
  this.cwd = cwd;
10
9
  }
11
10
  currentRoot() {
12
- this.root ??= realpathSync(this.run(['rev-parse', '--show-toplevel']) ?? this.cwd);
11
+ if (this.root === undefined) {
12
+ const root = this.run(['rev-parse', '--show-toplevel']) ?? this.cwd;
13
+ this.root = realPath(root) ?? root;
14
+ }
13
15
  return this.root;
14
16
  }
15
17
  fingerprint() {
@@ -1,6 +1,8 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { readFileSync } from 'node:fs';
3
- import { join, normalize, relative, sep } from 'node:path';
3
+ import { isAbsolute, join, normalize, relative, sep } from 'node:path';
4
+ import { realPathAhead } from '../fs/worktree.js';
5
+ import { estimetryCommand } from '../../application/contracts/estimetry-command.js';
4
6
  export const BLOCK_START = '# >>> estimetry >>>';
5
7
  export const BLOCK_END = '# <<< estimetry <<<';
6
8
  /**
@@ -9,7 +11,16 @@ export const BLOCK_END = '# <<< estimetry <<<';
9
11
  * by the time the background process looks, `HEAD` may already be the next commit.
10
12
  */
11
13
  export const BLOCK_COMMAND = 'if command -v estimetry >/dev/null 2>&1; then estimetry_sha=$(git rev-parse HEAD 2>/dev/null); printf \'%s\' "$estimetry_sha" | estimetry hook git post-commit >/dev/null 2>&1 & fi';
12
- const BLOCK = [BLOCK_START, BLOCK_COMMAND, BLOCK_END];
14
+ /**
15
+ * The personal hook runs this installation by its paths first, so neither the
16
+ * node a version manager picks for the project nor a program without the
17
+ * user's PATH (an IDE started from the Dock) stops it; else `estimetry` from
18
+ * PATH. A hook the project commits never holds the paths: they are this machine's.
19
+ */
20
+ function personalCommand(runner) {
21
+ return ('estimetry_sha=$(git rev-parse HEAD 2>/dev/null); ' +
22
+ `printf '%s' "$estimetry_sha" | { ${estimetryCommand(runner, 'hook git post-commit')}; } >/dev/null 2>&1 &`);
23
+ }
13
24
  const HUSKY_LOADER = '. "$(dirname "$0")/_/husky.sh"';
14
25
  const SHELLS = /^#!.*\b(sh|bash|zsh|dash|ksh)\b/;
15
26
  const MANAGERS = [
@@ -23,15 +34,16 @@ export class GitCommitHookInstaller {
23
34
  const layout = this.layout(projectRoot);
24
35
  return layout !== undefined && (read(layout.path) ?? '').includes(BLOCK_START);
25
36
  }
26
- plan(projectRoot, enabled) {
37
+ plan(projectRoot, enabled, runner) {
27
38
  const layout = this.layout(projectRoot);
28
39
  if (layout === undefined) {
29
40
  return enabled ? { changes: [], skipped: [], warnings: ['not a git repository, so --track-commits was skipped'] } : EMPTY;
30
41
  }
31
42
  const current = read(layout.path);
32
- return enabled ? this.install(layout, current) : this.uninstall(layout, current);
43
+ return enabled ? this.install(layout, current, runner) : this.uninstall(layout, current);
33
44
  }
34
- install(layout, current) {
45
+ install(layout, current, runner) {
46
+ const block = blockFor(layout, runner);
35
47
  const warnings = [];
36
48
  if (layout.husky !== undefined) {
37
49
  warnings.push(`${layout.shown} is part of the repository: the hook runs for colleagues who have estimetry installed`);
@@ -39,7 +51,7 @@ export class GitCommitHookInstaller {
39
51
  if (current === undefined) {
40
52
  const header = layout.husky === 9 ? [] : layout.husky === 5 ? ['#!/bin/sh', HUSKY_LOADER, ''] : ['#!/bin/sh'];
41
53
  return {
42
- changes: [{ path: layout.path, content: `${[...header, ...BLOCK].join('\n')}\n`, executable: true }],
54
+ changes: [{ path: layout.path, content: `${[...header, ...block].join('\n')}\n`, executable: true }],
43
55
  skipped: [],
44
56
  warnings,
45
57
  };
@@ -56,7 +68,7 @@ export class GitCommitHookInstaller {
56
68
  if (manager !== undefined) {
57
69
  warnings.push(`${layout.shown} is managed by ${manager}, which may drop the estimetry block when it reinstalls its hooks; run init again then`);
58
70
  }
59
- return { changes: [{ path: layout.path, content: withBlock(lines), executable: true }], skipped: [], warnings };
71
+ return { changes: [{ path: layout.path, content: withBlock(lines, block), executable: true }], skipped: [], warnings };
60
72
  }
61
73
  uninstall(layout, current) {
62
74
  if (current === undefined || !current.includes(BLOCK_START)) {
@@ -93,18 +105,25 @@ export class GitCommitHookInstaller {
93
105
  }
94
106
  const EMPTY = { changes: [], skipped: [], warnings: [] };
95
107
  function located(projectRoot, path, husky) {
96
- const inside = relative(projectRoot, path);
97
- const shown = inside !== '' && !inside.startsWith('..') ? inside : path;
98
- return husky === undefined ? { path, shown } : { path, shown, husky };
108
+ // Real paths on both sides: an absolute core.hooksPath written through a symlink is still inside the repository.
109
+ const inside = relative(realPathAhead(projectRoot), realPathAhead(path));
110
+ const outside = inside === '' || inside === '..' || inside.startsWith(`..${sep}`) || isAbsolute(inside);
111
+ const shown = outside ? path : inside;
112
+ const personal = husky === undefined && (outside || inside.split(sep)[0] === '.git');
113
+ return husky === undefined ? { path, shown, personal } : { path, shown, personal, husky };
114
+ }
115
+ /** The lines between the markers: with the paths of this installation only in a personal hook. */
116
+ function blockFor(layout, runner) {
117
+ return [BLOCK_START, layout.personal && runner !== undefined ? personalCommand(runner) : BLOCK_COMMAND, BLOCK_END];
99
118
  }
100
119
  /** The block right after the shebang (and the husky loader), so an `exit` at the end cannot skip it. */
101
- function withBlock(lines) {
120
+ function withBlock(lines, block) {
102
121
  const rest = withoutBlock(lines);
103
122
  let at = rest[0]?.startsWith('#!') ? 1 : 0;
104
123
  if (rest[at]?.includes('husky.sh')) {
105
124
  at += 1;
106
125
  }
107
- return [...rest.slice(0, at), ...BLOCK, ...rest.slice(at)].join('\n');
126
+ return [...rest.slice(0, at), ...block, ...rest.slice(at)].join('\n');
108
127
  }
109
128
  function withoutBlock(lines) {
110
129
  const start = lines.indexOf(BLOCK_START);
@@ -3,22 +3,29 @@ import { ProjectIdTaken, ProjectNotFound } from '../../domain/project/project-re
3
3
  import { readYaml, writeYamlAtomic } from '../fs/atomic-yaml.js';
4
4
  import { withFileLock } from '../fs/file-lock.js';
5
5
  import { parseProjectSnapshot } from './records.js';
6
+ import { registeredPath } from '../fs/worktree.js';
6
7
  export const PROJECTS_FILE_SCHEMA_VERSION = 1;
7
- /** `projects.yaml`: the global registry of projects and their working copies. */
8
+ /**
9
+ * `projects.yaml`: the global registry of projects and their working copies.
10
+ * Paths are written real (`registeredPath`); reads take them as written, so a
11
+ * hook touches no disk for them. A path written before paths were made real is
12
+ * matched by `findByPath` after a miss, and made real by the next write.
13
+ */
8
14
  export class FileProjectRepository {
9
15
  layout;
10
16
  constructor(layout) {
11
17
  this.layout = layout;
12
18
  }
19
+ /** `path` is a real path (`realPath`). */
13
20
  findByPath(path) {
14
- return this.readAll().find((project) => project.hasPath(path));
21
+ return this.readAll().find((project) => project.hasPath(path)) ?? this.readReal().find((project) => project.hasPath(path));
15
22
  }
16
23
  ids() {
17
24
  return new Set(this.readAll().map((project) => project.id.value));
18
25
  }
19
26
  addIfAbsent(project) {
20
27
  return withFileLock(this.layout.projectsLock, () => {
21
- const all = this.readAll();
28
+ const all = this.readReal();
22
29
  const owner = all.find((existing) => project.paths.some((path) => existing.hasPath(path)));
23
30
  if (owner) {
24
31
  return owner;
@@ -26,7 +33,7 @@ export class FileProjectRepository {
26
33
  if (all.some((existing) => existing.id.equals(project.id))) {
27
34
  throw new ProjectIdTaken(project.id.value);
28
35
  }
29
- this.writeAll([...all, project]);
36
+ this.writeAll([...all, real(project)]);
30
37
  return project;
31
38
  });
32
39
  }
@@ -35,13 +42,13 @@ export class FileProjectRepository {
35
42
  }
36
43
  update(id, change) {
37
44
  return withFileLock(this.layout.projectsLock, () => {
38
- const all = this.readAll();
45
+ const all = this.readReal();
39
46
  const index = all.findIndex((project) => project.id.equals(id));
40
47
  const current = all[index];
41
48
  if (!current) {
42
49
  throw new ProjectNotFound(id.value);
43
50
  }
44
- const changed = change(current);
51
+ const changed = real(change(current));
45
52
  all[index] = changed;
46
53
  this.writeAll(all);
47
54
  return changed;
@@ -63,5 +70,14 @@ export class FileProjectRepository {
63
70
  .filter((snapshot) => snapshot !== undefined)
64
71
  .map((snapshot) => Project.rehydrate(snapshot));
65
72
  }
73
+ /** The registry with every path that exists here made real: one `realpath` per path, for writes and a missed lookup. */
74
+ readReal() {
75
+ return this.readAll().map(real);
76
+ }
77
+ }
78
+ /** The project with its paths made real; two spellings of one copy become one path. */
79
+ function real(project) {
80
+ const snapshot = project.toSnapshot();
81
+ return Project.rehydrate({ ...snapshot, paths: [...new Set(snapshot.paths.map(registeredPath))] });
66
82
  }
67
83
  //# sourceMappingURL=file-project-repository.js.map
@@ -1,6 +1,7 @@
1
1
  import { join } from 'node:path';
2
2
  import { COMMANDS, ESTIMETRY_SKILL } from '../content/commands.js';
3
3
  import { withBlock, withoutBlock } from './claude-md.js';
4
+ import { estimetryCommand } from '../../../application/contracts/estimetry-command.js';
4
5
  import { hasOurHooks, isBrokenJson, withHooks, withoutHooks } from './hook-settings.js';
5
6
  import { CLAUDE_CODE_HOOK_EVENTS, SYNCHRONOUS_HOOK_EVENTS } from './hook-events.js';
6
7
  import { ownership, renderSkill } from './skill-file.js';
@@ -47,12 +48,14 @@ export class ClaudeCodeAdapter {
47
48
  warnings: plans.flatMap((plan) => plan.warnings),
48
49
  };
49
50
  }
50
- hooks({ projectRoot, files, shared }) {
51
+ hooks({ projectRoot, files, shared, runner }) {
51
52
  const [target, previous] = shared ? [SHARED_SETTINGS, LOCAL_SETTINGS] : [LOCAL_SETTINGS, SHARED_SETTINGS];
53
+ // Personal settings run this installation by its paths; settings the team commits hold no paths of this machine.
54
+ const command = (event) => estimetryCommand(shared ? undefined : runner, `hook claude-code ${event}`);
52
55
  const changes = [
53
56
  {
54
57
  path: join(projectRoot, target),
55
- content: withHooks(files.read(join(projectRoot, target)), this.hookEvents, target, SYNCHRONOUS_HOOK_EVENTS),
58
+ content: withHooks(files.read(join(projectRoot, target)), { events: this.hookEvents, synchronous: SYNCHRONOUS_HOOK_EVENTS, command }, target),
56
59
  },
57
60
  ];
58
61
  const warnings = [];
@@ -1,12 +1,18 @@
1
+ import { isEstimetryCommand } from '../../../application/contracts/estimetry-command.js';
1
2
  import { InstallBlocked } from '../../../application/contracts/install-blocked.js';
2
- /** Our hooks are recognised by this prefix; a hook the user rewrote is theirs. */
3
- export const HOOK_PREFIX = 'estimetry hook claude-code';
3
+ /**
4
+ * Our hooks are recognised by this prefix, or by the command of this installation
5
+ * (`estimetryCommand`) that falls back to it; a hook the user rewrote is theirs.
6
+ */
7
+ const HOOK_ARGS = 'hook claude-code';
8
+ export const HOOK_PREFIX = `estimetry ${HOOK_ARGS}`;
4
9
  export const HOOK_TIMEOUT_SECONDS = 10;
5
10
  /**
6
11
  * Adds one hook per event and drops our earlier ones; every other key, hook and
7
12
  * their order stay. `displayPath` names the file in the error a broken one gives.
8
13
  */
9
- export function withHooks(text, events, displayPath, synchronous = events) {
14
+ export function withHooks(text, set, displayPath) {
15
+ const { events, synchronous } = set;
10
16
  const settings = parse(text, displayPath) ?? {};
11
17
  const hooks = withoutOurHooks(hooksOf(settings, displayPath));
12
18
  for (const event of events) {
@@ -14,7 +20,7 @@ export function withHooks(text, events, displayPath, synchronous = events) {
14
20
  // The agent does not wait for an async hook: only hooks whose context it needs now, or the session end, are synchronous.
15
21
  const handler = {
16
22
  type: 'command',
17
- command: `${HOOK_PREFIX} ${event}`,
23
+ command: set.command(event),
18
24
  timeout: HOOK_TIMEOUT_SECONDS,
19
25
  ...(synchronous.includes(event) ? {} : { async: true }),
20
26
  };
@@ -88,7 +94,10 @@ function isOurs(handler) {
88
94
  return (isObject(handler) &&
89
95
  handler['type'] === 'command' &&
90
96
  typeof handler['command'] === 'string' &&
91
- (handler['command'] === HOOK_PREFIX || handler['command'].startsWith(`${HOOK_PREFIX} `)));
97
+ isOurCommand(handler['command']));
98
+ }
99
+ function isOurCommand(command) {
100
+ return isEstimetryCommand(command, HOOK_ARGS);
92
101
  }
93
102
  function hooksOf(settings, displayPath) {
94
103
  const hooks = settings['hooks'];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "estimetry",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Compares work estimates with actual effort in AI-agent development and reuses that experience in the next estimate",
5
5
  "keywords": [
6
6
  "estimation",
package/README.ru.md DELETED
@@ -1,417 +0,0 @@
1
- # estimetry
2
-
3
- [English](README.md) | **Русский**
4
-
5
- Сравнивает оценки работ с фактическими трудозатратами при разработке с AI-агентами и использует этот опыт в следующей оценке.
6
-
7
- CLI называется `estimetry`, короткий псевдоним — `emt`.
8
-
9
- ## Установка
10
-
11
- Нужны:
12
- - Node.js 22.12 или новее;
13
- - git;
14
- - [Claude Code](https://docs.claude.com/en/docs/claude-code) — пока единственный AI-инструмент, который поддерживает estimetry.
15
-
16
- ```sh
17
- npm install -g estimetry
18
- emt --version
19
- ```
20
-
21
- Ставьте глобально: хуки Claude Code вызывают `estimetry` из `PATH`.
22
-
23
- Для обновления: `npm install -g estimetry@latest`, затем один раз `emt upgrade` (см. [После обновления estimetry](#после-обновления-estimetry)).
24
-
25
- > estimetry в версии 0.x: команды и формат хранения ещё могут меняться между минорными версиями. Что изменилось и что сделать после обновления, написано в [CHANGELOG.md](CHANGELOG.md).
26
-
27
- ## Начало работы
28
-
29
- 1. В корне репозитория выполните `estimetry init`. Команда ставит хуки Claude Code и скиллы `/emt-…`.
30
- 2. Начните там новую сессию Claude Code и спросите, сколько займёт задача, или выполните `/emt-estimate`. Агент создаёт задачу, оценивает её по частям и сохраняет оценку, когда вы её одобрите.
31
- 3. Выполните `/emt-start` и работайте как обычно. Хуки измеряют время агентов и ваше собственное время; его показывает `emt status`.
32
- 4. Когда работа сделана, выполните `/emt-close`. Агент закрывает задачу и спрашивает, почему факт отличается от оценки.
33
-
34
- Каждая закрытая задача делает следующую оценку обоснованнее: `emt similar` находит похожие прошлые задачи, а `emt calibrate` даёт ваш личный коэффициент, когда таких задач накопится достаточно.
35
-
36
- ## Справка
37
-
38
- `emt --help` перечисляет все команды, включая вложенные (`task new`, `estimate save`, `parallel on`), по этапам: настройка, задачи и оценки, измерение, закрытие. У каждой — её опции, обязательные отмечены. В конце — примеры обычного порядка работы.
39
-
40
- `emt <command> --help` или `emt help <command>` показывает одну команду целиком, например `emt help task new`.
41
-
42
- Тот же список со всеми флагами — в [справочнике команд](#справочник-команд) в конце README.
43
-
44
- ## Настройка проекта: `estimetry init`
45
-
46
- Выполните в корне репозитория:
47
-
48
- ```sh
49
- estimetry init
50
- ```
51
-
52
- В терминале команда задаёт несколько вопросов:
53
- - какие AI-инструменты настроить (пока Claude Code);
54
- - процесс разработки (OpenSpec или никакого);
55
- - как делиться данными с командой;
56
- - ставить ли git-хук.
57
-
58
- `estimetry init --no-interactive` берёт флаги и значения по умолчанию вместо вопросов; так же ведёт себя любой запуск в CI или без терминала. Повторный запуск безопасен: он обновляет то, что ставил, и не трогает остальное.
59
-
60
- ### Что ставится
61
-
62
- | Что | Куда | Кто получает |
63
- |---|---|---|
64
- | Хуки на 12 событий Claude Code, каждый вызывает `estimetry hook claude-code <event>` | `.claude/settings.local.json` | вы |
65
- | Скиллы `estimetry`, `emt-estimate`, `emt-start`, `emt-extra`, `emt-parallel`, `emt-manual`, `emt-close`, `emt-retro` (они же команды `/emt-…`) | `~/.claude/skills/` (или `$CLAUDE_CONFIG_DIR/skills/`) | вы, во всех проектах |
66
- | Id проекта и процесс разработки | `.estimetry/config.yaml` | команда; закоммитьте его, чтобы клоны репозитория были одним проектом |
67
-
68
- С `--shared-hooks` хуки идут в `.claude/settings.json`, а скиллы — в `.claude/skills/` проекта. В `CLAUDE.md` между `<!-- estimetry:start -->` и `<!-- estimetry:end -->` добавляется напоминание запускать `/emt-estimate`, прежде чем называть срок. Эти файлы проект коммитит, поэтому их получает вся команда.
69
-
70
- С `--track-commits` в каталог хуков репозитория ставится хук `post-commit`. Учитываются `core.hooksPath`, ворктри и husky (`.husky/post-commit`). Существующий хук сохраняет своё содержимое: estimetry добавляет свой блок между `# >>> estimetry >>>` и `# <<< estimetry <<<`. Хук запускает estimetry в фоне, поэтому коммиты его не ждут. Коллеги без estimetry ничего не замечают.
71
-
72
- Данные задач никогда не попадают в репозиторий. Задачи, оценки и журнал событий лежат в `~/.local/share/estimetry/` или в `ESTIMETRY_HOME`, если он задан.
73
-
74
- ### Флаги
75
-
76
- | Флаг | Значение |
77
- |---|---|
78
- | `--tools <ids>` | AI-инструменты через запятую: `claude-code` (псевдоним `claude`) |
79
- | `--flow <id>` | `openspec` или `none`; по умолчанию определяется сам (`openspec/` в корне — значит OpenSpec) |
80
- | `--share <mode>` | `none`, `calibration` или `cards`; пока только сохраняется |
81
- | `--track-commits` / `--no-track-commits` | поставить или снять git-хук |
82
- | `--shared-hooks` / `--no-shared-hooks` | поставить для всей команды или только для себя |
83
- | `--force` | перезаписать сгенерированные скиллы, которые вы правили |
84
- | `--no-interactive` | не задавать вопросов |
85
- | `--json` | вывести отчёт в JSON |
86
-
87
- Повторный запуск сохраняет то, что уже стоит: если git-хук или общая установка есть, `estimetry init` без флагов их оставляет. Чтобы снять, выполните `estimetry init --no-track-commits` или `estimetry init --no-shared-hooks`.
88
-
89
- ### Что полезно знать
90
-
91
- - **Ваши правки сгенерированных скиллов сохраняются.** В каждом сгенерированном скилле есть `metadata.generatedBy` и хеш содержимого. Если вы его правили, init оставляет вашу версию и показывает её как `skipped`; `--force` перезаписывает. Файл с тем же именем, созданный не estimetry, не трогается никогда.
92
- - **Изменённый хук — ваш.** estimetry узнаёт свои хуки по началу команды `estimetry hook claude-code`. Если вы её изменили, init считает хук вашим и добавляет свой рядом.
93
- - **`settings.local.json` может не игнорироваться git.** Claude Code добавляет `**/.claude/settings.local.json` в ваши глобальные исключения git, только когда сам пишет этот файл. Если файл создал init и git его не игнорирует, init предлагает добавить ту же строку. С `--no-interactive` только предупреждает.
94
- - **Хукам нужен `estimetry` в `PATH`.** При запуске через `npx` хуки его не найдут, и init об этом предупреждает.
95
-
96
- ## Оценка задачи
97
-
98
- Спросите агента, сколько займёт задача, или выполните `/emt-estimate`. Прежде чем назвать хоть одну цифру, агент:
99
- 1. согласует с вами тип задачи и технологии, которые она действительно затрагивает;
100
- 2. набрасывает части плана и запускает `emt similar` — похожие закрытые задачи с их оценками, фактом, доп. работами и уроками;
101
- 3. запускает `emt calibrate` — ваши коэффициенты и тот, который оценка может применить;
102
- 4. показывает оценку по частям и на чём она основана, а сохраняет её через `emt estimate save` только после вашего одобрения.
103
-
104
- ```sh
105
- emt similar --type feature --stack typescript,node --hours 8
106
- emt calibrate --type feature --stack typescript,node
107
- emt calibrate --type feature --revise # для переоценки задачи в работе
108
- ```
109
-
110
- - **Похожесть** складывается из общих технологий (половина веса), типа первой оценки и, с `--hours`, размера. Для каждой задачи видно, из чего сложилась её похожесть. Без `--stack` учитывается стек проекта.
111
- - **Коэффициент** — медиана отношения факта к оценке в первом срезе, где хватает закрытых задач: по типу, затем по технологии. Общий срез смешивает любую работу и показывается только для справки. Если задач меньше `calibration.minTasks` (по умолчанию 5), оценка — **без калибровки**, и агент об этом говорит.
112
- - **Калиброванная оценка** умножает все три числа каждой части на коэффициент и записывает его (`calibrated: true`, `calibration.coefficient`), чтобы следующий коэффициент считался от оценки до умножения. Запас добавляется только в пессимистичные часы: доп. работы, которые вы поглотили, уже есть в коэффициенте.
113
- - **Ничего не записывают** `emt similar` и `emt calibrate`; `calibration.json` обновляют закрытия и `emt rebuild`.
114
- - **Сменился email.** Калибровка личная, по `author.id` в `config.yaml`. Перечислите прежние id, чтобы их карточки остались вашими:
115
-
116
- ```yaml
117
- author:
118
- id: new@example.com
119
- aliases: [old@example.com]
120
- ```
121
-
122
- ## Измерение задачи
123
-
124
- Когда задача начата (`emt start`), хуки Claude Code пишут её сессии в журнал задачи. `emt status` показывает измеренный на сейчас факт: время агентов, ваше время и насколько точны цифры.
125
-
126
- ### Что учитывается
127
-
128
- - **Время агента** — пока главный агент работает над ходом или работает сабагент, включая долгие инструменты.
129
- - **Ваше время** — пока сессия за вами: вы смотрите результат и пишете следующий промпт. Паузы дольше порога простоя не учитываются.
130
- - **Не учитывается** — команды, оставленные работать в фоне после того, как агент закончил ход (`run_in_background` или сабагент, ждущий свою фоновую задачу). Тогда работает машина, а не агент.
131
-
132
- ### Насколько точен факт
133
-
134
- Некоторые промежутки решает правило, а не событие: 20 минут тишины после ответа агента могут быть и вашим разбором результата, и вашим отсутствием. `emt status` показывает диапазон, в котором лежит факт:
135
-
136
- ```
137
- fact 29h 43m of 58h 30m (51%)
138
- uncertainty 27h 53m – 34h 0m (21% of the fact, above the 5% target)
139
- ```
140
-
141
- - **Нижняя граница** не считает сомнительные промежутки, которые правила засчитали: тишину от половины порога до порога, инструменты дольше двух порогов, начало хода, к которому сессия присоединилась посередине.
142
- - **Верхняя граница** добавляет сомнительные промежутки, которые правила не засчитали: паузы до двух порогов, хвост хода или сабагента, не сообщившего о конце, долгие ожидания, закончившиеся без длительности.
143
-
144
- Оценки и калибровка сравниваются с самим фактом; диапазон лишь говорит, насколько он может сдвинуться. Обычно большую часть диапазона дают ваши паузы после законченного хода: ничто не фиксирует, работали ли вы тогда, поэтому они остаются открытыми.
145
-
146
- ### Логи сессий, токены и стоимость
147
-
148
- Claude Code ведёт лог каждой сессии. estimetry читает его, когда сессия заканчивается (а также на `/clear` и `/resume`) и перед закрытием задачи, и оставляет в журнале задачи только то, что нужно:
149
- - когда начинались и заканчивались ходы агента и сабагенты: ход, конец которого хуки пропустили, заканчивается там, где его заканчивает лог, а сессия, присоединившаяся посередине, начинает ход там, где его начинает лог;
150
- - токены по моделям с их временем и общую стоимость сессии.
151
-
152
- Тексты лога — промпты, ответы, ввод и вывод инструментов, описания и типы сабагентов — в журнал не читаются никогда.
153
-
154
- `emt status` и карточка показывают токены задачи и её стоимость, а также у скольких её сессий был лог. Если задаче принадлежит только часть токенов сессии (сессия началась до `emt start` или служила и другой задаче), задача получает соответствующую долю стоимости сессии: каждый вид токенов взвешивается по его цене относительно входного токена, а стоимость помечается как приблизительная.
155
-
156
- Стоимость — это итог, который сам Claude Code записывает в лог сессии, по ценам API. На подписке это не то, что вы платите: читайте её как меру для сравнения задач между собой, а не как расходы.
157
-
158
- Сессии, которые закончились до установки этой версии, читаются при закрытии задачи. Claude Code удаляет логи через 30 дней; для более долгих задач увеличьте `cleanupPeriodDays` в его настройках.
159
-
160
- ### Какой задаче служит сессия
161
-
162
- - **Одна задача в работе** — сессия привязывается к ней сама.
163
- - **Несколько задач в работе** — агент получает id сессии в её начале и спрашивает вас, какая это задача. Затем он выполняет `emt attach <task> --session <id>`. Для первой задачи сессии её работа с начала задачи тоже учитывается, как при привязке, которую сессия делает сама. Той же командой работающую сессию переключают на другую задачу; время до и после переключения уходит в нужную задачу.
164
- - **Нет задач в работе** — время сессии хранится в журнале проекта и не идёт ни в какую задачу. Начните задачу, хотя бы `emt start --at "<когда начали>"`, и работа сессии с этого момента перейдёт в неё.
165
-
166
- ### Перезапуски и параллельные сессии
167
-
168
- Хуки находят проект по каталогу, в котором работает Claude Code, а не по id сессии.
169
-
170
- - **После перезапуска** (VS Code, сбой, перезагрузка) у новой сессии новый id, и она привязывается заново по правилам выше: при одной задаче в работе время продолжает идти в неё без всяких действий. При нескольких ответьте агенту, какая это задача: после привязки работа новой сессии с начала задачи тоже учитывается.
171
- - **Ход, оборванный сбоем,** не получает конца. Его хвост закрывается по порогу простоя и показывается как неопределённость (`± …` в `emt status`). Время между сбоем и перезапуском не учитывается.
172
- - **Две сессии на одной задаче** обе пишут в её журнал. Пересекающееся время агентов считается один раз, поэтому факт короче суммы работы двух агентов. Включите параллельный режим (`emt parallel on --agents 2`): тогда калибровка использует последовательный эквивалент — сумму работы агентов.
173
- - **Две сессии на двух задачах** после `emt attach` служат каждая своей задаче. Коммит уходит в задачу сессии, активной последней: git-хук не знает, какая сессия его сделала. Если обе коммитят в один момент, коммит может попасть в другую задачу. Это влияет только на объём кода в карточке, не на время.
174
-
175
- ### Код в другой рабочей копии или репозитории
176
-
177
- Агент может работать в одном репозитории, где лежат артефакты OpenSpec, а писать код в другом месте.
178
-
179
- - **Время и прогресс плана** от этого не страдают: время идёт в задачу сессии, а план читается там, где лежат артефакты.
180
- - **Git-ворктри** зарегистрированной рабочей копии принадлежит её проекту — с закоммиченным `.estimetry/config.yaml` или без него: задача, начатая в ворктри, — задача этого проекта, и сессия, открытая в основной рабочей копии, её видит. Отдельный клон без конфига — отдельный проект.
181
- - **План задачи, которую ведут в ворктри,** читается в рабочей копии, где лежат её чейнджи (группы её оценки и всех переоценок), — а если в копиях они разные, то там, где их меняли последними. Так даже тогда, когда сессия работает в основной рабочей копии: процент выполнения, завершение чейнджа, отметки и объём кода при закрытии. Ворктри без своего `.estimetry/config.yaml` берёт флоу из других рабочих копий проекта.
182
- - **Коммиты в ворктри** записываются в задачу: у ворктри общие git-хуки репозитория (при `init --track-commits`). Объём кода при закрытии меряется в рабочей копии задачи, где бы ни запускался `emt close`: коммиты, достижимые из её `HEAD`, и её незакоммиченные изменения. Незакоммиченные изменения других ворктри не видны.
183
- - **Другой репозиторий** относится к задаче, только если вы его добавите: выполните в нём `estimetry init --track-commits` и `emt attach <task>`. Тогда его коммиты записываются, а его код меряется при закрытии.
184
-
185
- Объём кода — только самопроверка: он никогда не меняет факт и коэффициенты.
186
-
187
- ### Отметки
188
-
189
- Каждые 20 минут работы отметка записывает состояние плана (чекбоксы `tasks.md` OpenSpec), `HEAD` и незакоммиченные изменения — всё из рабочей копии задачи. Отметки пишут только фоновые хуки. Интервал задаётся в `~/.local/share/estimetry/config.yaml`:
190
-
191
- ```yaml
192
- measurement:
193
- checkpointMinutes: 20 # от 10 до 30
194
- ```
195
-
196
- После отметки агенту вместе с вашим следующим промптом напоминают записать работу вне плана через `/emt-extra`.
197
-
198
- ### Прогресс плана
199
-
200
- `emt status` показывает и то, какая часть плана выполнена:
201
-
202
- ```
203
- plan 51% done by changes (58h 30m of 58h 30m in groups)
204
- not started close-retro-cards, estimate-mode
205
- changes 4 done, last hooks-and-flows 2026-11-01 (approx.)
206
- ```
207
-
208
- - **Части связываются через `group`.** Часть оценки, у которой `group` — имя чейнджа OpenSpec, связана с этим чейнджем в любом проекте задачи. Архивный чейндж считается выполненным на 100%, активный — по отмеченным чекбоксам, ещё не созданный — на 0%. Процент взвешивается по наиболее вероятным часам связанных частей.
209
- - **План задачи** — её активные чейнджи плюс архивные с датой не раньше дня перед стартом задачи. Более старый архив с тем же именем относится к прежней работе.
210
- - **Группы без чейнджа** показываются как `not started`, как `possible typo`, если есть чейндж с похожим именем, или как `archived before start`.
211
- - **Без групп** (или без оценки) план считается по чекбоксам всех его чейнджей и помечается как не связанный с оценкой.
212
- - **Не отслеживается**, если флоу проекта — `none` или неизвестный, у проекта нет `.estimetry/config.yaml` или его нет на этой машине. Для задачи из нескольких проектов процент считается по проектам, которые estimetry может прочитать, а остальные перечислены под `not tracked`: их группы могут выглядеть не начатыми, хотя они сделаны.
213
- - **Несколько рабочих копий** проекта (ворктри, клоны): план читается в рабочей копии задачи — той, где лежат её чейнджи (см. [Код в другой рабочей копии или репозитории](#код-в-другой-рабочей-копии-или-репозитории)); если такой нет — в той, где вы работаете.
214
-
215
- Чейндж завершён, когда его каталог появляется в архиве, как бы он туда ни попал: `openspec archive`, скилл, который его перенёс, или вы в терминале. Следующий вызов хука сессии, привязанной к задаче, записывает это с моментом переноса. Чейнджи, которые уже лежали в архиве, когда estimetry впервые смотрит на задачу, записываются только с датой и помечаются `(approx.)`. Чейндж, который вернули из архива, больше не считается завершённым. Процент показывается и в начале сессии (`plan 51% done`), и его записывает `emt parallel on`.
216
-
217
- ## Переоценка
218
-
219
- Когда задача начата, её оценка — это план, с которым сравнивается факт, и `emt estimate save` не даст её изменить. Если план оказался неверным, а объём и срок остаются прежними — ошибка в проекте решения, упущение анализа, — переоцените её:
220
-
221
- ```sh
222
- emt estimate revise plan2.yaml --reason "design was wrong" --category missed-analysis --spent exclude --lost-from "2026-11-02 10:00"
223
- ```
224
-
225
- `emt task show <task>` показывает части действующей оценки (с `--json` — в формате файла оценки): начните новую оценку с них.
226
-
227
- - `--spent include` — сделанная работа засчитывается в новую оценку.
228
- - `--spent exclude` — работа с `--lost-from` (по умолчанию со старта или прошлой переоценки) до переоценки (`--at`, по умолчанию сейчас) выброшена. Она не удаляется: `emt status` показывает её отдельно как потерянную и сравнивает с новой оценкой только учтённый факт.
229
- - `--covers <id>` — доп. работа, уже записанная за ту же потерю, чтобы потеря не посчиталась дважды. Только с `--spent exclude`, и одну доп. работу может покрыть только одна переоценка. Команда перечисляет доп. работы, записанные в окне, с их id, чтобы их можно было назвать.
230
- - Архивные чейнджи выброшенной работы уходят из плана: они не дают ни процента, ни завершения, ни предложения закрыть. Чейндж, заархивированный позже заново, считается как обычно.
231
-
232
- Первая оценка остаётся в журнале и в карточке: калибровка сравнивает с ней весь факт, поэтому поздняя переоценка не может сделать оценку правильной задним числом. Переоценённую оценку тоже меряют — против учтённого факта (см. [Калибровка](#калибровка)). Если заказчик согласовал больший объём или срок, используйте `emt renegotiate`.
233
-
234
- ## Закрытие задачи
235
-
236
- Задача закрывается только с вашего согласия. Когда чейндж задачи уходит в архив, агент получает заметку с вашим следующим промптом и спрашивает, был ли он последним и закрывать ли задачу. Сам он задачу никогда не закрывает.
237
-
238
- ```sh
239
- emt close # показывает факт и план, затем спрашивает
240
- emt close --yes # без терминала (агент): только после вашего согласия
241
- emt close --at "2026-11-02 18:00" # работа закончилась раньше
242
- emt close --abandoned # задачу бросили; в калибровку она не идёт
243
- ```
244
-
245
- Закрытие записывает объём кода и план, завершает параллельный режим и отпускает сессии задачи: сессия, закрывшая задачу, не переходит на другую задачу сама, пока не начнётся заново или пока вы не выполните `emt attach <task> --session <id>`.
246
-
247
- Затем проведите ретро с агентом (`/emt-retro`): почему факт отличается от оценки и один урок на будущее.
248
-
249
- ```sh
250
- emt retro --reason "manual-testing: two devices instead of one" --reason "API docs were outdated" --lesson "plan manual testing per platform"
251
- ```
252
-
253
- Причина, которая начинается с id части оценки (`manual-testing:`), относится к этой части. Повторный `emt retro` заменяет ретро.
254
-
255
- - **С заказчиком согласовали больше работы.** `emt renegotiate "Payments v2" --description "refunds added"` закрывает задачу как есть и создаёт новую на остаток, связанную с ней. Оцените и начните новую задачу как обычно.
256
- - **Закрыли по ошибке.** `emt reopen T-3` снова открывает задачу; её карточка пропадает до следующего закрытия.
257
- - **Ручное время части.** `emt manual 40m "testing on device" --part manual-testing` засчитывает время в эту часть оценки.
258
- - **Закрытые задачи** перечисляет `emt task list --closed`; `emt task show T-3` показывает карточку.
259
-
260
- ### Карточка
261
-
262
- Каждая закрытая задача получает карточку в `~/.local/share/estimetry/cards/<task>.yaml`, около 50 строк. В ней:
263
- - оценка и факт, в том числе по частям оценки;
264
- - доп. работы и параллельный режим;
265
- - объём кода — строки рабочего кода, тестов, конфигов и документации;
266
- - ретро.
267
-
268
- Время делится между частями по чекбоксам, которые их чейнджи закрыли между отметками. Время, которое не может забрать ни одна часть, показывается как `unattributed`.
269
-
270
- У переоценённой задачи сохраняются обе оценки: `estimate` и `parts` — первая оценка, `currentEstimate` и `currentParts` — действующая на момент закрытия. В карточке перечислены и все переоценки с работой, потерянной в их окне, и тем, сколько было учтено на момент каждой, а учтённый факт стоит рядом с полным. Время делится между частями текущей оценки с момента последней переоценки; то, что было учтено до неё, показывается как `before revision`. Доп. работы, названные в `--covers`, перечислены отдельно — как покрытые переоценкой.
271
-
272
- Объём кода считает записанные коммиты задачи, ещё достижимые из `HEAD`, плюс незакоммиченное. Без записанных коммитов он считает ваши коммиты со старта задачи. Сгенерированные файлы (lock-файлы, `*.g.dart`, `dist/` и подобные) не учитываются. Строки — только самопроверка: они никогда не меняют факт и коэффициенты.
273
-
274
- Названия, описания и ретро лежат в отдельном разделе карточки `text`, отдельно от цифр.
275
-
276
- ### Калибровка
277
-
278
- `calibration.json` хранит ваши коэффициенты, посчитанные по вашим карточкам:
279
- - отношение факта к оценке — общее, по типу задачи и по технологии (медиана, среднее, число задач);
280
- - доля доп. работ по категориям и сколько объёма добавили пересогласования;
281
- - насколько точно был спрогнозирован объём кода;
282
- - какие виды частей выходят за оценку.
283
-
284
- Коэффициент, основанный меньше чем на 5 задачах, показывается, но не применяется. Минимум задаётся в `config.yaml`:
285
-
286
- ```yaml
287
- calibration:
288
- minTasks: 5
289
- ```
290
-
291
- Задачи в параллельном режиме учитываются с последовательным эквивалентом. Брошенные задачи и задачи только с ручным временем не учитываются.
292
-
293
- Переоценённые задачи дают две точности:
294
- - главный коэффициент сравнивает весь факт с **первой** оценкой, по типу этой оценки: это то число, которое получил менеджер;
295
- - `revised` сравнивает учтённый факт с **текущей** оценкой: насколько хороша была оценка, сделанная при переоценке, и как далеко в работе обычно случаются переоценки;
296
- - `revisions` показывает по типу задачи, категории и `--spent`, насколько переоценки увеличивают оценку и сколько работы выбрасывают.
297
-
298
- Части переоценённой задачи учитываются, только если до переоценки ушло не больше 5% её учтённого факта. Задачи с `--spent exclude` не участвуют в объёме кода и строках в час: откаченные строки ничего не говорят о размере задачи.
299
-
300
- `emt rebuild` пересобирает снимки задач, карточки и `calibration.json` из журналов — например, после обновления, изменившего формулу.
301
-
302
- ### Что никогда не сохраняется
303
-
304
- Журнал хранит, когда что-то происходило, а не что было сказано или сделано: никаких текстов промптов, ввода и вывода инструментов, команд, сообщений коммитов. Коммиты записываются как хеш, родители, `patch-id` и строки по файлам. Из логов сессий сохраняются время, число токенов по моделям и стоимость; лог, который не удалось прочитать, оставляет только код в `errors.log`.
305
-
306
- ### После обновления estimetry
307
-
308
- Выполните один раз `emt upgrade` из любого каталога. Команда заново устанавливает estimetry во все рабочие копии всех зарегистрированных проектов на этой машине, включая ворктри. Каждая копия сохраняет свои выборы: инструменты, флоу, личную или общую установку, хук коммитов. Команда показывает, что изменится, и спрашивает подтверждение; без терминала нужен `--yes`. Копия, где estimetry не устанавливали, пропускается, как и копия, которой нет на этой машине. При общей установке план предупреждает, что меняются файлы, которые проект коммитит. Чтобы обновить только один проект, выполните `emt init` внутри него.
309
-
310
- До этого хуки продолжают работать: они вызывают новый `estimetry` из `PATH`. Старым остаётся только то, что записал `init`: настройки хуков в проектах, скиллы и, при общей установке, напоминание в `CLAUDE.md`. В начале сессии в проекте, установленном старой версией, агент получает подсказку предложить `emt upgrade`; сам он её не запускает.
311
-
312
- Обновляйте все установленные копии estimetry сразу. Карточки, записанные старой версией, пересобираются из журналов при следующем закрытии, `emt task show` или `emt rebuild`. Карточка новее версии не даёт старой estimetry перезаписать `calibration.json` и показывается вместо этого; версии до этой проверки пропускают такие карточки молча, поэтому не закрывайте ими задачи.
313
-
314
- ## Справочник команд
315
-
316
- Все команды и флаги по этапам, как их перечисляет `emt --help`. `estimetry` и `emt` — одна и та же команда.
317
-
318
- <!-- commands:start: generated from the CLI by `npm run docs:commands` -->
319
-
320
- ### Настройка
321
-
322
- - **`emt init`** — настроить estimetry в этом проекте: хуки, скиллы и команды AI-инструмента, конфиг проекта
323
- - `--tools <ids>` — AI-инструменты через запятую (claude-code)
324
- - `--flow <id>` — процесс разработки: openspec или none (по умолчанию определяется сам)
325
- - `--share <mode>` — чем делиться с командой: none, calibration, cards
326
- - `--track-commits` — установить git-хук post-commit
327
- - `--no-track-commits` — удалить git-хук post-commit
328
- - `--shared-hooks` — установить для всей команды, в файлы, которые проект коммитит
329
- - `--no-shared-hooks` — установить только для себя (по умолчанию)
330
- - `--force` — перезаписать сгенерированные скиллы, которые вы правили
331
- - `--no-interactive` — не спрашивать; брать флаги и значения по умолчанию
332
- - **`emt upgrade`** — после обновления estimetry: заново установить его во все проекты на этой машине, каждый со своими выборами
333
- - `--yes` — пользователь уже согласился (нужно без терминала)
334
- - **`emt rebuild [task]`** — пересобрать снимки задач, карточки и calibration.json из журналов
335
-
336
- ### Задачи и оценки
337
-
338
- - **`emt task new <title>`** — создать задачу в текущем проекте
339
- - `--type <type>` — тип задачи: feature, integration, bugfix, refactor, infra, migration, research
340
- - `--ticket <key>` — ключ тикета во внешнем трекере
341
- - **`emt task list`** — список задач текущего проекта
342
- - `--all` — задачи всех проектов
343
- - `--closed` — вместе с закрытыми
344
- - **`emt task show <task>`** — показать задачу
345
- - **`emt similar`** — найти закрытые задачи, похожие на новую: их оценки, факт, доп. работы и уроки
346
- - `--type <type>` — тип новой задачи
347
- - `--stack <labels>` — технологии, которые задача затрагивает, через запятую; по умолчанию стек проекта
348
- - `--hours <hours>` — предварительные наиболее вероятные часы новой задачи, до калибровки
349
- - `--limit <n>` — сколько задач показать (по умолчанию: "5")
350
- - **`emt calibrate`** — показать ваши коэффициенты для типа и стека и тот, который можно применить к оценке
351
- - `--type <type>` — тип оцениваемой задачи
352
- - `--stack <labels>` — технологии, которые задача затрагивает, через запятую; по умолчанию стек проекта
353
- - `--revise` — для переоценки задачи в работе: коэффициент оценок, сделанных во время работы
354
- - **`emt estimate save <file>`** — сделать файл оценки планом задачи (можно, пока работа не началась)
355
- - `--task <id>` — id задачи; по умолчанию единственная новая или оценённая задача проекта
356
- - **`emt estimate revise [file]`** — переоценить план задачи в работе: старая оценка остаётся, новая сравнивается с учтённым фактом
357
- - `--reason <text>` — почему изменился план: короткая формулировка, согласованная с пользователем
358
- - `--category <category>` — new-requirement, missed-analysis, rework или environment
359
- - `--spent <policy>` — include: сделанная работа учитывается; exclude: работа в окне потерь выброшена
360
- - `--lost-from <time>` — с exclude: когда работа пошла не туда (ISO 8601 или "YYYY-MM-DD HH:MM")
361
- - `--covers <id>` — id доп. работы, которая описывает ту же потерю; повторяется для нескольких
362
- - `--at <time>` — с какого момента действует новая оценка; по умолчанию сейчас
363
- - `--task <id>` — id задачи; по умолчанию единственная задача в работе в этом проекте
364
- - `--repair` — записать недостающий снимок плана последней переоценки
365
-
366
- ### Измерение
367
-
368
- - **`emt start [task]`** — начать работу над задачей; с этого момента её трудозатраты записываются
369
- - `--at <time>` — задним числом (ISO 8601 или "YYYY-MM-DD HH:MM"), для работы, начатой раньше
370
- - **`emt attach <task>`** — подключить задачу к текущему проекту (для задач в нескольких репозиториях)
371
- - `--session <id>` — ещё и привязать эту сессию AI-инструмента к задаче (когда в работе несколько задач)
372
- - **`emt manual <duration> <description>`** — записать время, которого хуки не видели: вашу работу вне сессий агента или работу агента с --agent
373
- - `--at <time>` — когда работа закончилась (ISO 8601 или "YYYY-MM-DD HH:MM"); сливается с измеренным временем
374
- - `--agent` — время агента, например работа до установки estimetry
375
- - `--task <id>` — id задачи; по умолчанию единственная задача в работе в этом проекте
376
- - `--part <id>` — id части оценки, к которой относится время, например manual-testing
377
- - **`emt extra <description>`** — записать работу вне оценённого плана
378
- - `--category <category>` — одна из: new-requirement, missed-analysis, rework, environment (обязательно)
379
- - `--time <duration>` — ваша прикидка, сколько это стоило; факт не меняет
380
- - `--lines <n>` — сколько строк кода это заняло
381
- - `--change <name>` — чейндж, к которому это относится
382
- - `--task <id>` — id задачи; по умолчанию единственная задача в работе в этом проекте
383
- - **`emt parallel on`** — включить параллельный режим; записывает, сколько бюджета потрачено
384
- - `--reason <text>` — почему работа идёт параллельно
385
- - `--agents <n>` — число агентов
386
- - `--parts <ids>` — id частей оценки, которые делаются параллельно, через запятую
387
- - `--task <id>` — id задачи; по умолчанию единственная задача в работе в этом проекте
388
- - **`emt parallel off`** — выключить параллельный режим
389
- - `--task <id>` — id задачи; по умолчанию единственная задача в работе в этом проекте
390
- - **`emt status [task]`** — показать факт задачи на сейчас: агенты, вы, неопределённость и оценка
391
- - `--json` — вывести JSON (длительности в минутах)
392
-
393
- ### Закрытие
394
-
395
- - **`emt close [task]`** — закрыть задачу после согласия пользователя; затем выполнить `emt retro`
396
- - `--at <time>` — когда работа закончилась (ISO 8601 или "YYYY-MM-DD HH:MM"); по умолчанию сейчас
397
- - `--abandoned` — задачу бросили: в калибровке она не используется
398
- - `--yes` — пользователь уже согласился её закрыть (нужно без терминала)
399
- - **`emt reopen <task>`** — открыть задачу, закрытую по ошибке
400
- - **`emt retro [task]`** — записать, почему факт отличается от оценки, и один урок
401
- - `--reason <text>` — причина, можно в виде "<part id>: <text>"; повторяется для нескольких (обязательно)
402
- - `--lesson <text>` — один урок для следующей оценки (обязательно)
403
- - **`emt renegotiate <title>`** — заказчик согласился на дополнительную работу: закрыть задачу как есть и начать новую на остаток
404
- - `--task <id>` — задача, по которой договорились заново; по умолчанию единственная задача в работе в этом проекте
405
- - `--description <text>` — что изменилось; по умолчанию название
406
- - `--category <category>` — категория доп. работы, по умолчанию new-requirement
407
- - `--type <type>` — тип новой задачи; по умолчанию тип исходной
408
- - `--at <time>` — когда закончилась исходная работа; по умолчанию сейчас
409
- - `--yes` — пользователь уже согласился (нужно без терминала)
410
-
411
- ### Общие опции
412
-
413
- - `-v, --version` — вывести номер версии
414
- - `-h, --help` — показать справку по команде
415
- - `--json` — вывести JSON; есть у большинства команд
416
-
417
- <!-- commands:end -->
@@ -1,12 +0,0 @@
1
- export const EMPTY_PLAN = { changes: [], skipped: [], warnings: [] };
2
- export function mergePlans(plans) {
3
- return {
4
- changes: plans.flatMap((plan) => plan.changes),
5
- skipped: plans.flatMap((plan) => plan.skipped),
6
- warnings: plans.flatMap((plan) => plan.warnings),
7
- };
8
- }
9
- export function isRemoval(change) {
10
- return 'remove' in change;
11
- }
12
- //# sourceMappingURL=file-change.js.map
@@ -1,49 +0,0 @@
1
- import { SessionId } from '../../domain/measurement/session-id.js';
2
- import { InvalidValue } from '../../domain/shared/domain-error.js';
3
- import { journalEntry } from './journal-entry.js';
4
- import { CORE_SOURCE } from './session-task.js';
5
- /**
6
- * `emt attach <task> --session <id>`: the session serves `task` from now on.
7
- * The previous task gets the end of the window and the new one its start, so
8
- * a switch in the middle of a turn neither doubles nor loses time.
9
- */
10
- export class BindSession {
11
- bindings;
12
- tasks;
13
- journal;
14
- ids;
15
- authors;
16
- constructor(bindings, tasks, journal, ids, authors) {
17
- this.bindings = bindings;
18
- this.tasks = tasks;
19
- this.journal = journal;
20
- this.ids = ids;
21
- this.authors = authors;
22
- }
23
- bind(sessionText, task, project, now) {
24
- const session = SessionId.parse(sessionText);
25
- if (this.tasks.summary(task)?.status !== 'in-progress') {
26
- throw new InvalidValue(`${task} is not in progress; start it with \`emt start ${task}\` first`);
27
- }
28
- let previous;
29
- this.bindings.update(session, (current) => {
30
- if (current?.task === task) {
31
- return undefined; // already bound: nothing to switch
32
- }
33
- if (current?.task !== undefined && this.tasks.summary(current.task)?.status === 'in-progress') {
34
- previous = { task: current.task, project: current.project };
35
- }
36
- return { session: session.value, project: project.id, root: project.root, task, since: now.toISOString(), everBound: true };
37
- });
38
- if (previous !== undefined) {
39
- this.mark('session.unbound', session, previous.task, previous.project, now);
40
- }
41
- if (this.bindings.get(session)?.since === now.toISOString()) {
42
- this.mark('session.bound', session, task, project.id, now);
43
- }
44
- }
45
- mark(type, session, task, project, at) {
46
- this.journal.append(journalEntry(type, { source: CORE_SOURCE, session: session.value }, { id: this.ids.next(), at, author: this.authors.current(), project, task }));
47
- }
48
- }
49
- //# sourceMappingURL=bind-session.js.map
@@ -1,15 +0,0 @@
1
- import { ACTIVITY_EVENT_SCHEMA_VERSION } from '../../domain/measurement/activity-events.js';
2
- /** Wraps data into the envelope of the journal; validation happens when the journal appends it. */
3
- export function journalEntry(type, data, meta) {
4
- return {
5
- schemaVersion: ACTIVITY_EVENT_SCHEMA_VERSION,
6
- id: meta.id,
7
- ts: meta.at.toISOString(),
8
- type,
9
- author: meta.author.id,
10
- ...(meta.task === undefined ? {} : { task: meta.task }),
11
- project: meta.project,
12
- data,
13
- };
14
- }
15
- //# sourceMappingURL=journal-entry.js.map
@@ -1,24 +0,0 @@
1
- const SEMVER = /^(\d+)\.(\d+)\.(\d+)/;
2
- /**
3
- * Whether a copy set up by `installed` is older than the running `current`:
4
- * a copy without a recorded version predates the record, so it is. A newer or
5
- * unreadable version is not: upgrading would go backwards or guess.
6
- */
7
- export function installOutdated(installed, current) {
8
- if (installed === undefined) {
9
- return true;
10
- }
11
- const from = SEMVER.exec(installed);
12
- const to = SEMVER.exec(current);
13
- if (from === null || to === null) {
14
- return false;
15
- }
16
- for (let i = 1; i <= 3; i++) {
17
- const delta = Number(to[i]) - Number(from[i]);
18
- if (delta !== 0) {
19
- return delta > 0;
20
- }
21
- }
22
- return false;
23
- }
24
- //# sourceMappingURL=install-outdated.js.map
@@ -1,7 +0,0 @@
1
- import { CORE_SOURCE, journalEntry } from '../shared/journal-entry.js';
2
- /** The plan snapshot of a revision, written after its event (estimate-revision spec). */
3
- export function writePlanRevised(writer, task, revision, where) {
4
- const meta = writer.meta.next();
5
- writer.journal.appendRecord(journalEntry('plan.revised', { source: CORE_SOURCE, revision, projects: writer.snapshots.started(task, task.startedAt ?? meta.at, where) }, { id: meta.id, at: meta.at, author: meta.author, project: task.homeProject.value, task: task.id.toString() }));
6
- }
7
- //# sourceMappingURL=plan-revised.js.map
@@ -1,9 +0,0 @@
1
- /**
2
- * The changes of a task that pick its working copy (plan-progress spec): the
3
- * groups of its current estimate and of the one it started with, so a copy is
4
- * still found by a change a revision dropped.
5
- */
6
- export function changesOf(task) {
7
- return [...new Set([...(task.estimate?.groups ?? []), ...(task.originalEstimate?.groups ?? [])])];
8
- }
9
- //# sourceMappingURL=task-changes.js.map
@@ -1,15 +0,0 @@
1
- import { stackLabels } from './stack-labels.js';
2
- /** What `emt similar` and `emt calibrate` are asked about: a checked task type and labels of a stack. */
3
- export class EstimateQuery {
4
- type;
5
- stack;
6
- constructor(type, stack) {
7
- this.type = type;
8
- this.stack = stack;
9
- }
10
- /** Labels are compared as `stackLabels` gives them. */
11
- static of(query) {
12
- return new EstimateQuery(query.type, stackLabels(query.stack));
13
- }
14
- }
15
- //# sourceMappingURL=estimate-query.js.map