youmd 0.13.14 → 0.13.16

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.
Files changed (59) hide show
  1. package/dist/commands/doctor.d.ts.map +1 -1
  2. package/dist/commands/doctor.js +1 -2
  3. package/dist/commands/doctor.js.map +1 -1
  4. package/dist/commands/push.d.ts.map +1 -1
  5. package/dist/commands/push.js +21 -1
  6. package/dist/commands/push.js.map +1 -1
  7. package/dist/commands/runtime.d.ts +5 -0
  8. package/dist/commands/runtime.d.ts.map +1 -0
  9. package/dist/commands/runtime.js +63 -0
  10. package/dist/commands/runtime.js.map +1 -0
  11. package/dist/commands/session.d.ts.map +1 -1
  12. package/dist/commands/session.js +29 -17
  13. package/dist/commands/session.js.map +1 -1
  14. package/dist/commands/stack.d.ts +0 -2
  15. package/dist/commands/stack.d.ts.map +1 -1
  16. package/dist/commands/stack.js +0 -30
  17. package/dist/commands/stack.js.map +1 -1
  18. package/dist/commands/sync.d.ts.map +1 -1
  19. package/dist/commands/sync.js +26 -8
  20. package/dist/commands/sync.js.map +1 -1
  21. package/dist/commands/worktree.d.ts +51 -0
  22. package/dist/commands/worktree.d.ts.map +1 -0
  23. package/dist/commands/worktree.js +303 -0
  24. package/dist/commands/worktree.js.map +1 -0
  25. package/dist/generated/capability-registry.d.ts +245 -101
  26. package/dist/generated/capability-registry.d.ts.map +1 -1
  27. package/dist/generated/capability-registry.js +258 -101
  28. package/dist/generated/capability-registry.js.map +1 -1
  29. package/dist/index.js +34 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/lib/api.d.ts +75 -1
  32. package/dist/lib/api.d.ts.map +1 -1
  33. package/dist/lib/api.js +44 -1
  34. package/dist/lib/api.js.map +1 -1
  35. package/dist/lib/remote-command.js +12 -11
  36. package/dist/lib/remote-command.js.map +1 -1
  37. package/dist/lib/remote-executor.d.ts +12 -0
  38. package/dist/lib/remote-executor.d.ts.map +1 -1
  39. package/dist/lib/remote-executor.js +65 -7
  40. package/dist/lib/remote-executor.js.map +1 -1
  41. package/dist/lib/runtime/event-journal.d.ts +77 -0
  42. package/dist/lib/runtime/event-journal.d.ts.map +1 -0
  43. package/dist/lib/runtime/event-journal.js +254 -0
  44. package/dist/lib/runtime/event-journal.js.map +1 -0
  45. package/dist/lib/worktreeRegistry.d.ts +40 -0
  46. package/dist/lib/worktreeRegistry.d.ts.map +1 -0
  47. package/dist/lib/worktreeRegistry.js +329 -0
  48. package/dist/lib/worktreeRegistry.js.map +1 -0
  49. package/dist/mcp/registry.d.ts.map +1 -1
  50. package/dist/mcp/registry.js +237 -1
  51. package/dist/mcp/registry.js.map +1 -1
  52. package/native/prebuilds/darwin-universal/youmd_safe_open.node +0 -0
  53. package/package.json +1 -1
  54. package/scripts/skillstack-sync/README.md +1 -1
  55. package/scripts/skillstack-sync/capture-agent-config.sh +26 -13
  56. package/scripts/skillstack-sync/context-sync.sh +82 -6
  57. package/scripts/skillstack-sync/deletion-guard.sh +75 -0
  58. package/scripts/skillstack-sync/sync.sh +118 -37
  59. package/scripts/skillstack-sync/tests/deletion-guard.test.sh +50 -0
@@ -0,0 +1,254 @@
1
+ "use strict";
2
+ // event-journal.ts — local, append-only runtime event storage.
3
+ //
4
+ // This is deliberately a small storage adapter, not a daemon, graph database,
5
+ // hosted projector, or native-session controller. It accepts only redacted
6
+ // AgentEvent v1 envelopes and gives adapters a restart-safe, idempotent ledger.
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.validateRuntimeEvent = validateRuntimeEvent;
42
+ exports.runtimeEventJournalPath = runtimeEventJournalPath;
43
+ exports.readRuntimeEventJournal = readRuntimeEventJournal;
44
+ exports.appendRuntimeEvent = appendRuntimeEvent;
45
+ const crypto_1 = require("crypto");
46
+ const fs = __importStar(require("fs"));
47
+ const path = __importStar(require("path"));
48
+ const config_1 = require("../config");
49
+ const EVENT_SCHEMA = "https://you.md/schemas/agent-runtime/event/v1";
50
+ const EVENT_VERSION = "you-md/agent-event/v1";
51
+ const JOURNAL_VERSION = "you-md/local-runtime-event-journal/v1";
52
+ const REF_RE = /^[a-z][a-z0-9-]*:[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
53
+ const HASH_RE = /^sha256:[a-f0-9]{64}$/;
54
+ const MAX_EVENT_BYTES = 262144;
55
+ const MAX_JOURNAL_LINE_BYTES = MAX_EVENT_BYTES * 2;
56
+ function journalDir(options = {}) {
57
+ return options.dir ?? path.join((0, config_1.getWritableHomeBundleDir)(), "runtime", "events");
58
+ }
59
+ function stableJson(value) {
60
+ if (value === null || typeof value !== "object")
61
+ return JSON.stringify(value);
62
+ if (Array.isArray(value))
63
+ return `[${value.map(stableJson).join(",")}]`;
64
+ const record = value;
65
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(",")}}`;
66
+ }
67
+ function sha256(value) {
68
+ return `sha256:${(0, crypto_1.createHash)("sha256").update(value).digest("hex")}`;
69
+ }
70
+ function isIsoDate(value) {
71
+ return typeof value === "string" && Number.isFinite(Date.parse(value));
72
+ }
73
+ function isRef(value) {
74
+ return typeof value === "string" && REF_RE.test(value);
75
+ }
76
+ function isRefList(value) {
77
+ return Array.isArray(value) && value.length <= 256 && value.every(isRef) && new Set(value).size === value.length;
78
+ }
79
+ function containsSecretLikeValue(value, depth = 0) {
80
+ if (depth > 12)
81
+ return true;
82
+ if (typeof value === "string") {
83
+ return /(?:-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:sk|pk|api)[-_][A-Za-z0-9]{16,}|AKIA[0-9A-Z]{16}|xox[baprs]-)/.test(value);
84
+ }
85
+ if (!value || typeof value !== "object")
86
+ return false;
87
+ if (Array.isArray(value))
88
+ return value.some((entry) => containsSecretLikeValue(entry, depth + 1));
89
+ return Object.entries(value).some(([key, entry]) => /(?:password|secret|token|api[_-]?key|authorization|cookie)/i.test(key) || containsSecretLikeValue(entry, depth + 1));
90
+ }
91
+ function isPlainRecord(value) {
92
+ return !!value && typeof value === "object" && !Array.isArray(value);
93
+ }
94
+ function isJsonValue(value, depth = 0) {
95
+ if (depth > 12 || value === undefined || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint")
96
+ return false;
97
+ if (value === null || typeof value === "string" || typeof value === "boolean")
98
+ return true;
99
+ if (typeof value === "number")
100
+ return Number.isFinite(value);
101
+ if (Array.isArray(value))
102
+ return value.length <= 256 && value.every((entry) => isJsonValue(entry, depth + 1));
103
+ return isPlainRecord(value) && Object.keys(value).length <= 64 && Object.values(value).every((entry) => isJsonValue(entry, depth + 1));
104
+ }
105
+ /** Validates the durable, privacy-safe subset before any bytes reach disk. */
106
+ function validateRuntimeEvent(value) {
107
+ if (!isPlainRecord(value))
108
+ return false;
109
+ const event = value;
110
+ if (event.$schema !== EVENT_SCHEMA ||
111
+ event.schemaVersion !== EVENT_VERSION ||
112
+ event.kind !== "AgentEvent" ||
113
+ ![event.eventRef, event.ownerRef, event.runRef, event.agentRef, event.projectRef, event.machineRef, event.workspaceRef, event.taskRef].every(isRef) ||
114
+ !Number.isInteger(event.sequence) || event.sequence < 0 ||
115
+ typeof event.eventType !== "string" || !/^[a-z][a-z0-9_.-]{1,79}$/.test(event.eventType) ||
116
+ !["recorded", "projected", "rejected"].includes(String(event.lifecycle)) ||
117
+ !(event.capabilityRef === null || isRef(event.capabilityRef)) ||
118
+ !isPlainRecord(event.runtime) || !isPlainRecord(event.auth) || !isPlainRecord(event.payload) ||
119
+ !isJsonValue(event.runtime) || !isJsonValue(event.auth) || !isJsonValue(event.payload) ||
120
+ typeof event.idempotencyKey !== "string" || event.idempotencyKey.length < 8 || event.idempotencyKey.length > 256 ||
121
+ !isRefList(event.artifactRefs) || !isRefList(event.proposalRefs) ||
122
+ !isIsoDate(event.occurredAt) || event.secretValuesExposed !== false)
123
+ return false;
124
+ const delivery = event.delivery;
125
+ if (!delivery || delivery.sourceForm !== "transient-local" || delivery.storedForm !== "persistent-redacted" ||
126
+ delivery.redacted !== true || delivery.canarySafe !== true || !HASH_RE.test(delivery.payloadHash) ||
127
+ !Number.isInteger(delivery.byteLength) || delivery.byteLength < 0 || delivery.byteLength > MAX_EVENT_BYTES ||
128
+ Buffer.byteLength(stableJson(event.payload), "utf8") !== delivery.byteLength ||
129
+ sha256(stableJson(event.payload)) !== delivery.payloadHash)
130
+ return false;
131
+ return !containsSecretLikeValue(event.payload) && !containsSecretLikeValue(event.auth) && !containsSecretLikeValue(event.runtime);
132
+ }
133
+ function runtimeEventJournalPath(runRef, options = {}) {
134
+ if (!isRef(runRef))
135
+ throw new Error("runRef must be a qualified reference");
136
+ // The filename deliberately contains a hash, not a native/runtime identifier.
137
+ return path.join(journalDir(options), `${sha256(runRef).slice("sha256:".length)}.jsonl`);
138
+ }
139
+ function entryHash(entry) {
140
+ return sha256(stableJson(entry));
141
+ }
142
+ function validateEntry(value, previous) {
143
+ if (!isPlainRecord(value))
144
+ return false;
145
+ const entry = value;
146
+ if (entry.journalVersion !== JOURNAL_VERSION || !Number.isInteger(entry.sequence) || entry.sequence !== (previous?.sequence ?? -1) + 1 ||
147
+ !validateRuntimeEvent(entry.event) || entry.event.sequence !== entry.sequence ||
148
+ entry.previousEventHash !== (previous?.eventHash ?? null) || typeof entry.eventHash !== "string" || !HASH_RE.test(entry.eventHash) ||
149
+ !isIsoDate(entry.appendedAt))
150
+ return false;
151
+ return entry.eventHash === entryHash({
152
+ journalVersion: JOURNAL_VERSION,
153
+ sequence: entry.sequence,
154
+ event: entry.event,
155
+ previousEventHash: entry.previousEventHash,
156
+ appendedAt: entry.appendedAt,
157
+ });
158
+ }
159
+ /** Read only complete, verified entries. A corrupt tail is fail-closed, never silently discarded. */
160
+ function readRuntimeEventJournal(runRef, options = {}) {
161
+ let target;
162
+ try {
163
+ target = runtimeEventJournalPath(runRef, options);
164
+ if (!fs.existsSync(target))
165
+ return { ok: true, entries: [] };
166
+ const body = fs.readFileSync(target, "utf8");
167
+ const lines = body.split("\n").filter(Boolean);
168
+ const entries = [];
169
+ for (let index = 0; index < lines.length; index += 1) {
170
+ if (Buffer.byteLength(lines[index], "utf8") > MAX_JOURNAL_LINE_BYTES) {
171
+ return { ok: false, error: `journal line ${index + 1} exceeds the bounded size` };
172
+ }
173
+ let candidate;
174
+ try {
175
+ candidate = JSON.parse(lines[index]);
176
+ }
177
+ catch {
178
+ return { ok: false, error: `journal line ${index + 1} is not valid JSON` };
179
+ }
180
+ if (!validateEntry(candidate, entries.at(-1)))
181
+ return { ok: false, error: `journal integrity check failed at line ${index + 1}` };
182
+ entries.push(candidate);
183
+ }
184
+ return { ok: true, entries };
185
+ }
186
+ catch {
187
+ return { ok: false, error: "runtime event journal could not be read" };
188
+ }
189
+ }
190
+ function withJournalLock(target, action) {
191
+ const lock = `${target}.lock`;
192
+ try {
193
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
194
+ fs.mkdirSync(lock, { mode: 0o700 });
195
+ }
196
+ catch (error) {
197
+ if (error.code === "EEXIST")
198
+ return { ok: false, error: "runtime event journal is busy" };
199
+ return { ok: false, error: "runtime event journal lock could not be acquired" };
200
+ }
201
+ try {
202
+ return action();
203
+ }
204
+ finally {
205
+ fs.rmSync(lock, { recursive: true, force: true });
206
+ }
207
+ }
208
+ /**
209
+ * Appends one canonical event exactly once. Replaying the identical eventRef is
210
+ * a no-op; a divergent reuse fails before writing. This function never projects
211
+ * to the network or opens a native session.
212
+ */
213
+ function appendRuntimeEvent(event, options = {}) {
214
+ if (!validateRuntimeEvent(event))
215
+ return { ok: false, error: "event fails the durable runtime-event safety contract" };
216
+ const target = runtimeEventJournalPath(event.runRef, options);
217
+ const result = withJournalLock(target, () => {
218
+ const current = readRuntimeEventJournal(event.runRef, options);
219
+ if (!current.ok)
220
+ return current;
221
+ const duplicate = current.entries.find((entry) => entry.event.eventRef === event.eventRef);
222
+ if (duplicate) {
223
+ return stableJson(duplicate.event) === stableJson(event)
224
+ ? { ok: true, status: "replayed", entry: duplicate }
225
+ : { ok: false, error: "eventRef replay conflicts with the persisted event" };
226
+ }
227
+ if (event.sequence !== current.entries.length)
228
+ return { ok: false, error: "event sequence is not the next contiguous journal sequence" };
229
+ const appendedAt = (options.now?.() ?? new Date()).toISOString();
230
+ const base = {
231
+ journalVersion: JOURNAL_VERSION,
232
+ sequence: event.sequence,
233
+ event,
234
+ previousEventHash: current.entries.at(-1)?.eventHash ?? null,
235
+ appendedAt,
236
+ };
237
+ const entry = { ...base, eventHash: entryHash(base) };
238
+ const serialized = stableJson(entry);
239
+ if (Buffer.byteLength(serialized, "utf8") > MAX_JOURNAL_LINE_BYTES) {
240
+ return { ok: false, error: "runtime event journal entry exceeds the bounded size" };
241
+ }
242
+ const handle = fs.openSync(target, "a", 0o600);
243
+ try {
244
+ fs.writeSync(handle, `${serialized}\n`, undefined, "utf8");
245
+ fs.fsyncSync(handle);
246
+ }
247
+ finally {
248
+ fs.closeSync(handle);
249
+ }
250
+ return { ok: true, status: "appended", entry };
251
+ });
252
+ return result;
253
+ }
254
+ //# sourceMappingURL=event-journal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-journal.js","sourceRoot":"","sources":["../../../src/lib/runtime/event-journal.ts"],"names":[],"mappings":";AAAA,+DAA+D;AAC/D,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,gFAAgF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HhF,oDA6BC;AAED,0DAIC;AAyBD,0DAqBC;AAmBD,gDAkCC;AAhQD,mCAAoC;AACpC,uCAAyB;AACzB,2CAA6B;AAC7B,sCAAqD;AAErD,MAAM,YAAY,GAAG,+CAA+C,CAAC;AACrE,MAAM,aAAa,GAAG,uBAAuB,CAAC;AAC9C,MAAM,eAAe,GAAG,uCAAuC,CAAC;AAChE,MAAM,MAAM,GAAG,gDAAgD,CAAC;AAChE,MAAM,OAAO,GAAG,uBAAuB,CAAC;AACxC,MAAM,eAAe,GAAG,MAAO,CAAC;AAChC,MAAM,sBAAsB,GAAG,eAAe,GAAG,CAAC,CAAC;AA2DnD,SAAS,UAAU,CAAC,UAAsC,EAAE;IAC1D,OAAO,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,IAAA,iCAAwB,GAAE,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,UAAU,CAAC,KAAc;IAChC,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC9E,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,KAAK,CAAC,GAAG,CAAC,UAAU,C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AE,MAAM,EAAE,UAAmB,EAAE,KAAK,EAAE,CAAC;IACnE,CAAC,CAAC,CAAC;IACH,OAAO,MAAmC,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,40 @@
1
+ export type RegistryRow = Record<string, unknown> & {
2
+ id: string;
3
+ };
4
+ export declare const SYNC_REGISTRY_STATUSES: readonly ["created", "active", "dirty", "unpushed", "pushed", "merged", "retired", "abandoned", "restored"];
5
+ export declare function stateDir(env?: NodeJS.ProcessEnv, home?: string): string;
6
+ /** Replace absolute paths with `<local>/<basename>` and redact secrets. */
7
+ export declare function redactLocal(text: string): string;
8
+ export declare function parseJsonl(text: string): Array<Record<string, unknown>>;
9
+ /** Later rows override earlier ones per id (the registry is append-only). */
10
+ export declare function collapseRegistry(rows: Array<Record<string, unknown>>): RegistryRow[];
11
+ export declare function readRegistry(file: string): RegistryRow[];
12
+ export declare function sha256(text: string): string;
13
+ export interface BuildSyncOptions {
14
+ machineRef: string;
15
+ /** Overrides reading archive.card from disk (tests). */
16
+ cardMarkdown?: string;
17
+ bundlePointer?: string;
18
+ readFile?: (p: string) => string | null;
19
+ }
20
+ export declare function worktreeRefOf(repo: string, branch: string, headSha: string): string;
21
+ /** Build the redacted POST /api/v1/me/worktrees/sync body for one registry row. */
22
+ export declare function buildSyncBody(row: RegistryRow, opts: BuildSyncOptions): Record<string, unknown>;
23
+ /** Idempotency key from the spec: id + head_sha + cardHash. */
24
+ export declare function idempotencyKey(body: Record<string, unknown>): string;
25
+ /**
26
+ * Claude ids are v4 uuids or `agent-<hex>`; Codex rollout ids are v7 uuids
27
+ * (ULID-style, start `01`, version nibble 7).
28
+ */
29
+ export declare function inferHarness(sessionRef: string): "claude" | "codex" | null;
30
+ /**
31
+ * Map one real stranded-work.jsonl row (workItemRef/source/sessionRefs/repoName/
32
+ * classification/evidence{...}) to a work-item sync body. Only `stranded` and
33
+ * `superseded-likely` rows become work items; active/safe/open-pr are covered by
34
+ * worktree sync. A superseded-likely row stays `pending` server-side and only
35
+ * carries a candidate -- it is never auto-superseded.
36
+ */
37
+ export declare function buildWorkItemBody(row: Record<string, unknown>, machineRef: string): Record<string, unknown> | null;
38
+ /** Resolve wt ref | registry id | branch | path-basename against the local registry. */
39
+ export declare function resolveLocalRow(ref: string, rows: RegistryRow[]): RegistryRow | undefined;
40
+ //# sourceMappingURL=worktreeRegistry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worktreeRegistry.d.ts","sourceRoot":"","sources":["../../src/lib/worktreeRegistry.ts"],"names":[],"mappings":"AAcA,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnE,eAAO,MAAM,sBAAsB,6GAEzB,CAAC;AAMX,wBAAgB,QAAQ,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,EAAE,IAAI,SAAyB,GAAG,MAAM,CAEpG;AAED,2EAA2E;AAC3E,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGhD;AAWD,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAavE;AAED,6EAA6E;AAC7E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,WAAW,EAAE,CAQpF;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,EAAE,CAGxD;AAUD,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3C;AAED,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,wDAAwD;IACxD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,CAAC;CACzC;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAInF;AAED,mFAAmF;AACnF,wBAAgB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAqD/F;AAED,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAEpE;AAMD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,IAAI,CAK1E;AAoCD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAsDlH;AAED,wFAAwF;AACxF,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,WAAW,GAAG,SAAS,CAMzF"}
@@ -0,0 +1,329 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SYNC_REGISTRY_STATUSES = void 0;
37
+ exports.stateDir = stateDir;
38
+ exports.redactLocal = redactLocal;
39
+ exports.parseJsonl = parseJsonl;
40
+ exports.collapseRegistry = collapseRegistry;
41
+ exports.readRegistry = readRegistry;
42
+ exports.sha256 = sha256;
43
+ exports.worktreeRefOf = worktreeRefOf;
44
+ exports.buildSyncBody = buildSyncBody;
45
+ exports.idempotencyKey = idempotencyKey;
46
+ exports.inferHarness = inferHarness;
47
+ exports.buildWorkItemBody = buildWorkItemBody;
48
+ exports.resolveLocalRow = resolveLocalRow;
49
+ /**
50
+ * Pure helpers for `you worktree push`: read the local worktree registry
51
+ * (worktree-lifecycle.sh JSONL), collapse it to one row per id, and build the
52
+ * redacted sync body. Nothing here touches the network.
53
+ *
54
+ * Privacy contract: absolute paths never leave the machine. Path-shaped
55
+ * strings are replaced with `<local>/<basename>` and secrets are redacted
56
+ * before hashing, so the card hash is over exactly what is uploaded.
57
+ */
58
+ const crypto_1 = require("crypto");
59
+ const fs = __importStar(require("fs"));
60
+ const path = __importStar(require("path"));
61
+ const redact_1 = require("./redact");
62
+ exports.SYNC_REGISTRY_STATUSES = [
63
+ "created", "active", "dirty", "unpushed", "pushed", "merged", "retired", "abandoned", "restored",
64
+ ];
65
+ const ABS_PATH = /(?:\/(?:Users|home|private|tmp|var|opt|Volumes|Library)\/[^\s"'`)\]]+|[A-Za-z]:\\(?:Users|Windows)\\[^\s"'`)\]]+|~\/[^\s"'`)\]]+)/g;
66
+ function stateDir(env = process.env, home = process.env.HOME ?? "") {
67
+ return env.WTL_STATE || path.join(home, ".agent-shared", "state");
68
+ }
69
+ /** Replace absolute paths with `<local>/<basename>` and redact secrets. */
70
+ function redactLocal(text) {
71
+ const noPaths = text.replace(ABS_PATH, (m) => `<local>/${path.basename(m.replace(/[/\\]+$/, ""))}`);
72
+ return (0, redact_1.redactText)(noPaths).text;
73
+ }
74
+ function redactDeep(value) {
75
+ if (typeof value === "string")
76
+ return redactLocal(value);
77
+ if (Array.isArray(value))
78
+ return value.map(redactDeep);
79
+ if (value && typeof value === "object") {
80
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactDeep(v)]));
81
+ }
82
+ return value;
83
+ }
84
+ function parseJsonl(text) {
85
+ const rows = [];
86
+ for (const line of text.split("\n")) {
87
+ const t = line.trim();
88
+ if (!t)
89
+ continue;
90
+ try {
91
+ const v = JSON.parse(t);
92
+ if (v && typeof v === "object" && !Array.isArray(v))
93
+ rows.push(v);
94
+ }
95
+ catch {
96
+ // A torn trailing line from a concurrent append must not break the push.
97
+ }
98
+ }
99
+ return rows;
100
+ }
101
+ /** Later rows override earlier ones per id (the registry is append-only). */
102
+ function collapseRegistry(rows) {
103
+ const byId = new Map();
104
+ for (const row of rows) {
105
+ const id = typeof row.id === "string" ? row.id : "";
106
+ if (!id)
107
+ continue;
108
+ byId.set(id, { ...(byId.get(id) ?? {}), ...row, id });
109
+ }
110
+ return [...byId.values()];
111
+ }
112
+ function readRegistry(file) {
113
+ if (!fs.existsSync(file))
114
+ return [];
115
+ return collapseRegistry(parseJsonl(fs.readFileSync(file, "utf8")));
116
+ }
117
+ const str = (v) => (typeof v === "string" ? v : "");
118
+ const num = (v, d = 0) => (typeof v === "number" && Number.isFinite(v) ? v : d);
119
+ const bool = (v) => v === true;
120
+ function ms(v) {
121
+ const t = typeof v === "string" ? Date.parse(v) : NaN;
122
+ return Number.isFinite(t) ? t : 0;
123
+ }
124
+ function sha256(text) {
125
+ return `sha256:${(0, crypto_1.createHash)("sha256").update(text).digest("hex")}`;
126
+ }
127
+ function worktreeRefOf(repo, branch, headSha) {
128
+ const cleaned = branch.replace(/[^A-Za-z0-9._/-]/g, "-").replace(/\/{2,}/g, "/");
129
+ const b = cleaned && /^[A-Za-z0-9._][A-Za-z0-9._/-]{0,199}$/.test(cleaned) ? cleaned : `detached-${headSha.slice(0, 7)}`;
130
+ return `wt:${repo}:${b}`;
131
+ }
132
+ /** Build the redacted POST /api/v1/me/worktrees/sync body for one registry row. */
133
+ function buildSyncBody(row, opts) {
134
+ const status = exports.SYNC_REGISTRY_STATUSES.includes(str(row.status))
135
+ ? str(row.status)
136
+ : "active";
137
+ const archive = (row.archive && typeof row.archive === "object" ? row.archive : {});
138
+ const headSha = str(row.head_sha).toLowerCase();
139
+ const repo = str(row.repo);
140
+ const sessions = (row.sessions && typeof row.sessions === "object" ? row.sessions : {});
141
+ const ids = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string").map(redactLocal) : []);
142
+ let cardMarkdown = opts.cardMarkdown;
143
+ if (cardMarkdown === undefined && typeof archive.card === "string" && archive.card) {
144
+ const read = opts.readFile ?? ((p) => (fs.existsSync(p) ? fs.readFileSync(p, "utf8") : null));
145
+ const raw = read(archive.card);
146
+ if (raw !== null)
147
+ cardMarkdown = raw;
148
+ }
149
+ const card = cardMarkdown === undefined ? undefined : redactLocal(cardMarkdown);
150
+ const body = {
151
+ registryId: row.id,
152
+ projectSlug: repo.toLowerCase().replace(/[^a-z0-9._-]+/g, "-"),
153
+ repoRef: repo,
154
+ branch: str(row.branch),
155
+ base: str(row.base) || "origin/main",
156
+ headSha,
157
+ goal: redactLocal(str(row.goal)) || "(no goal recorded)",
158
+ registryStatus: status,
159
+ merged: bool(row.merged) || status === "merged",
160
+ machineRef: opts.machineRef,
161
+ sizeKb: num(row.size_kb),
162
+ createdAt: ms(row.created_at),
163
+ lastActivityAt: ms(row.last_activity_at),
164
+ sessions: { claude: ids(sessions.claude), codex: ids(sessions.codex) },
165
+ facts: { dirty: bool(row.dirty), pushed: bool(row.pushed), ahead: Math.max(0, Math.floor(num(row.ahead))), idleHours: num(row.idle_hours) },
166
+ };
167
+ if (str(row.pr_url))
168
+ body.prUrl = str(row.pr_url);
169
+ if (str(row.merged_via))
170
+ body.mergedVia = str(row.merged_via);
171
+ if (str(row.retired_at))
172
+ body.retiredAt = ms(row.retired_at);
173
+ if (str(row.lane_ref))
174
+ body.laneRef = str(row.lane_ref);
175
+ if (str(archive.remote_ref))
176
+ body.remoteRef = str(archive.remote_ref);
177
+ const pointer = opts.bundlePointer ?? str(archive.bundle_pointer);
178
+ if (pointer)
179
+ body.bundlePointer = pointer;
180
+ if (card !== undefined) {
181
+ body.cardMarkdown = card;
182
+ body.cardHash = sha256(card);
183
+ }
184
+ const redacted = redactDeep(body);
185
+ // Identifier-shaped fields are hex/slug only: the phone-number redactor corrupts long digit runs
186
+ // inside a 40-char SHA, so restore them verbatim when they are provably safe.
187
+ if (/^[a-f0-9]{7,64}$/.test(headSha))
188
+ redacted.headSha = headSha;
189
+ if (typeof row.id === "string" && /^[A-Za-z0-9._-]{1,300}$/.test(row.id))
190
+ redacted.registryId = row.id;
191
+ if (/^[A-Za-z0-9._/@:-]{1,300}$/.test(str(archive.remote_ref)))
192
+ redacted.remoteRef = str(archive.remote_ref);
193
+ return redacted;
194
+ }
195
+ /** Idempotency key from the spec: id + head_sha + cardHash. */
196
+ function idempotencyKey(body) {
197
+ return `${String(body.registryId)}:${String(body.headSha)}:${String(body.cardHash ?? "nocard")}`;
198
+ }
199
+ const WORK_ITEM_CLASSES = new Set(["stranded", "superseded-likely"]);
200
+ const GOAL_MAX = 280;
201
+ const EDITS_MAX = 50;
202
+ /**
203
+ * Claude ids are v4 uuids or `agent-<hex>`; Codex rollout ids are v7 uuids
204
+ * (ULID-style, start `01`, version nibble 7).
205
+ */
206
+ function inferHarness(sessionRef) {
207
+ if (/^agent-[0-9a-f]+$/i.test(sessionRef))
208
+ return "claude";
209
+ const m = /^([0-9a-f]{8})-[0-9a-f]{4}-([0-9a-f])[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/i.exec(sessionRef);
210
+ if (!m)
211
+ return null;
212
+ return m[1].startsWith("01") && m[2] === "7" ? "codex" : "claude";
213
+ }
214
+ function slug(text, max) {
215
+ const s = text.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
216
+ return s.length <= max ? s : `${s.slice(0, max - 9)}-${s.slice(-8)}`;
217
+ }
218
+ function diffStatSummary(v) {
219
+ if (typeof v === "string")
220
+ return v;
221
+ if (!v || typeof v !== "object")
222
+ return "";
223
+ const d = v;
224
+ const parts = [];
225
+ if (num(d.branchFiles) || num(d.branchNetLines))
226
+ parts.push(`branch ${num(d.branchFiles)} files, ${num(d.branchNetLines)} net lines`);
227
+ if (num(d.dirtyFiles) || num(d.untrackedFiles)) {
228
+ parts.push(`dirty ${num(d.dirtyFiles)} files (+${num(d.dirtyAdded)}/-${num(d.dirtyDeleted)}), ${num(d.untrackedFiles)} untracked`);
229
+ }
230
+ return parts.join("; ");
231
+ }
232
+ function prSummaries(v) {
233
+ if (!Array.isArray(v))
234
+ return [];
235
+ const out = [];
236
+ for (const p of v.slice(0, 20)) {
237
+ if (!p || typeof p !== "object")
238
+ continue;
239
+ const r = p;
240
+ if (!Number.isFinite(r.number))
241
+ continue;
242
+ out.push({
243
+ number: r.number,
244
+ state: str(r.state) || "UNKNOWN",
245
+ ...(str(r.url) ? { url: redactLocal(str(r.url)) } : {}),
246
+ ...(str(r.title) ? { title: redactLocal(str(r.title)).slice(0, 200) } : {}),
247
+ });
248
+ }
249
+ return out;
250
+ }
251
+ /**
252
+ * Map one real stranded-work.jsonl row (workItemRef/source/sessionRefs/repoName/
253
+ * classification/evidence{...}) to a work-item sync body. Only `stranded` and
254
+ * `superseded-likely` rows become work items; active/safe/open-pr are covered by
255
+ * worktree sync. A superseded-likely row stays `pending` server-side and only
256
+ * carries a candidate -- it is never auto-superseded.
257
+ */
258
+ function buildWorkItemBody(row, machineRef) {
259
+ const classification = str(row.classification);
260
+ if (!WORK_ITEM_CLASSES.has(classification))
261
+ return null;
262
+ const source = str(row.source);
263
+ if (source !== "worktree" && source !== "branch" && source !== "session")
264
+ return null;
265
+ const producerRef = str(row.workItemRef);
266
+ if (!producerRef)
267
+ return null;
268
+ const refs = Array.isArray(row.sessionRefs) ? row.sessionRefs.filter((x) => typeof x === "string") : [];
269
+ const firstSession = refs[0] ?? "";
270
+ const inferred = firstSession ? inferHarness(firstSession) : null;
271
+ const harness = inferred ?? (source === "session" ? "claude" : "git");
272
+ // Session rows key on the session id; worktree/branch rows key on the producer ref so two rows never collide.
273
+ const sessionRef = slug(source === "session" && firstSession ? firstSession : producerRef.replace(/^sw(?:-sess)?:/, ""), 120);
274
+ const cwdRepo = slug(str(row.repoName) || path.basename(str(row.repo).replace(/[/\\]+$/, "")), 200);
275
+ if (!sessionRef || !cwdRepo)
276
+ return null;
277
+ const ev = (row.evidence && typeof row.evidence === "object" ? row.evidence : {});
278
+ const edits = (Array.isArray(ev.editedFiles) ? ev.editedFiles : [])
279
+ .filter((x) => typeof x === "string")
280
+ .slice(0, EDITS_MAX)
281
+ .map(redactLocal);
282
+ const prs = prSummaries(ev.prs);
283
+ const evidence = {
284
+ edits,
285
+ plans: Array.isArray(ev.plans) ? ev.plans.filter((x) => typeof x === "string").slice(0, 20).map(redactLocal) : [],
286
+ prs,
287
+ };
288
+ const diffStat = redactLocal(diffStatSummary(ev.diffStat));
289
+ if (diffStat)
290
+ evidence.diffStat = diffStat;
291
+ if (Number.isFinite(ev.localCommits))
292
+ evidence.localCommits = ev.localCommits;
293
+ if (Number.isFinite(ev.lostFiles))
294
+ evidence.lostFiles = ev.lostFiles;
295
+ const confidence = str(row.confidence);
296
+ const branch = str(row.branch);
297
+ const body = {
298
+ source: harness,
299
+ sessionRef,
300
+ cwdRepo,
301
+ workItemRef: redactLocal(producerRef).slice(0, 300),
302
+ goal: redactLocal(str(row.goal)).slice(0, GOAL_MAX) || "(no goal recorded)",
303
+ lastActivityAt: ms(row.lastActivityAt),
304
+ classification,
305
+ evidence,
306
+ machineRef,
307
+ };
308
+ if (confidence)
309
+ body.confidence = confidence;
310
+ if (branch)
311
+ body.branch = redactLocal(branch).slice(0, 200);
312
+ if (str(row.path))
313
+ body.path = redactLocal(str(row.path));
314
+ if (classification === "superseded-likely") {
315
+ body.supersededCandidate = {
316
+ prs,
317
+ ...(str(ev.note) ? { note: redactLocal(str(ev.note)).slice(0, 400) } : {}),
318
+ confidence: confidence || "low",
319
+ };
320
+ }
321
+ return redactDeep(body);
322
+ }
323
+ /** Resolve wt ref | registry id | branch | path-basename against the local registry. */
324
+ function resolveLocalRow(ref, rows) {
325
+ return (rows.find((r) => r.id === ref) ??
326
+ rows.find((r) => worktreeRefOf(str(r.repo), str(r.branch), str(r.head_sha)) === ref) ??
327
+ rows.find((r) => str(r.branch) === ref));
328
+ }
329
+ //# sourceMappingURL=worktreeRegistry.js.map