dsh-hashline-edit 0.4.3 → 0.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.
Files changed (63) hide show
  1. package/CHANGELOG.md +345 -0
  2. package/README.md +58 -5
  3. package/cordis.patch.yml +11 -1
  4. package/grammars/go-0.25.0-9504573f352b20be.wasm +0 -0
  5. package/grammars/java-0.23.5-4fdeac4ca6ca089f.wasm +0 -0
  6. package/grammars/python-0.25.0-16108b50df4ee9a3.wasm +0 -0
  7. package/grammars/rust-0.24.2-24c89bd9252255e4.wasm +0 -0
  8. package/grammars/tsx-0.23.2-79e5da75ea62855a.wasm +0 -0
  9. package/grammars/typescript-0.23.2-778025db5a8be0e7.wasm +0 -0
  10. package/grammars/vue-0.1.0-193c01119229352f.wasm +0 -0
  11. package/lib/client.js +13 -3
  12. package/lib/index.js +2345 -75
  13. package/lib/types/dsh/codegraph/cli.d.ts +61 -0
  14. package/lib/types/dsh/codegraph/project.d.ts +27 -0
  15. package/lib/types/dsh/codegraph/tools.d.ts +36 -0
  16. package/lib/types/dsh/codegraph/view.d.ts +25 -0
  17. package/lib/types/dsh/diagnostics/cli.d.ts +76 -0
  18. package/lib/types/dsh/diagnostics/messages.d.ts +37 -0
  19. package/lib/types/dsh/diagnostics/parse.d.ts +39 -0
  20. package/lib/types/dsh/diagnostics/tools.d.ts +20 -0
  21. package/lib/types/dsh/diagnostics/view.d.ts +31 -0
  22. package/lib/types/dsh/guidance.d.ts +7 -3
  23. package/lib/types/dsh/index.d.ts +32 -3
  24. package/lib/types/dsh/syntax-health.d.ts +60 -0
  25. package/lib/types/dsh/tools/edit.d.ts +15 -1
  26. package/lib/types/dsh/tools/output.d.ts +10 -0
  27. package/lib/types/dsh/tools/read-folded.d.ts +85 -0
  28. package/lib/types/src/bundled-assets.d.ts +13 -0
  29. package/lib/types/src/domain-errors.d.ts +12 -1
  30. package/lib/types/src/edit-tool.d.ts +9 -1
  31. package/lib/types/src/mutation-engine/edit-expand.d.ts +36 -0
  32. package/lib/types/src/mutation-engine/edit-indent.d.ts +49 -0
  33. package/lib/types/src/mutation-engine/edit-request.d.ts +8 -0
  34. package/lib/types/src/mutation-engine/types.d.ts +57 -0
  35. package/lib/types/src/payload-contract.d.ts +8 -0
  36. package/lib/types/src/read-expansion/fold-skeleton.d.ts +32 -0
  37. package/lib/types/src/read-expansion/grammar-manifest.d.ts +3 -1
  38. package/lib/types/src/read-expansion/grammar-runtime.d.ts +1 -1
  39. package/lib/types/src/read-expansion/span-expansion.d.ts +26 -0
  40. package/package.json +21 -23
  41. package/prompts/codegraph-guidelines.md +8 -0
  42. package/prompts/diagnostics-guidelines.md +8 -0
  43. package/prompts/edit-guidelines.md +6 -2
  44. package/prompts/edit.md +3 -1
  45. package/prompts/read-description.md +1 -1
  46. package/prompts/read-guidelines.md +3 -1
  47. package/src/bundled-assets.ts +23 -0
  48. package/src/domain-errors.ts +52 -1
  49. package/src/edit-tool.ts +12 -1
  50. package/src/mutation-engine/edit-expand.ts +328 -0
  51. package/src/mutation-engine/edit-indent.ts +121 -0
  52. package/src/mutation-engine/edit-request.ts +8 -1
  53. package/src/mutation-engine/pipeline.ts +150 -48
  54. package/src/mutation-engine/types.ts +54 -0
  55. package/src/payload-contract.ts +165 -19
  56. package/src/read-expansion/ast-provider.ts +32 -0
  57. package/src/read-expansion/fold-skeleton.ts +56 -0
  58. package/src/read-expansion/grammar-cache.ts +33 -1
  59. package/src/read-expansion/grammar-manifest.ts +3 -1
  60. package/src/read-expansion/grammar-runtime.ts +1 -1
  61. package/src/read-expansion/qualified-names.ts +7 -0
  62. package/src/read-expansion/read-provider.ts +9 -0
  63. package/src/read-expansion/span-expansion.ts +26 -0
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Read an asset that ships inside this package.
3
+ *
4
+ * WHY this module sits one level below the package root: `new URL("../x", import.meta.url)` is
5
+ * resolved from THIS file, so the root is one level up both in the source tree (`src/`) and in the
6
+ * published bundle (`lib/index.js`), where every `src/` module is inlined and `import.meta.url` is
7
+ * the bundle's own URL. A helper at any other depth would resolve correctly in one of the two and
8
+ * silently miss in the other.
9
+ *
10
+ * @param relativePath - path from the package root, e.g. `grammars/typescript-...wasm`.
11
+ * @returns the file's bytes, or undefined when it is absent (a partial install, a stripped build).
12
+ */
13
+ export declare function readBundledAsset(relativePath: string): Uint8Array | undefined;
@@ -28,7 +28,7 @@
28
28
  * See ADR-0047.
29
29
  */
30
30
  export type Audience = "MODEL" | "USER";
31
- export type DomainErrorCode = "E_BAD_PAYLOAD" | "E_EMPTY_RANGE" | "E_STALE_ANCHOR" | "E_UNKNOWN_ANCHOR" | "E_FOREIGN_ANCHOR" | "E_STALE_RANGE" | "E_TARGET_LOST" | "E_UNVERIFIED_RANGE" | "E_MALFORMED_ANCHOR" | "E_SUSPICIOUS_TEXT" | "E_BATCH_ABORT" | "E_NOOP_LOOP" | "E_UNSUPPORTED_FILE" | "E_ACCESS" | "E_NOT_FOUND" | "E_UNDO_STALE" | "E_UNDO_UNAVAILABLE" | "E_LOSSY_TEXT" | "E_UNDO_REVERT_FAILED" | "E_UNKNOWN" | "E_LARGE_FILE" | "E_INTERNAL_INVARIANT" | "E_PATCH_SYNTAX" | "E_UNIQUE_MATCH";
31
+ export type DomainErrorCode = "E_BAD_PAYLOAD" | "E_EMPTY_RANGE" | "E_STALE_ANCHOR" | "E_UNKNOWN_ANCHOR" | "E_FOREIGN_ANCHOR" | "E_STALE_RANGE" | "E_TARGET_LOST" | "E_UNVERIFIED_RANGE" | "E_MALFORMED_ANCHOR" | "E_SUSPICIOUS_TEXT" | "E_BATCH_ABORT" | "E_NOOP_LOOP" | "E_UNSUPPORTED_FILE" | "E_ACCESS" | "E_NOT_FOUND" | "E_UNDO_STALE" | "E_UNDO_UNAVAILABLE" | "E_LOSSY_TEXT" | "E_UNDO_REVERT_FAILED" | "E_UNKNOWN" | "E_LARGE_FILE" | "E_INTERNAL_INVARIANT" | "E_PATCH_SYNTAX" | "E_UNIQUE_MATCH" | "E_EXPAND_UNAVAILABLE";
32
32
  /**
33
33
  * The registered tool whose call produced an `E_BAD_PAYLOAD`. WHY the registered name: the model
34
34
  * reads the tool list, so `undo_last_edit` names the call it must repair and a short form would
@@ -56,6 +56,12 @@ export interface ServedRow {
56
56
  }
57
57
  export type RangeCause = "retirement" | "never-served" | "served-range staleness" | "anchor staleness" | "served span";
58
58
  export declare function isRangeCause(value: unknown): value is RangeCause;
59
+ /**
60
+ * Why `expand: "item"` could not place the anchor in one syntax item (ADR-0031). Registry-owned so
61
+ * the payload union and its renderer cannot drift; the AST provider's own refusal vocabulary stays
62
+ * internal to the expansion seam and never reaches the model.
63
+ */
64
+ export type ExpandUnavailableReason = "non-code" | "grammar-unavailable" | "no-enclosing-item" | "stale-content";
59
65
  export interface ErrorPayloadMap {
60
66
  E_BAD_PAYLOAD: {
61
67
  message: string;
@@ -194,6 +200,11 @@ export interface ErrorPayloadMap {
194
200
  servedRows?: ServedRow[];
195
201
  servedBlock?: string;
196
202
  };
203
+ E_EXPAND_UNAVAILABLE: {
204
+ path: string;
205
+ line: number;
206
+ reason: ExpandUnavailableReason;
207
+ };
197
208
  }
198
209
  export interface CodeSpec<P> {
199
210
  audience: Audience;
@@ -9,6 +9,14 @@
9
9
  * Typed boundaries: validate once at admission (payload-contract via normReq/assertReq),
10
10
  * trust inside. Immutable state: never mutates caller-owned request.
11
11
  */
12
+ import type { SpanProvider } from "./read-expansion/span-expansion.js";
13
+ /**
14
+ * The optional seams of the edit use case. `spanProvider` overrides the AST span provider an
15
+ * `expand: "item"` payload reads (ADR-0031); absent uses the engine's lazily created AST provider.
16
+ */
17
+ export interface EditToolOptions {
18
+ spanProvider?: SpanProvider;
19
+ }
12
20
  type EditToolContext = {
13
21
  cwd: string;
14
22
  sessionManager?: {
@@ -37,5 +45,5 @@ export interface EditTool {
37
45
  /** SAFETY: Preview without persisting — mirrors pi's compPreview(request, cwd, ctx). The ctx must carry the session whose serves the anchors came from (#165). */
38
46
  preview(request: unknown, cwd: string, ctx: PreviewContext): Promise<PreviewResult>;
39
47
  }
40
- export declare function createEditTool(): EditTool;
48
+ export declare function createEditTool(options?: EditToolOptions): EditTool;
41
49
  export {};
@@ -0,0 +1,36 @@
1
+ import { type HEdit, type LeaseSpanSource } from "../hashline/resolve.js";
2
+ import type { SpanProvider } from "../read-expansion/span-expansion.js";
3
+ import type { HashStore } from "../hash-store.js";
4
+ import type { ItemApplyOutcome } from "./types.js";
5
+ /** Everything the expansion needs from the pipeline's per-item state. */
6
+ export interface ExpandedItemInput {
7
+ /** The parsed item: its bounds name the licensing anchor, its `content_lines` the replacement. */
8
+ edit: HEdit;
9
+ /** The item's admitted `indent` mode, when it carried one. */
10
+ indent?: "auto";
11
+ /** The working buffer this item applies to. */
12
+ content: string;
13
+ /** Content hashes of `content`, indexed by line. */
14
+ hashes: string[];
15
+ /** The session's served mirror, used by the served hash echo gate only. */
16
+ served: (string | null)[];
17
+ /** Canon digests parallel to `served`; empty means no evidence. */
18
+ canonDigests: (string | null)[];
19
+ identity: LeaseSpanSource;
20
+ absolutePath: string;
21
+ /** The path the model named, for refusal text. */
22
+ filePath: string;
23
+ mode: "general" | "literal";
24
+ sessionKey: string;
25
+ store: HashStore;
26
+ blockedHashes?: ReadonlySet<string>;
27
+ /** Override seam; absent means the lazily created AST provider. */
28
+ provider: SpanProvider | undefined;
29
+ signal?: AbortSignal;
30
+ }
31
+ /**
32
+ * Apply one `expand: "item"` item: license the anchor, resolve the enclosing item, splice the
33
+ * replacement, and return the same outcome shape a range edit returns so every later stage (identity
34
+ * bookkeeping, drift, undo, commit, serve) is shared.
35
+ */
36
+ export declare function applyExpandedItem(input: ExpandedItemInput): Promise<ItemApplyOutcome>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Auto relative indentation for `edit` payloads (`indent: "auto"`, ADR-0030).
3
+ *
4
+ * The anchor line supplies the base indentation; the payload supplies the block. A snippet written
5
+ * flush-left — or uniformly indented, as a model naturally writes one — is re-based onto the anchor
6
+ * line so the written bytes land at the depth the model meant, without the model having to count the
7
+ * anchor's columns and without a re-read to learn them.
8
+ *
9
+ * The transform is pure and literal: the common prefix is measured over the payload's own characters,
10
+ * so a tab stays a tab and a space stays a space, and an empty (or whitespace-only) line is never
11
+ * padded. Nothing here mutates; the pipeline decides where the result goes.
12
+ */
13
+ /** The leading whitespace of one line — spaces and tabs only, matched as written. */
14
+ export declare function leadingWhitespaceOf(line: string): string;
15
+ /** What one `indent: "auto"` transform did, so the model channel can report it without a re-read. */
16
+ export interface AutoIndentResult {
17
+ /** The payload text with the shared prefix removed and the base indent written onto every line. */
18
+ text: string;
19
+ /** True when at least one byte of the payload changed. */
20
+ changed: boolean;
21
+ /** How many non-blank payload lines differ from the submitted ones. */
22
+ changedLines: number;
23
+ /** The literal prefix removed from every non-blank line (`""` when none was shared). */
24
+ strippedPrefix: string;
25
+ }
26
+ /**
27
+ * Re-base `text` onto `baseIndent`: strip the payload's own longest common leading-whitespace prefix,
28
+ * then prefix every non-blank line with the base indent. Blank lines are carried through untouched
29
+ * (they are written as the model wrote them, never padded).
30
+ */
31
+ export declare function applyAutoIndent(text: string, baseIndent: string): AutoIndentResult;
32
+ /** The applied-indentation facts one item reports through the warnings channel. */
33
+ export interface IndentSummary {
34
+ /** The anchor line's leading whitespace the payload was aligned to. */
35
+ baseIndent: string;
36
+ /** The payload's own shared prefix that was removed before the base indent was written. */
37
+ strippedPrefix: string;
38
+ /** How many non-blank payload lines moved. */
39
+ changedLines: number;
40
+ }
41
+ /**
42
+ * The model-facing note for one applied auto-indent. It reports facts only (the anchor's indentation,
43
+ * the removed prefix, the number of lines) so the model can see the written indentation without a
44
+ * re-read; it never asks the model to do anything.
45
+ */
46
+ export declare function buildIndentNote(args: {
47
+ ref: string;
48
+ summary: IndentSummary;
49
+ }): string;
@@ -16,6 +16,10 @@ export type DesiredContent = {
16
16
  mode: "copy" | "cut";
17
17
  } | {
18
18
  kind: "empty";
19
+ } | {
20
+ kind: "insert";
21
+ side: "before" | "after";
22
+ text: string;
19
23
  };
20
24
  export type NormalizedEditItem = {
21
25
  target: {
@@ -25,6 +29,10 @@ export type NormalizedEditItem = {
25
29
  at: Placement;
26
30
  payload: DesiredContent;
27
31
  file?: string;
32
+ /** Admitted `indent` mode (ADR-0030); absent is `"as-is"`. */
33
+ indent?: "auto";
34
+ /** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
35
+ expand?: "item";
28
36
  };
29
37
  export type NormalizedEditRequest = {
30
38
  file: string;
@@ -7,6 +7,8 @@
7
7
  import type { LineEnding } from "../edit-diff.js";
8
8
  import type { ResolvedRange } from "../served-session/serve-render.js";
9
9
  import type { HashStore } from "../hash-store.js";
10
+ import type { SpanProvider } from "../read-expansion/span-expansion.js";
11
+ import type { IndentSummary } from "./edit-indent.js";
10
12
  export interface PipelineOptions {
11
13
  /** Workspace root used to re-assert lifecycle path boundaries at commit time. */
12
14
  workspaceRoot?: string;
@@ -36,6 +38,11 @@ export interface PipelineOptions {
36
38
  * destination content is rewritten, so the rollback of that in-flight member is exercised.
37
39
  */
38
40
  onAfterMoveRename?: (toAbsolutePath: string) => void | Promise<void>;
41
+ /**
42
+ * Override seam for `expand: "item"` (ADR-0031): the AST span provider the expansion reads. Absent
43
+ * uses the lazily created AST provider, so a caller that never expands a node wires nothing.
44
+ */
45
+ spanProvider?: SpanProvider;
39
46
  }
40
47
  /**
41
48
  * The honest outcome of a failed multi-member commit's rollback attempt. `restored` members are
@@ -128,3 +135,53 @@ export interface ProcessedEditFile {
128
135
  */
129
136
  lifecycle?: MemberLifecycle;
130
137
  }
138
+ /** Where one item's replacement landed, in pre-item coordinates. */
139
+ interface ItemMutationSpan {
140
+ startLine: number;
141
+ endLine: number;
142
+ inserted: number;
143
+ }
144
+ /**
145
+ * The outcome of applying ONE edit item. Both the range path (`applyOneEdit`) and the
146
+ * `expand: "item"` path (`applyExpandedItem`) return it, so the mutate loop's identity bookkeeping,
147
+ * counting, drift scan and commit are shared rather than forked per payload shape.
148
+ */
149
+ interface AppliedItemOutcome {
150
+ kind: "applied";
151
+ content: string;
152
+ hashes: string[];
153
+ removedHashes: Set<string>;
154
+ range: ResolvedRange;
155
+ firstChangedLine: number | undefined;
156
+ lastChangedLine: number | undefined;
157
+ anchorWarnings: string[] | undefined;
158
+ literalBypass: boolean;
159
+ neverServedCount: number;
160
+ /** A span-ref move's retired source span, in pre-item coordinates. */
161
+ sourceRange: ResolvedRange | undefined;
162
+ /** Every line region the item mutated; the identity map splices exactly these. */
163
+ mutationSpans: ItemMutationSpan[] | undefined;
164
+ /** Honest per-item line counts for a span-ref item. */
165
+ mutationStats: {
166
+ addedLines: number;
167
+ removedLines: number;
168
+ } | undefined;
169
+ /** The applied auto-indentation, when `indent: "auto"` changed the payload. */
170
+ indent?: IndentSummary;
171
+ }
172
+ /** The outcome of an item whose replacement left the bytes unchanged. */
173
+ interface NoopItemOutcome {
174
+ kind: "noop";
175
+ range: ResolvedRange;
176
+ noopEdit: {
177
+ loc: string;
178
+ currentContent: string;
179
+ } | undefined;
180
+ anchorWarnings: string[] | undefined;
181
+ literalBypass: boolean;
182
+ neverServedCount: number;
183
+ indent?: IndentSummary;
184
+ }
185
+ /** One item's outcome: applied, or a noop that wrote nothing. */
186
+ export type ItemApplyOutcome = AppliedItemOutcome | NoopItemOutcome;
187
+ export {};
@@ -46,11 +46,19 @@ type DesiredContent = {
46
46
  mode: "copy" | "cut";
47
47
  } | {
48
48
  kind: "empty";
49
+ } | {
50
+ kind: "insert";
51
+ side: "before" | "after";
52
+ text: string;
49
53
  };
50
54
  type NormalizedEditItem = {
51
55
  target: AnchorSpan;
52
56
  at: Placement;
53
57
  payload: DesiredContent;
58
+ /** Admitted `indent` mode (ADR-0030); absent is `"as-is"`. */
59
+ indent?: "auto";
60
+ /** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
61
+ expand?: "item";
54
62
  };
55
63
  export type NormalizedEditRequest = {
56
64
  file: string;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The folded read's grammar side: which of a parsed file's nodes are its items, and how deeply each
3
+ * one nests.
4
+ *
5
+ * WHY the walk lives here and not in the read path: the answer is a property of the language's
6
+ * grammar and its decoration tables, exactly like the enclosing-scope seam beside it, so another
7
+ * grammar gains a skeleton by adding a kind table — never by teaching `read` a second tree walk.
8
+ *
9
+ * The walk reuses the enclosing-scope rules: only a node type the language's table owns is an item,
10
+ * and the file root is never one (it is the whole file, not a member of it).
11
+ *
12
+ * @module dsh-hashline-edit/read-expansion/fold-skeleton
13
+ */
14
+ import type { SyntaxNodeLike } from "./ast-span.js";
15
+ import type { ScopeDecorator } from "./scope-decoration.js";
16
+ import type { SkeletonItem } from "./span-expansion.js";
17
+ import type { SpanKindTable } from "./span-kind.js";
18
+ /**
19
+ * Collect one parsed file's items in file order, each with its nesting level.
20
+ *
21
+ * A node is an item when the language's kind table owns its grammar type; the decorator then widens
22
+ * that node to the declaration's wrappers and leading documentation, so an item's span is the same
23
+ * span an enclosing-scope read would serve. Every other node is walked through unchanged, which is
24
+ * how a declaration wrapped in `export_statement` or reached through a `variable_declarator` is
25
+ * still found at the top level of its file.
26
+ *
27
+ * @param root - the parsed file's root node.
28
+ * @param kinds - the language's grammar-type to note-kind table.
29
+ * @param decorate - the language's scope decorator (wrapper ascent plus leading decoration).
30
+ * @returns every item, in file order, at its 1-based nesting depth.
31
+ */
32
+ export declare function collectSkeletonItems(root: SyntaxNodeLike, kinds: SpanKindTable, decorate: ScopeDecorator): SkeletonItem[];
@@ -6,7 +6,9 @@
6
6
  * cache file, so a manifest bump cannot keep serving the previous grammar.
7
7
  *
8
8
  * WHY nothing here is imported as a module: the runtime (`web-tree-sitter`) is the only dependency;
9
- * grammar `.wasm` files are fetched on first use and are never part of the published package.
9
+ * WHY nothing here is imported as a module: the runtime (`web-tree-sitter`) is the only dependency;
10
+ * the pinned `.wasm` files ship inside this package under `grammars/` (ADR-0026) and are fetched only
11
+ * when that copy is missing, so a first read parses offline and never waits on the network.
10
12
  */
11
13
  export interface GrammarManifestEntry {
12
14
  readonly language: string;
@@ -6,7 +6,7 @@
6
6
  * the wasm host. `hasWebTreeSitterRuntime` is the cheap preflight; grammar bytes are only fetched
7
7
  * after it answered yes, and a resolution failure is the same answer as an offline grammar.
8
8
  *
9
- * WHY the runtime is the only dependency: grammars are fetched bytes, so the package grows only by
9
+ * WHY the runtime is the only DEPENDENCY: grammar bytes ship in this package (`grammars/`, ADR-0026)
10
10
  * the wasm host, never by a grammar set. `Language.load` accepts the verified bytes directly, so no
11
11
  * second disk read is needed after the cache check.
12
12
  */
@@ -21,6 +21,26 @@ interface AnchorWindow {
21
21
  }
22
22
  /** The window shape the seam accepts; `read` delegates anchor resolution to admission. */
23
23
  export type SpanWindow = OffsetWindow | AnchorWindow;
24
+ /**
25
+ * One retained syntax item of a folded read: the 1-indexed, inclusive lines its span covers and its
26
+ * nesting level. The span is the language's decorated item — wrappers and leading documentation
27
+ * included — so a range built from it is the whole item an edit replaces or deletes.
28
+ */
29
+ export interface SkeletonItem {
30
+ /** 1-indexed first line of the item's span. */
31
+ readonly startLine: number;
32
+ /** 1-indexed last line of the item's span. */
33
+ readonly endLine: number;
34
+ /** 1 is a top-level item; a declaration nested inside another item is one deeper. */
35
+ readonly depth: number;
36
+ }
37
+ /**
38
+ * What a skeleton attempt answered: the file's items in file order, or the typed reason it has no
39
+ * skeleton. A decline is not an error — the folded read renders the exact served page instead.
40
+ */
41
+ export type SkeletonAnswer = {
42
+ readonly items: readonly SkeletonItem[];
43
+ } | SpanDecline;
24
44
  /**
25
45
  * The boundary provider seam. A provider may answer synchronously now and asynchronously once a
26
46
  * grammar has to be fetched, so the read path always awaits it. `around_anchor` windows reach the
@@ -33,6 +53,12 @@ export interface SpanProvider {
33
53
  readonly runtimeAbsent?: boolean;
34
54
  /** Start grammar fetches off the read path; session_start calls this without awaiting. */
35
55
  prefetch?: (cwd?: string) => void | Promise<void>;
56
+ /**
57
+ * Optional: the whole file's structural skeleton, for the folded read mode. A provider that can
58
+ * name a file's items answers them in file order; one that cannot declines with the same typed
59
+ * vocabulary `enclosingSpan` uses.
60
+ */
61
+ skeleton?(file: string): SkeletonAnswer | Promise<SkeletonAnswer>;
36
62
  }
37
63
  /**
38
64
  * Only a folded requested span at or below this size triggers expansion. Folding happens first, so
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hashline-edit",
3
- "version": "0.4.3",
3
+ "version": "0.5.1",
4
4
  "description": "Hash-anchored read/apply_patch/edit tools for DeepSeek Harness (dsh). Every line gets a unique 3- or 4-char hash (A-Za-z0-9, configurable) that stays stable across edits; apply_patch and the anchored range edit tool are the file-mutation entry points, each committing its whole batch as one transaction.",
5
5
  "keywords": [
6
6
  "anchors",
@@ -33,7 +33,8 @@
33
33
  "prompts",
34
34
  "src",
35
35
  "README.md",
36
- "LICENSE"
36
+ "LICENSE",
37
+ "grammars"
37
38
  ],
38
39
  "type": "module",
39
40
  "main": "./lib/index.js",
@@ -48,25 +49,6 @@
48
49
  },
49
50
  "./package.json": "./package.json"
50
51
  },
51
- "scripts": {
52
- "test": "vitest run",
53
- "test:watch": "vitest",
54
- "test:coverage": "vitest run --coverage --coverage.thresholds.lines=85 --coverage.thresholds.statements=85 --coverage.thresholds.functions=85 --coverage.thresholds.branches=80",
55
- "test:win": "vitest run --config vitest.config.windows.ts",
56
- "test:win:3": "node scripts/test-width.mjs 3 dsh",
57
- "test:win:coverage": "vitest run --config vitest.config.windows.ts --coverage --coverage.thresholds.lines=85 --coverage.thresholds.statements=85 --coverage.thresholds.functions=85 --coverage.thresholds.branches=80",
58
- "lint": "oxlint . && knip --max-issues 0",
59
- "lint:knip": "knip --max-issues 0",
60
- "format": "oxfmt --check .",
61
- "format:fix": "oxfmt .",
62
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.dsh.json",
63
- "build": "node scripts/build-dsh.mjs",
64
- "prepublishOnly": "node scripts/build-dsh.mjs && pnpm run typecheck && pnpm run lint && pnpm run test:win",
65
- "canon:audit": "node scripts/canon-churn-audit.mjs",
66
- "prepack": "node scripts/build-dsh.mjs",
67
- "audit": "pnpm audit --audit-level high --registry https://registry.npmjs.org/",
68
- "verify": "pnpm run lint && pnpm run format && pnpm run typecheck && pnpm run test:win:coverage"
69
- },
70
52
  "dependencies": {
71
53
  "diff": "^8.0.2",
72
54
  "file-type": "^21.3.0",
@@ -114,7 +96,6 @@
114
96
  "dsh": ">=0.2.2-rc.1 <0.2.3-0",
115
97
  "node": ">=24.0.0"
116
98
  },
117
- "packageManager": "pnpm@12.0.0",
118
99
  "dsh": {
119
100
  "bundle": {
120
101
  "patch": "./cordis.patch.yml"
@@ -131,5 +112,22 @@
131
112
  "platform": "web",
132
113
  "immediately": true
133
114
  }
115
+ },
116
+ "scripts": {
117
+ "test": "vitest run",
118
+ "test:watch": "vitest",
119
+ "test:coverage": "vitest run --coverage --coverage.thresholds.lines=85 --coverage.thresholds.statements=85 --coverage.thresholds.functions=85 --coverage.thresholds.branches=80",
120
+ "test:win": "vitest run --config vitest.config.windows.ts",
121
+ "test:win:3": "node scripts/test-width.mjs 3 dsh",
122
+ "test:win:coverage": "vitest run --config vitest.config.windows.ts --coverage --coverage.thresholds.lines=85 --coverage.thresholds.statements=85 --coverage.thresholds.functions=85 --coverage.thresholds.branches=80",
123
+ "lint": "oxlint . && knip --max-issues 0",
124
+ "lint:knip": "knip --max-issues 0",
125
+ "format": "oxfmt --check .",
126
+ "format:fix": "oxfmt .",
127
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.dsh.json",
128
+ "build": "node scripts/build-dsh.mjs",
129
+ "canon:audit": "node scripts/canon-churn-audit.mjs",
130
+ "audit": "pnpm audit --audit-level high --registry https://registry.npmjs.org/",
131
+ "verify": "pnpm run lint && pnpm run format && pnpm run typecheck && pnpm run test:win:coverage"
134
132
  }
135
- }
133
+ }
@@ -0,0 +1,8 @@
1
+ # codegraph guidelines
2
+
3
+ - Prefer `codegraph_explore` over grep/find for structural questions — architecture, a flow from X to Y, where a symbol lives, what would break — whenever the workspace has a `.codegraph` index: one call returns the relevant source plus the call paths a text search cannot follow.
4
+ - Source returned by `codegraph_explore`, `codegraph_node` and `codegraph_context` is served as `HASH│content` rows and is therefore already read: edit it with the anchors it shows instead of reading the file again.
5
+ - Use `codegraph_search`, `codegraph_callers`, `codegraph_callees`, `codegraph_impact` and `codegraph_implementations` for one-hop follow-ups; they return locations only, so call `codegraph_node` when a body is needed.
6
+ - A call that reports no `.codegraph` index means the workspace is not indexed: do not index it yourself, ask the user first (`codegraph init` in the repository root).
7
+ - The `.codegraph` index is derived state: when a call reports stale or empty results, `codegraph sync` in the project root refreshes it.
8
+ - Served rows stay editable for the rest of the session while the file is unchanged: anchor leases survive later edits (unchanged lines keep their anchors, changed lines come back with fresh ones), so chain edits without re-reading. An external write to the file, or a different session, invalidates them — a refusal returns the current rows as a fresh serve.
@@ -0,0 +1,8 @@
1
+ # diagnostics guidelines
2
+
3
+ - Prefer `diagnostics` over re-reading a build log: one call turns a compiler's or linter's errors and warnings into anchored rows for the files it names.
4
+ - Every block is served as `HASH│content` rows and is therefore already read: fix the file with those anchors instead of reading it again.
5
+ - The row a diagnostic points at is named in the header above its block (`— path:line:col`); the rows stay byte-identical to a `read` page, so the marker never appears inside them.
6
+ - `tool` picks the toolchain: `cargo-check` and `cargo-clippy` for Rust, `tsc` for TypeScript. Run it from — or pass `cwd` as — the directory the toolchain expects: the cargo workspace root, or the one holding `tsconfig.json`.
7
+ - Narrow the report with `maxDiagnostics` and widen each snippet with `contextLines` (1-10) rather than reading a whole file around one error.
8
+ - A result that reports a missing toolchain, a missing `tsconfig.json` or no parseable output is guidance, not a failure: fix the invocation or ask the user how the project is built instead of retrying blindly.
@@ -1,8 +1,12 @@
1
1
  - edit: one call targets one `file` in one transaction — batch all N changes to that file as N items in the same call, and use parallel `edit` calls for different target files.
2
- - edit: every item carries exactly one payload — `text` (literal content; `""` deletes the range when `at` is `"in-place"`, and is a no-op for `"before"`/`"after"`) or `text_ref` (with required non-null `mode`: `"copy"` re-inserts the served span's bytes, `"cut"` also deletes the source lines); never both, never neither.
2
+ - edit: every item carries exactly one payload — `text` (literal content; `""` deletes the range when `at` is `"in-place"`, and is a no-op for `"before"`/`"after"`), `text_ref` (with required non-null `mode`: `"copy"` re-inserts the served span's bytes, `"cut"` also deletes the source lines), or one of the insertion slots `after`/`before` (the lines to place immediately below/above `anchor_from`); never two, never none.
3
3
  - edit: when `text_ref` uses `mode: "cut"` (same file or another served file via `text_ref.file`), the source lines are deleted automatically in the same correlated transaction — never send a second `edit` to delete the source span.
4
4
  - edit: anchors are strictly the bare `{{HASH_LEN}}` characters before `│` in served `HASH│content` rows — never a line number, full row, or null. `anchor_from` is always required and names the first line of the range; `anchor_to` is optional and names the last line — omit it to edit the single line `anchor_from` names (the range is single-line without it, which is mandatory when `at` is `"before"` or `"after"`), and a `text_ref` span always names both bounds.
5
5
  - edit: change only what the task changes — one item per intended range, keeping unchanged boundary rows and `HASH│` prefixes out of `text`.
6
6
  - edit: a stale or unknown anchor, or an overlapping range, rejects the whole call and writes nothing. A `text` payload echoing served rows in default top-level `mode: "general"` is refused (`E_SUSPICIOUS_TEXT`); prefer `text_ref` to duplicate or move served spans, or set top-level `mode: "literal"` when `text` must intentionally reproduce served lines.
7
7
  - edit: anchors already in context (from `read`, an auto-read, or an intercepted shell view that output `HASH│content` rows) need no re-read; an anchor rejection serves the current `HASH│content` rows back, so repair directly from those rows instead of re-reading or guessing.
8
- - edit: `write` is the whole-file path — use `write` to create a new file or replace every line, never `edit`.
8
+ - edit: to insert without touching the anchor line, use `after` or `before` — `{ "anchor_from": "aB3", "after": " x: 1," }` adds one line below; the payload is bare file content and never restates the anchor line (`at` + `text` is the older spelling of the same insertion and still accepted).
9
+ - edit: `indent: "auto"` (optional; default `"as-is"`) writes a flush-left or uniformly indented `text`/`after`/`before` payload at the depth of the `anchor_from` line — the tool strips the payload's shared leading-whitespace prefix and keeps tabs, spaces and blank lines as written. `text_ref` refuses `indent` (copied bytes are verbatim). The result's notes report the lines it moved.
10
+ - edit: `expand: "item"` (optional) replaces the whole syntax item containing `anchor_from` — its leading doc comment/attributes and its closing brace included — so name only `anchor_from` and send a `text` payload; `anchor_to`, `text_ref`, `after`/`before` and a non-in-place `at` are refused. Prefer it over a hand-written multi-line range when the intent is "replace this function/class/method": you do not reproduce the doc comment or the closing brace, and the diff shows the whole replaced node. It needs a shipped code grammar (rust, typescript, tsx, vue, python, go, java); a non-code file, an unavailable grammar, or an anchor outside any item refuses (`E_EXPAND_UNAVAILABLE`) and writes nothing. One expanded item per call.
11
+ - edit: a successful call that turns a clean file into one with parse errors appends a `[W_SYNTAX]` warning naming the damaged line; the write already landed, so re-read around that line and correct the range instead of repeating the call.
12
+ - edit: `write` is the whole-file path — use `write` to create a new file or replace every line, never `edit`.
package/prompts/edit.md CHANGED
@@ -1 +1,3 @@
1
- Change one or more line ranges in one target text file with hash anchors: pass `file`, `edits` (one item per change), and optional top-level `mode` (`"general"` by default, or `"literal"`). Each item names one inclusive bare `{{HASH_LEN}}`-character anchor from before `│` in served rows (`anchor_from`), an optional second one closing a multi-line range (`anchor_to` — omit it to edit the single line `anchor_from` names; pass the identical hash to spell a single line explicitly), optional `at` (`"in-place"` by default; `"before"` or `"after"` inserts at a single-line target), and exactly one payload — `text` for replacement content (`""` deletes the span when `at` is `"in-place"`, and is a no-op with `"before"`/`"after"`) or `text_ref` (`{ anchor_from, anchor_to, file?, mode: "copy" | "cut" }`, whose two bounds are always required, where required `mode` `"copy"` re-inserts the served span's bytes and `"cut"` also deletes the source lines). One call targets one `file`; only `text_ref.file` may reference another served file as the copy/cut source (with `"cut"` deleting those source lines in the same correlated transaction). A rejected call writes nothing.
1
+ Change one or more line ranges in one target text file with hash anchors: pass `file`, `edits` (one item per change), and optional top-level `mode` (`"general"` by default, or `"literal"`). Each item names one inclusive bare `{{HASH_LEN}}`-character anchor from before `│` in served rows (`anchor_from`), an optional second one closing a multi-line range (`anchor_to` — omit it to edit the single line `anchor_from` names; pass the identical hash to spell a single line explicitly), optional `at` (`"in-place"` by default; `"before"` or `"after"` inserts at a single-line target), and exactly one payload — `text` for replacement content (`""` deletes the span when `at` is `"in-place"`, and is a no-op with `"before"`/`"after"`) or `text_ref` (`{ anchor_from, anchor_to, file?, mode: "copy" | "cut" }`, whose two bounds are always required, where required `mode` `"copy"` re-inserts the served span's bytes and `"cut"` also deletes the source lines). One call targets one `file`; only `text_ref.file` may reference another served file as the copy/cut source (with `"cut"` deleting those source lines in the same correlated transaction). A rejected call writes nothing. Two shortcuts cover the common pure insertions: `after` and `before` each carry the exact lines to place immediately below or above the single line `anchor_from` names, instead of spelling `at` plus `text`. An item still carries exactly one payload — `text`, `text_ref`, `after`, or `before`.
2
+
3
+ Two optional modifiers change where and how much the payload replaces. `indent: "auto"` (default `"as-is"`) re-bases a `text`/`after`/`before` payload on the leading whitespace of the line `anchor_from` names: write the snippet flush-left — or at any uniform extra indentation — and the tool drops the snippet's own shared leading-whitespace prefix, then writes every non-blank line at the anchor line's depth. Tabs and spaces stay literal (no conversion), blank lines are left as written, and `text_ref` refuses `indent` because those bytes are copied verbatim; the result's notes name the depth it landed at. `expand: "item"` replaces the whole syntax item that contains `anchor_from` — its leading doc comment/attributes/decorators and its matching closing brace — instead of a range you spell out: name only `anchor_from` (`anchor_to` is refused, because the AST decides the end) with a `text` payload, on a shipped code grammar (rust, typescript, tsx, vue, python, go, java). Prefer `expand` over hand-writing a whole function, class or method: you never have to reproduce the doc comment or the closing brace, and the diff shows the expanded range it replaced. A non-code file, an unavailable grammar, or an anchor outside any syntax item refuses and writes nothing. An expanded item must be the only item in its call.
@@ -1 +1 @@
1
- Read a UTF-8 text file as hash-anchored `HASH│content` rows. Each anchor is the `edit` identity for that line, and only the bare `{{HASH_LEN}}` characters before `│` are the anchor. Served mode is the default; `mode: "verbatim"` returns plain text with no anchors and no line-budget cap (and does not register anchors for `edit`). Supports `offset`/`limit` paging and `windows` to batch up to 16 disjoint ranges (`offset`/`limit`, or `around_anchor` + `radius` for an anchor already served in this session) in one call. Image, binary, and directory paths are refused (`E_UNSUPPORTED_FILE`).
1
+ Read a UTF-8 text file as hash-anchored `HASH│content` rows. Each anchor is the `edit` identity for that line, and only the bare `{{HASH_LEN}}` characters before `│` are the anchor. Served mode is the default; `mode: "verbatim"` returns plain text with no anchors and no line-budget cap (and does not register anchors for `edit`); `mode: "folded"` returns the file's structural skeleton — one row per syntax item carrying that item's first and last anchors as `HASH1..HASH2│opening line` — and always covers the whole file, so it refuses `offset`/`limit`/`windows`. Supports `offset`/`limit` paging and `windows` to batch up to 16 disjoint ranges (`offset`/`limit`, or `around_anchor` + `radius` for an anchor already served in this session) in one call. Image, binary, and directory paths are refused (`E_UNSUPPORTED_FILE`).
@@ -2,4 +2,6 @@
2
2
  - read: batch up to 16 disjoint ranges of a file in ONE call with `windows` — each using `offset`/`limit`, or `around_anchor` plus `radius` around an anchor already served in this session (unserved anchors are omitted with a warning). Read multiple files with parallel `read` calls, one file per call.
3
3
  - read: keep requested windows compact (61 lines or fewer) — the tool automatically widens compact windows to their enclosing syntax block (capped at 80 lines for code/Markdown and 40 for plain text, noted `[widened …]`), so do not manually pad `offset`/`limit` margins. Single-page output is also bounded by a byte budget.
4
4
  - read: omit `mode` for any file you might later edit (code, configs, READMEs) so rows carry anchors; pass `mode: "verbatim"` only for strictly read-only reference files (e.g., skill files), as `verbatim` is uncapped and records no anchors for `edit`.
5
- - read: `read` accepts UTF-8 text files only — images, binary files, and directories are refused (`E_UNSUPPORTED_FILE`).
5
+ - read: `read` accepts UTF-8 text files only — images, binary files, and directories are refused (`E_UNSUPPORTED_FILE`).
6
+ - read: pass `mode: "folded"` to survey a large source file as its structural skeleton — one row per syntax item carrying that item's first and last anchors (`HASH1..HASH2│opening line`, or one anchor for a single-line item), with `foldDepth` 1-3 (default 1) revealing nested members. A folded read always covers the whole file and refuses `offset`/`limit`/`windows`.
7
+ - read: a folded range row is a whole-item target — copy its two anchors into `anchor_from` and `anchor_to` to replace or delete the item. A `… (N lines) …` row is a run the page did not show: its first..last anchors are served but its lines are not, so read that range with `offset`/`limit` before editing inside it.
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ /**
4
+ * Read an asset that ships inside this package.
5
+ *
6
+ * WHY this module sits one level below the package root: `new URL("../x", import.meta.url)` is
7
+ * resolved from THIS file, so the root is one level up both in the source tree (`src/`) and in the
8
+ * published bundle (`lib/index.js`), where every `src/` module is inlined and `import.meta.url` is
9
+ * the bundle's own URL. A helper at any other depth would resolve correctly in one of the two and
10
+ * silently miss in the other.
11
+ *
12
+ * @param relativePath - path from the package root, e.g. `grammars/typescript-...wasm`.
13
+ * @returns the file's bytes, or undefined when it is absent (a partial install, a stripped build).
14
+ */
15
+ export function readBundledAsset(relativePath: string): Uint8Array | undefined {
16
+ try {
17
+ return readFileSync(new URL(`../${relativePath}`, import.meta.url));
18
+ } catch {
19
+ // SAFETY: a missing or unreadable asset is "not bundled", never a failure: every caller has a
20
+ // SAFETY: fallback (a cached copy, a fetch, or simply no parse) and must stay silent.
21
+ return undefined;
22
+ }
23
+ }
@@ -57,7 +57,8 @@ export type DomainErrorCode =
57
57
  | "E_INTERNAL_INVARIANT"
58
58
  // WHY: apply_patch's two genuinely new codes (E_STALE_ANCHOR already exists above).
59
59
  | "E_PATCH_SYNTAX"
60
- | "E_UNIQUE_MATCH";
60
+ | "E_UNIQUE_MATCH"
61
+ | "E_EXPAND_UNAVAILABLE";
61
62
 
62
63
  /**
63
64
  * The registered tool whose call produced an `E_BAD_PAYLOAD`. WHY the registered name: the model
@@ -133,6 +134,17 @@ export function isRangeCause(value: unknown): value is RangeCause {
133
134
  return typeof value === "string" && (RANGE_CAUSES as readonly string[]).includes(value);
134
135
  }
135
136
 
137
+ /**
138
+ * Why `expand: "item"` could not place the anchor in one syntax item (ADR-0031). Registry-owned so
139
+ * the payload union and its renderer cannot drift; the AST provider's own refusal vocabulary stays
140
+ * internal to the expansion seam and never reaches the model.
141
+ */
142
+ export type ExpandUnavailableReason =
143
+ | "non-code"
144
+ | "grammar-unavailable"
145
+ | "no-enclosing-item"
146
+ | "stale-content";
147
+
136
148
  export interface ErrorPayloadMap {
137
149
  E_BAD_PAYLOAD: {
138
150
  message: string;
@@ -274,6 +286,11 @@ export interface ErrorPayloadMap {
274
286
  servedRows?: ServedRow[];
275
287
  servedBlock?: string;
276
288
  };
289
+ E_EXPAND_UNAVAILABLE: {
290
+ path: string;
291
+ line: number;
292
+ reason: ExpandUnavailableReason;
293
+ };
277
294
  }
278
295
 
279
296
  export interface CodeSpec<P> {
@@ -331,6 +348,36 @@ function unsupportedFormat(payload: ErrorPayloadMap["E_UNSUPPORTED_FILE"]): stri
331
348
  }
332
349
  return `Path is a binary file: ${payload.path} (${payload.description ?? "binary"}).`;
333
350
  }
351
+ /**
352
+ * Model-facing text for `E_EXPAND_UNAVAILABLE`: one clause per refused cause, facts only — the
353
+ * remedy is a different payload shape, so no `Options:` block is served (ADR-0047).
354
+ */
355
+ function expandUnavailableFormat(payload: ErrorPayloadMap["E_EXPAND_UNAVAILABLE"]): string {
356
+ const where = `line ${payload.line} of ${payload.path}`;
357
+ if (payload.reason === "non-code") {
358
+ return (
359
+ `"expand": "item" is unavailable at ${where}: the shipped syntax grammars serve rust, ` +
360
+ `typescript, tsx, vue, python, go and java files only. Nothing was written.`
361
+ );
362
+ }
363
+ if (payload.reason === "grammar-unavailable") {
364
+ return (
365
+ `"expand": "item" is unavailable at ${where}: this host has no syntax grammar for the ` +
366
+ `file. Nothing was written.`
367
+ );
368
+ }
369
+ if (payload.reason === "stale-content") {
370
+ return (
371
+ `"expand": "item" is unavailable at ${where}: the resolved syntax item no longer ` +
372
+ `contains the anchor line. Nothing was written.`
373
+ );
374
+ }
375
+ return (
376
+ `"expand": "item" is unavailable at ${where}: no single syntax item contains that line — ` +
377
+ `it sits outside every item (imports, file header) or the syntax tree could not resolve one. ` +
378
+ `Nothing was written.`
379
+ );
380
+ }
334
381
 
335
382
  function accessFormat(payload: ErrorPayloadMap["E_ACCESS"]): string {
336
383
  if (payload.kind === "symlink-loop") {
@@ -610,6 +657,10 @@ export const ERROR_REGISTRY: { [K in DomainErrorCode]: CodeSpec<ErrorPayloadMap[
610
657
  audience: "MODEL",
611
658
  format: ({ message }) => message,
612
659
  },
660
+ E_EXPAND_UNAVAILABLE: {
661
+ audience: "MODEL",
662
+ format: expandUnavailableFormat,
663
+ },
613
664
  };
614
665
 
615
666
  export interface WarningPayloadMap {