dsh-better-edit 0.1.3 → 0.1.4

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/lib/drift.js CHANGED
@@ -92,7 +92,7 @@ export async function scanDrift(input) {
92
92
  const result = computeDrift({ ...input, reported });
93
93
  if (!result || result.allAlreadyReported)
94
94
  return result?.text;
95
- await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })));
95
+ await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })), input.resultLines.length);
96
96
  await markDriftReported(input.sessionKey, input.path, result.rows.filter((row) => row.drifted).map((row) => row.hash));
97
97
  return result.text;
98
98
  }
@@ -124,7 +124,7 @@ export async function execPipeline(io, params, cwd, options) {
124
124
  catch (error) {
125
125
  if (error instanceof AnchorMismatchError ||
126
126
  error instanceof ServedRejectionError) {
127
- await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy);
127
+ await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy, originalHashes.length);
128
128
  }
129
129
  throw error;
130
130
  }
@@ -113,8 +113,8 @@ export function verifyServedRange(args) {
113
113
  }
114
114
  }
115
115
  }
116
- export async function recordEchoServes(sessionKey, path, rows, policy) {
116
+ export async function recordEchoServes(sessionKey, path, rows, policy, lineCount) {
117
117
  if (policy !== "live")
118
118
  return;
119
- await recordServed(sessionKey, path, rows);
119
+ await recordServed(sessionKey, path, rows, lineCount);
120
120
  }
package/lib/sandbox.js CHANGED
@@ -9,8 +9,8 @@
9
9
  * under `workspace-write` even though the built-in `write` succeeds there.
10
10
  * @module dsh-better-edit/sandbox
11
11
  */
12
- import { FsError } from '@deepseek-ai/dsh-fs';
13
- import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs, } from '@deepseek-ai/dsh-sandbox';
12
+ import { FsError } from "@deepseek-ai/dsh-fs";
13
+ import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs, } from "@deepseek-ai/dsh-sandbox";
14
14
  /**
15
15
  * The filesystem escalation API: advertisement gating, per-call policy
16
16
  * resolution, the one-approved wider retry, and denial-marker mapping. A pure
@@ -26,9 +26,12 @@ export class FsSandboxController {
26
26
  this.ctx = ctx;
27
27
  const defaultMode = ctx.fs.sandboxMode;
28
28
  this.escalationModes = defaultMode === undefined ? [] : ESCALATION_TARGETS;
29
- this.policy = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy');
29
+ this.policy =
30
+ defaultMode === undefined
31
+ ? undefined
32
+ : ctx.get("sandboxPolicy");
30
33
  if (defaultMode !== undefined && this.policy === undefined) {
31
- throw new Error('dsh-better-edit: the mounted filesystem confines but ctx.sandboxPolicy is missing');
34
+ throw new Error("dsh-better-edit: the mounted filesystem confines but ctx.sandboxPolicy is missing");
32
35
  }
33
36
  }
34
37
  /**
@@ -40,15 +43,15 @@ export class FsSandboxController {
40
43
  schemaFields() {
41
44
  return {
42
45
  sandbox_permissions: {
43
- type: 'string',
46
+ type: "string",
44
47
  enum: [...this.escalationModes],
45
- description: 'The wider sandbox mode this file operation needs. Only valid as a one-shot retry '
46
- + 'of an operation the sandbox just denied; requires justification and user approval.',
48
+ description: "The wider sandbox mode this file operation needs. Only valid as a one-shot retry " +
49
+ "of an operation the sandbox just denied; requires justification and user approval.",
47
50
  },
48
51
  justification: {
49
- type: 'string',
50
- description: 'Required with sandbox_permissions: one sentence for the user explaining '
51
- + 'why this exact file operation needs the wider access.',
52
+ type: "string",
53
+ description: "Required with sandbox_permissions: one sentence for the user explaining " +
54
+ "why this exact file operation needs the wider access.",
52
55
  },
53
56
  };
54
57
  }
@@ -66,16 +69,24 @@ export class FsSandboxController {
66
69
  */
67
70
  async resolvePolicy(toolName, args, exec) {
68
71
  validateEscalationArgs(args.sandbox_permissions, args.justification);
69
- const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} });
70
- if (args.sandbox_permissions === undefined || args.justification === undefined) {
72
+ const standingPolicy = this.policy?.resolve({
73
+ ...(exec.agent ? { session: exec.agent.session } : {}),
74
+ });
75
+ if (args.sandbox_permissions === undefined ||
76
+ args.justification === undefined) {
71
77
  return standingPolicy;
72
78
  }
73
79
  if (this.escalationModes.length === 0) {
74
- throw new Error('sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)');
80
+ throw new Error("sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)");
75
81
  }
76
82
  const policy = standingPolicy;
77
- const approvedMode = await approveEscalation({ requestedMode: args.sandbox_permissions, justification: args.justification, effectiveMode: policy.mode, subject: 'operation' }, {
78
- approver: this.ctx.get('approval'),
83
+ const approvedMode = await approveEscalation({
84
+ requestedMode: args.sandbox_permissions,
85
+ justification: args.justification,
86
+ effectiveMode: policy.mode,
87
+ subject: "operation",
88
+ }, {
89
+ approver: this.ctx.get("approval"),
79
90
  agent: exec.agent,
80
91
  callId: exec.callId,
81
92
  toolName,
@@ -89,9 +100,9 @@ export class FsSandboxController {
89
100
  * hint, keeping the structured code. Any other error passes through.
90
101
  */
91
102
  mapError(error, policy) {
92
- if (!(error instanceof FsError) || error.code !== 'FS_SANDBOX_DENIED')
103
+ if (!(error instanceof FsError) || error.code !== "FS_SANDBOX_DENIED")
93
104
  return error;
94
105
  const mode = policy.mode;
95
- return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker('operation')}`, 'FS_SANDBOX_DENIED', { cause: error });
106
+ return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker("operation")}`, "FS_SANDBOX_DENIED", { cause: error });
96
107
  }
97
108
  }
@@ -62,11 +62,39 @@ export function upsertServed(store, sessionKey, path, entries) {
62
62
  store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
63
63
  });
64
64
  }
65
- export function recordServes(store, sessionKey, path, rows) {
65
+ export function recordServes(store, sessionKey, path, rows, lineCount) {
66
66
  if (rows.length === 0)
67
67
  return;
68
68
  try {
69
- upsertServed(store, sessionKey, path, rows);
69
+ if (lineCount === undefined) {
70
+ upsertServed(store, sessionKey, path, rows);
71
+ return;
72
+ }
73
+ // A serve of the CURRENT file state must never leave hashes at
74
+ // positions beyond the file's line count: a stale tail would hold a
75
+ // surviving line's hash at its OLD position while the new serve holds
76
+ // it at its current one, and the duplicate makes every later edit on
77
+ // that line fail E_RANGE_UNVERIFIED ("served at N positions").
78
+ withStore(() => {
79
+ const updated = getServed(store, sessionKey, path).slice();
80
+ if (updated.length > lineCount)
81
+ updated.length = lineCount;
82
+ for (const entry of rows) {
83
+ if (!Number.isInteger(entry.position) || entry.position < 0) {
84
+ throw new TypeError(`Invalid served position: ${entry.position}`);
85
+ }
86
+ if (entry.hash !== null &&
87
+ (typeof entry.hash !== "string" || !HASH_RE.test(entry.hash))) {
88
+ throw new TypeError(`Invalid served hash: ${String(entry.hash)}`);
89
+ }
90
+ while (updated.length <= entry.position)
91
+ updated.push(null);
92
+ updated[entry.position] = entry.hash;
93
+ }
94
+ while (updated.length > 0 && updated[updated.length - 1] === null)
95
+ updated.pop();
96
+ store.stmts.servedUpsert(sessionKey, path, JSON.stringify(updated), Date.now());
97
+ });
70
98
  }
71
99
  catch (error) {
72
100
  console.error("Failed to record served rows:", error);
@@ -165,12 +193,12 @@ export async function loadServed(sessionKey, path) {
165
193
  const store = await loadHashStore();
166
194
  return getServed(store, sessionKey, path);
167
195
  }
168
- export async function recordServed(sessionKey, path, rows) {
196
+ export async function recordServed(sessionKey, path, rows, lineCount) {
169
197
  if (rows.length === 0)
170
198
  return;
171
199
  try {
172
200
  const store = await loadHashStore();
173
- recordServes(store, sessionKey, path, rows);
201
+ recordServes(store, sessionKey, path, rows, lineCount);
174
202
  }
175
203
  catch (error) {
176
204
  console.error('Failed to record served rows:', error);
@@ -167,7 +167,7 @@ async function processFile(io, items, _cwd, opts) {
167
167
  ? error.servedRows
168
168
  : echoRowsForItem(edit, originalHashes);
169
169
  if (echoRows) {
170
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
170
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
171
171
  }
172
172
  const echoBlock = echoRows
173
173
  ? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
@@ -196,7 +196,7 @@ async function processFile(io, items, _cwd, opts) {
196
196
  const originalLines = splitLines(originalNormalized);
197
197
  const echoRows = echoRowsForItem(edit, originalHashes);
198
198
  if (echoRows) {
199
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
199
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
200
200
  }
201
201
  throw new Error(`[E_NOOP_LOOP] edits[${item.index}] (${item.path}): this exact edit (anchors ${item.remove_from} to ${item.remove_to}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend it; it will never change the file. The whole batch was rejected and nothing was written.` +
202
202
  (echoRows
package/lib/tool-edit.js CHANGED
@@ -75,7 +75,7 @@ export function buildEditTool(io, sandbox) {
75
75
  if (count >= NOOP_LOOP_THRESHOLD) {
76
76
  const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
77
77
  const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
78
- await recordEchoServes(sessionKey, absolutePath, echoRows, "live");
78
+ await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
79
79
  throw new Error(`[E_NOOP_LOOP] This exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend this edit; it will never change the file. Current range:\n${echo}`);
80
80
  }
81
81
  if (count === 2) {
@@ -141,7 +141,8 @@ export function buildEditTool(io, sandbox) {
141
141
  driftNotice,
142
142
  };
143
143
  const changed = buildChanged(successInput);
144
- if (changed.details.servedRows && changed.details.servedRows.length > 0) {
144
+ if (changed.details.servedRows &&
145
+ changed.details.servedRows.length > 0) {
145
146
  await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
146
147
  }
147
148
  return changed.content[0].text;
package/lib/tool-read.js CHANGED
@@ -71,7 +71,7 @@ export function buildReadTool(io) {
71
71
  });
72
72
  const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
73
73
  if (preview.served.length > 0) {
74
- await recordServed(sessionKey, absolutePath, preview.served);
74
+ await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
75
75
  }
76
76
  await clearDriftReported(sessionKey, absolutePath);
77
77
  // Record the present observation with the fs policy gate so later
@@ -40,4 +40,4 @@ export interface ResolvedRange {
40
40
  delta: number;
41
41
  }
42
42
  export type ServeRecordPolicy = "live" | "preview";
43
- export declare function recordEchoServes(sessionKey: string, path: string, rows: ServedRow[], policy: ServeRecordPolicy): Promise<void>;
43
+ export declare function recordEchoServes(sessionKey: string, path: string, rows: ServedRow[], policy: ServeRecordPolicy, lineCount?: number): Promise<void>;
@@ -9,9 +9,9 @@
9
9
  * under `workspace-write` even though the built-in `write` succeeds there.
10
10
  * @module dsh-better-edit/sandbox
11
11
  */
12
- import type { Context } from '@deepseek-ai/cordis';
13
- import type { ToolExecution } from '@deepseek-ai/dsh-tools';
14
- import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox';
12
+ import type { Context } from "@deepseek-ai/cordis";
13
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
14
+ import type { SandboxExecutionPolicy, SandboxMode } from "@deepseek-ai/dsh-sandbox";
15
15
  /** The two escalation arguments a mutating tool may carry (advertised only under a confining backend). */
16
16
  export interface FsEscalationArgs {
17
17
  sandbox_permissions?: string;
@@ -20,12 +20,12 @@ export interface FsEscalationArgs {
20
20
  /** The schema fields for the escalation arguments, spread into a tool's `parameters` when a confining backend is mounted. */
21
21
  export interface EscalationSchemaFields {
22
22
  sandbox_permissions: {
23
- type: 'string';
23
+ type: "string";
24
24
  enum: string[];
25
25
  description: string;
26
26
  };
27
27
  justification: {
28
- type: 'string';
28
+ type: "string";
29
29
  description: string;
30
30
  };
31
31
  }
@@ -17,7 +17,7 @@ export declare function upsertServed(store: HashStore, sessionKey: string, path:
17
17
  export declare function recordServes(store: HashStore, sessionKey: string, path: string, rows: Array<{
18
18
  position: number;
19
19
  hash: string | null;
20
- }>): void;
20
+ }>, lineCount?: number): void;
21
21
  /**
22
22
  * Record post-mutation diff serves against the file's CURRENT length. Before
23
23
  * upserting the diff rows, positions beyond `lineCount` are dropped from the
@@ -41,7 +41,7 @@ export declare function clearReported(store: HashStore, sessionKey: string, path
41
41
  export declare function deleteServed(store: HashStore, sessionKey: string, path: string): void;
42
42
  export declare function wipeServed(store: HashStore, sessionKey: string): void;
43
43
  export declare function loadServed(sessionKey: string, path: string): Promise<(string | null)[]>;
44
- export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[]): Promise<void>;
44
+ export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number): Promise<void>;
45
45
  /**
46
46
  * Async sibling of {@link recordServesTruncated}: record post-mutation diff
47
47
  * rows against the file's current line count.
package/lib/write-hook.js CHANGED
@@ -53,7 +53,7 @@ export function registerWriteHook(rootCtx, agentCtx, io) {
53
53
  });
54
54
  const preview = await fmtReadPreview(normalized, {}, fileHashes, absolutePath);
55
55
  if (preview.served.length > 0) {
56
- await recordServed(sessionKey, absolutePath, preview.served);
56
+ await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
57
57
  }
58
58
  await clearDriftReported(sessionKey, absolutePath);
59
59
  const text = hadUtf8DecodeErrors
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/edit/batch_edit/undo_last_edit tools for DeepSeek Harness (dsh). Every line gets a unique 3-char hash (A-Za-z0-9) that stays stable across edits; stale or ambiguous anchors are rejected, never fuzzy-matched. Undo persists across restarts.",
6
6
  "main": "lib/index.js",