dsh-taskbridge 1.5.0 → 1.5.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/src/version.js CHANGED
@@ -1,99 +1,121 @@
1
- // The version this build actually is, read from its own package manifest.
2
- //
3
- // A literal version in the source is a second copy of a fact that already lives in
4
- // `package.json`, and the two drift: the MCP handshake reported `1.4.2` while a
5
- // pre-release tarball of the same source answered `initialize` with that shipped
6
- // number, so a host could not tell which build it was talking to.
7
- //
8
- // The manifest is the ONE source. It is read from disk on demand and is the fixed
9
- // relative location `<package root>/package.json`, where `<package root>` is the
10
- // directory above this module's own `src/`. That is the only layout this build
11
- // supports: a checkout, an installed tarball and the published `files` allowlist all
12
- // keep `src/`, so no other lookup is attempted. A build that cannot read the manifest
13
- // says so instead of inventing a number.
14
-
15
- import { readFileSync } from 'node:fs';
16
- import { dirname, join, resolve } from 'node:path';
17
- import { fileURLToPath } from 'node:url';
18
-
19
- /** This module's directory (`<package root>/src`). */
20
- const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
21
-
22
- /**
23
- * The package root this module is loaded from: one directory above `src/`.
24
- *
25
- * Derived from the module's own location rather than `process.cwd()`, which a host may
26
- * have set to anything.
27
- */
28
- export const PACKAGE_ROOT = resolve(MODULE_DIR, '..');
29
-
30
- /** Absolute path of the manifest this module reads. The only location it reads. */
31
- export const MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
32
-
33
- /** The package name reported when the manifest cannot supply one. */
34
- const FALLBACK_NAME = 'dsh-taskbridge';
35
-
36
- /** The memoised manifest answer, or null before the first read. */
37
- let cached = null;
38
-
39
- /**
40
- * Read the manifest this build belongs to.
41
- *
42
- * Memoised: the answer cannot change while the process runs, and the handshake may be
43
- * asked for it repeatedly by an MCP host that reconnects.
44
- * @returns {{ ok: true, name: string, version: string, path: string }
45
- * | { ok: false, reason: string, path: string }} the manifest facts, or why not.
46
- */
47
- export function readPackageManifest() {
48
- if (cached !== null) return cached;
49
- cached = loadPackageManifest();
50
- return cached;
51
- }
52
-
53
- /**
54
- * Read and parse the manifest without memoising.
55
- * @returns {{ ok: true, name: string, version: string, path: string }
56
- * | { ok: false, reason: string, path: string }} the manifest facts, or why not.
57
- */
58
- function loadPackageManifest() {
59
- let text;
60
- try {
61
- text = readFileSync(MANIFEST_PATH, 'utf8');
62
- } catch (error) {
63
- return { ok: false, path: MANIFEST_PATH, reason: error?.code === 'ENOENT' ? 'manifest-missing' : 'manifest-unreadable' };
64
- }
65
- let parsed;
66
- try {
67
- parsed = JSON.parse(text);
68
- } catch {
69
- return { ok: false, path: MANIFEST_PATH, reason: 'manifest-invalid' };
70
- }
71
- const version = typeof parsed?.version === 'string' ? parsed.version.trim() : '';
72
- const name = typeof parsed?.name === 'string' ? parsed.name.trim() : '';
73
- if (version === '') return { ok: false, path: MANIFEST_PATH, reason: 'manifest-version-missing' };
74
- return {
75
- ok: true,
76
- name: name === '' ? FALLBACK_NAME : name,
77
- version,
78
- path: MANIFEST_PATH,
79
- };
80
- }
81
-
82
- /**
83
- * The version to report, with an explicit fallback when the manifest cannot be read.
84
- *
85
- * The fallback version is `'0.0.0-unknown'` rather than a plausible-looking release
86
- * number: an MCP host that reads it learns the build could not describe itself, which
87
- * is the true fact, instead of being told a version that belongs to a different build.
88
- * The fallback NAME is this package's own name, so an unreadable manifest still reports
89
- * the right package rather than a historical alias.
90
- * @returns {{ name: string, version: string, source: string }} reported identity.
91
- * `source` is `package.json` when the manifest was read, `fallback` otherwise.
92
- */
93
- export function reportedVersion() {
94
- const manifest = readPackageManifest();
95
- if (manifest.ok) {
96
- return { name: manifest.name, version: manifest.version, source: 'package.json' };
97
- }
98
- return { name: FALLBACK_NAME, version: '0.0.0-unknown', source: 'fallback' };
99
- }
1
+ // The version this build actually is, read from its own package manifest.
2
+ //
3
+ // A literal version in the source is a second copy of a fact that already lives in
4
+ // `package.json`, and the two drift: the MCP handshake reported `1.4.2` while a
5
+ // pre-release tarball of the same source answered `initialize` with that shipped
6
+ // number, so a host could not tell which build it was talking to.
7
+ //
8
+ // The manifest is the ONE source. It is read from disk on demand and is the fixed
9
+ // relative location `<package root>/package.json`, where `<package root>` is the
10
+ // directory above this module's own `src/`. That is the only layout this build
11
+ // supports: a checkout, an installed tarball and the published `files` allowlist all
12
+ // keep `src/`, so no other lookup is attempted. A build that cannot read the manifest
13
+ // says so instead of inventing a number.
14
+
15
+ import { readFileSync } from 'node:fs';
16
+ import { dirname, join, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ /** This module's directory (`<package root>/src`). */
20
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
21
+
22
+ /**
23
+ * The package root this module is loaded from: one directory above `src/`.
24
+ *
25
+ * Derived from the module's own location rather than `process.cwd()`, which a host may
26
+ * have set to anything.
27
+ */
28
+ export const PACKAGE_ROOT = resolve(MODULE_DIR, '..');
29
+
30
+ /** Absolute path of the manifest this module reads. The only location it reads. */
31
+ export const MANIFEST_PATH = join(PACKAGE_ROOT, 'package.json');
32
+
33
+ /** The package name reported when the manifest cannot supply one. */
34
+ const FALLBACK_NAME = 'dsh-taskbridge';
35
+
36
+ /** The memoised manifest answer, or null before the first read. */
37
+ let cached = null;
38
+
39
+ /**
40
+ * Read the manifest this build belongs to.
41
+ *
42
+ * Memoised: a normal process cannot change its own manifest while it runs, and the
43
+ * handshake may be asked for it repeatedly by an MCP host that reconnects.
44
+ *
45
+ * `refresh: true` bypasses (and replaces) that memo. It exists for the ONE case where the
46
+ * manifest DOES change under a live module instance: the host replaces the installed
47
+ * package on disk while this module stays loaded (a DSH hot update), so a stale answer
48
+ * would make the plugin write a Codex integration stamped with the PREVIOUS version — and
49
+ * the next start, reading the real manifest, would then call that fresh file custom.
50
+ * Every other caller keeps the process-lifetime cache.
51
+ * @param {{ refresh?: boolean }} [options] - `refresh: true` re-reads the manifest once.
52
+ * @returns {{ ok: true, name: string, version: string, path: string }
53
+ * | { ok: false, reason: string, path: string }} the manifest facts, or why not.
54
+ */
55
+ export function readPackageManifest({ refresh = false } = {}) {
56
+ if (refresh !== true && cached !== null) return cached;
57
+ cached = loadPackageManifest();
58
+ return cached;
59
+ }
60
+
61
+ /**
62
+ * Forget the memoised manifest, so the NEXT read goes back to disk.
63
+ *
64
+ * Kept as its own function for callers that want to invalidate without reading, while
65
+ * {@link readPackageManifest} with `refresh: true` is the ordinary "re-read now" path.
66
+ * @returns {void}
67
+ */
68
+ export function refreshPackageManifest() {
69
+ cached = null;
70
+ }
71
+
72
+ /**
73
+ * Read and parse the manifest without memoising.
74
+ * @returns {{ ok: true, name: string, version: string, path: string }
75
+ * | { ok: false, reason: string, path: string }} the manifest facts, or why not.
76
+ */
77
+ function loadPackageManifest() {
78
+ let text;
79
+ try {
80
+ text = readFileSync(MANIFEST_PATH, 'utf8');
81
+ } catch (error) {
82
+ return { ok: false, path: MANIFEST_PATH, reason: error?.code === 'ENOENT' ? 'manifest-missing' : 'manifest-unreadable' };
83
+ }
84
+ let parsed;
85
+ try {
86
+ parsed = JSON.parse(text);
87
+ } catch {
88
+ return { ok: false, path: MANIFEST_PATH, reason: 'manifest-invalid' };
89
+ }
90
+ const version = typeof parsed?.version === 'string' ? parsed.version.trim() : '';
91
+ const name = typeof parsed?.name === 'string' ? parsed.name.trim() : '';
92
+ if (version === '') return { ok: false, path: MANIFEST_PATH, reason: 'manifest-version-missing' };
93
+ return {
94
+ ok: true,
95
+ name: name === '' ? FALLBACK_NAME : name,
96
+ version,
97
+ path: MANIFEST_PATH,
98
+ };
99
+ }
100
+
101
+ /**
102
+ * The version to report, with an explicit fallback when the manifest cannot be read.
103
+ *
104
+ * The fallback version is `'0.0.0-unknown'` rather than a plausible-looking release
105
+ * number: an MCP host that reads it learns the build could not describe itself, which
106
+ * is the true fact, instead of being told a version that belongs to a different build.
107
+ * The fallback NAME is this package's own name, so an unreadable manifest still reports
108
+ * the right package rather than a historical alias.
109
+ * @param {{ refresh?: boolean }} [options] - forwarded to {@link readPackageManifest};
110
+ * `refresh: true` is what a plugin activation uses, because a host may have replaced the
111
+ * installed package while this module stayed loaded.
112
+ * @returns {{ name: string, version: string, source: string }} reported identity.
113
+ * `source` is `package.json` when the manifest was read, `fallback` otherwise.
114
+ */
115
+ export function reportedVersion(options = {}) {
116
+ const manifest = readPackageManifest(options);
117
+ if (manifest.ok) {
118
+ return { name: manifest.name, version: manifest.version, source: 'package.json' };
119
+ }
120
+ return { name: FALLBACK_NAME, version: '0.0.0-unknown', source: 'fallback' };
121
+ }
@@ -21,7 +21,7 @@
21
21
 
22
22
  import { randomUUID } from 'node:crypto';
23
23
  import { lstat, mkdir, realpath } from 'node:fs/promises';
24
- import { isAbsolute, join, resolve } from 'node:path';
24
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
25
25
 
26
26
  import { AUDIT_CODES, AUDIT_LIMITS, AuditError, probeRepository, readRepositoryTopLevel, readStatus } from './audit.js';
27
27
  import { isInside } from './locks.js';
@@ -127,9 +127,9 @@ async function pathExists(target) {
127
127
  * Owns plugin-created detached worktrees.
128
128
  *
129
129
  * One manager per plugin instance. The manager keeps metadata in memory only: a
130
- * restart forgets the registry, which is honest — a forgotten tree is still on
131
- * disk and still reviewable, and the alternative (silently deleting trees at
132
- * startup) would destroy evidence.
130
+ * restart forgets the registry. A validated continuation may recover its ONE
131
+ * recorded tree through Git's live registry; startup never scans, deletes or
132
+ * adopts arbitrary directories.
133
133
  */
134
134
  export class WorktreeManager {
135
135
  /**
@@ -525,6 +525,72 @@ export class WorktreeManager {
525
525
  return record === undefined ? null : this.view(record);
526
526
  }
527
527
 
528
+ /**
529
+ * Recover one original tree after a restart, without creating or changing it.
530
+ * The engine has already verified the caller, task history and Session identity.
531
+ * Here the stored tree identity must also agree with real paths and Git's live
532
+ * registration. A directory name alone is never evidence of a managed tree.
533
+ * @param {object} request - original taskId, sourcePath, workspacePath, state and signal.
534
+ * @returns {Promise<object>} verified metadata, or a refusal.
535
+ */
536
+ async recover(request) {
537
+ const { taskId, sourcePath, workspacePath, signal } = request;
538
+ const refuse = (reason) => new WorktreeError(WORKTREE_CODES.unknownTree,
539
+ 'the original worktree could not be verified after restart', { reason });
540
+ this.throwIfAborted(signal, { taskId, phase: 'recover' });
541
+ if (request.state === WORKTREE_STATES.disposed || safeTaskSegment(taskId) === ''
542
+ || typeof sourcePath !== 'string' || !isAbsolute(sourcePath)
543
+ || typeof workspacePath !== 'string' || !isAbsolute(workspacePath)) {
544
+ throw refuse('invalid recorded tree');
545
+ }
546
+ const present = this.get(workspacePath);
547
+ if (present !== null) return present;
548
+
549
+ const [root, source, workspace] = await Promise.all([
550
+ realpath(this.rootDir), realpath(sourcePath), realpath(workspacePath),
551
+ ]);
552
+ const key = (path) => normalizeKey(resolve(path));
553
+ const prefix = `${safeTaskSegment(taskId)}-`;
554
+ const name = basename(workspace);
555
+ if (key(source) !== key(sourcePath) || key(workspace) !== key(workspacePath)
556
+ || key(dirname(workspace)) !== key(root) || !name.startsWith(prefix)
557
+ || !/^[A-Za-z0-9]{1,12}$/.test(name.slice(prefix.length)) || key(source) === key(workspace)) {
558
+ throw refuse('recorded tree path mismatch');
559
+ }
560
+
561
+ const results = await Promise.all([
562
+ this.deps.runGit(source, ['worktree', 'list', '--porcelain', '-z']),
563
+ this.deps.runGit(source, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
564
+ this.deps.runGit(workspace, ['rev-parse', '--path-format=absolute', '--git-common-dir']),
565
+ this.deps.runGit(workspace, ['rev-parse', '--show-toplevel']),
566
+ ]);
567
+ const [listing, sourceCommon, treeCommon, top] = results.map((result) => requireResult(result, 'recover worktree'));
568
+ if ([listing, sourceCommon, treeCommon, top].some((result) => result.code !== 0)
569
+ || !isAbsolute(sourceCommon.stdout.trim()) || !isAbsolute(treeCommon.stdout.trim())
570
+ || key(sourceCommon.stdout.trim()) !== key(treeCommon.stdout.trim())
571
+ || key(top.stdout.trim()) !== key(workspace)) {
572
+ throw refuse('tree repository mismatch');
573
+ }
574
+ const registrations = listing.stdout.split('\0\0').filter(Boolean).map((block) => block.split('\0'));
575
+ const registration = registrations.find((fields) => fields.some((field) =>
576
+ field.startsWith('worktree ') && key(field.slice(9)) === key(workspace)));
577
+ const head = registration?.find((field) => field.startsWith('HEAD '))?.slice(5) ?? '';
578
+ if (!registration?.includes('detached') || !/^[a-f0-9]{40,64}$/i.test(head)
579
+ || registration.some((field) => field === 'prunable' || field.startsWith('prunable '))) {
580
+ throw refuse('original detached tree is not registered');
581
+ }
582
+ this.throwIfAborted(signal, { taskId, phase: 'recover' });
583
+ // Unknown original timestamps and source dirtiness stay unknown. The next
584
+ // run captures its own audit baseline; recovery never cleans either checkout.
585
+ const record = {
586
+ taskId, workspacePath: workspace, sourcePath: source, baseHead: head,
587
+ isolated: true, detachedVerified: true, state: WORKTREE_STATES.awaitingHostReview,
588
+ createdAt: null, completedAt: null, sourcePreexistingChanges: null,
589
+ };
590
+ this.trees.set(normalizeKey(workspace), record);
591
+ return this.view(record);
592
+ }
593
+
528
594
  /**
529
595
  * Remove one tree at a host's explicit request.
530
596
  *