Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat: on-device PDF page editing via a new pdf_edit tool
Durganshu40b09131bbd8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c75520b..ceef117 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,17 @@All notable changes to Gotcha are documented here.## [Unreleased]+### Added+- **PDF editing.** A new `pdf_edit` tool reshapes PDFs entirely on-device: merge+ several files into one, split into single pages, extract or delete a page+ range, and rotate pages, plus an `info` read for the page count. Encrypted+ files open with a password you supply — but because the edited copy cannot keep+ that protection, Gotcha now refuses the edit until it has told you the copy+ will open without a password and you have agreed. Every operation writes a new+ file and leaves the original alone unless you ask for it to be replaced. Editing the+ text or images printed on a page is not possible — PDF stores glyphs at fixed+ coordinates, so there is nothing to reflow — and a bundled `pdf_editing` skill+ teaches the assistant to say so rather than fake it.## [1.1.1]### Fixeddiff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 8e1a166..fff4f54 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -362,12 +362,15 @@ dependencies {// HTML parsing for webfetch toolimplementation("org.jsoup:jsoup:1.17.2")- // PDF text extraction for document attachments (DocumentParser). bouncycastle- // is pulled in only for encrypted/signed PDFs, which are out of scope; the- // text path never touches it, so exclude it to keep the dependency lean.- implementation("com.tom-roush:pdfbox-android:2.0.27.0") {- exclude(group = "org.bouncycastle")- }+ // PDF text extraction for document attachments (DocumentParser) and page-structure+ // editing (PdfTool). bouncycastle is pdfbox's crypto provider for encrypted PDFs;+ // it used to be excluded as out of scope, but pdf_edit takes a password argument+ // (bank statements and payslips are routinely locked). The exclusion cannot simply+ // come back: pdfbox registers BouncyCastleProvider for EVERY encrypted PDF, even+ // 40-bit RC4, so without it any password file fails with NoClassDefFoundError+ // (PdfEncryptionTest covers this). Costs ~5.6 MB of dex, which ships uncompressed+ // while isMinifyEnabled is false — enabling R8 would strip most of it.+ implementation("com.tom-roush:pdfbox-android:2.0.27.0")// Connectors: Custom Tabs for the BYO-OAuth consent flowimplementation("androidx.browser:browser:1.8.0")diff --git a/app/src/main/assets/skills/pdf.json b/app/src/main/assets/skills/pdf.jsonnew file mode 100644index 0000000..7e72ac7--- /dev/null+++ b/app/src/main/assets/skills/pdf.json@@ -0,0 +1,23 @@+{+ "id": "pdf_editing",+ "targetPackageNames": [],+ "title": "PDF Editing Skills",+ "description": "Reshape PDFs on-device with pdf_edit instead of a web converter or an app's UI.",+ "requiresTools": [+ "pdf_edit"+ ],+ "keywords": [+ "pdf",+ "pdfs",+ "page",+ "pages",+ "merge",+ "combine",+ "split",+ "rotate",+ "scan",+ "scanned",+ "booklet"+ ],+ "instructions": "Never send a PDF to a web converter and never automate a PDF app's UI to reorganise pages. pdf_edit does it locally: the file never leaves the device, and there is no watermark or page limit.\n\nWhat it does, all page-level:\n1. operation='info' — page count, file size, page dimensions. Call this FIRST whenever you need a page range and do not already know how long the document is. Never guess a page count from the file name or size.\n2. 'merge' — joins the 'inputs' array into one PDF, in exactly the order given. Confirm the order with the user when it is not obvious; a merge in the wrong order looks like data loss to them.\n3. 'split' — one file per page, written as <name>-p1.pdf, <name>-p2.pdf … into 'output' (a directory, defaulting to the input's folder). For anything longer than a few pages, ask whether they really want every page as a separate file — extract_pages is usually what they mean.\n4. 'extract_pages' — copies the pages named in 'pages' into a new PDF. This is the tool for 'just send me the invoice page' or 'pull out chapter 2'.\n5. 'delete_pages' — the inverse; drops the named pages.\n6. 'rotate_pages' — adds 90, 180 or 270 degrees clockwise. Rotation ACCUMULATES on whatever the page already had, so rotating twice by 90 lands at 180. Sideways scans are the usual reason.\n\nPage numbers are 1-based and take ranges: '3', '1-3,7', '9-' (nine to the end), or 'all'.\n\nOutput rules that matter. Every operation writes a NEW file and leaves the input untouched, so an existing output path fails unless you pass overwrite=true — do not reflexively retry with overwrite after that error, since the file in the way may be one the user still wants. Pick a clearly derived new name instead (statement-p2.pdf, report-merged.pdf) and say where you put it. Editing in place is legitimate when the user explicitly asks for it: pass the same path as input and output with overwrite=true.\n\nPassword-protected PDFs need 'password'. Ask the user for it — never guess, and never try a list of likely passwords. Editing one is gated on purpose: pdf_edit CANNOT carry the protection over to the copy it writes, so the first attempt is refused and you must warn the user before retrying. Say it plainly — 'the edited copy will not be password-protected, anyone who has the file will be able to open it' — ask with the 'question' tool, and only pass confirmed=true once they have actually agreed. Never set confirmed=true pre-emptively or to clear the error: the whole point is that the user, not you, decides to give up the protection. These are usually bank statements, payslips and medical letters, which is exactly why it is not your call. Reading is unaffected — operation='info' and read_file need only the password.\n\nThe hard limit: pdf_edit CANNOT change what is printed on a page — no editing text, fixing a typo, filling a form, redacting a name, or replacing an image. A PDF stores glyphs at fixed coordinates with no paragraphs to reflow, so this is a property of the format, not a missing feature. When asked, say that directly and offer what does work: read_file extracts the text of a PDF for you to quote or summarise, and the page operations above cover reorganising. Do not fake it by rebuilding the document from extracted text — the result loses all layout, images and signatures while looking plausible.\n\nFinding the file: PDFs usually live in /sdcard/Download, /sdcard/Documents or a WhatsApp media folder. Use glob (e.g. '/sdcard/Download/*.pdf') rather than asking the user for a full path they will not know."+}diff --git a/app/src/main/java/com/gotcha/tools/PdfTool.kt b/app/src/main/java/com/gotcha/tools/PdfTool.ktnew file mode 100644index 0000000..e9c96fe--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/PdfTool.kt@@ -0,0 +1,571 @@+package com.gotcha.tools++import android.content.Context+import com.tom_roush.pdfbox.io.MemoryUsageSetting+import com.tom_roush.pdfbox.multipdf.PDFMergerUtility+import com.tom_roush.pdfbox.pdmodel.PDDocument+import java.io.File++/**+ * Structural PDF editing on top of pdfbox-android — the write half of the+ * library [DocumentParser] already uses for text extraction.+ *+ * Covers the operations that do not require re-typesetting a page: merging,+ * splitting, extracting, deleting and rotating pages, plus a cheap [info] read+ * so the model can see the page count before choosing a range. Editing existing+ * body text is deliberately out of scope — PDF stores glyph runs at fixed+ * coordinates, so there is nothing to reflow.+ *+ * Every operation reads and writes through [FileResolver], so shared-storage+ * paths raise the usual "All files access" permission result rather than+ * throwing. Only available to Operator (writes files).+ */+@Suppress("TooManyFunctions")+class PdfTool(private val context: Context) {++ private val resolver = FileResolver(context)++ companion object {+ /**+ * Per-file input cap. Higher than [DocumentParser.MAX_DOC_BYTES] because+ * that limit protects the model's context window, which structural edits+ * never touch — this one only protects device memory.+ */+ const val MAX_PDF_BYTES = 50L * 1024 * 1024++ /** Keeps a merge from being handed an unbounded glob result. */+ const val MAX_MERGE_INPUTS = 50++ /** Ceiling on files produced by one split, so a 900-page scan cannot flood a directory. */+ const val MAX_SPLIT_FILES = 200++ /**+ * Above this, pdfbox spills its parsed objects to temp files instead of the+ * heap. Android gives an app a few hundred MB at best, and a scanned PDF+ * expands far beyond its on-disk size.+ */+ private const val MAX_MAIN_MEMORY_BYTES = 16L * 1024 * 1024++ val OPERATIONS = listOf("info", "merge", "split", "extract_pages", "delete_pages", "rotate_pages")++ private val VALID_ROTATIONS = setOf(90, 180, 270)+ }++ /**+ * Single entry point; [operation] selects the branch. Arguments that do not+ * apply to the chosen operation are ignored rather than rejected, so a model+ * that over-supplies (a `pages` on a merge) still succeeds.+ */+ @Suppress("LongParameterList", "ReturnCount")+ fun edit(+ operation: String,+ input: String? = null,+ inputs: List<String>? = null,+ output: String? = null,+ pages: String? = null,+ degrees: Int? = null,+ password: String? = null,+ overwrite: Boolean = false,+ confirmed: Boolean = false+ ): ToolResult {+ val op = operation.trim().lowercase()+ if (op !in OPERATIONS) {+ return ToolResult.error(+ "Unknown operation '$operation'. Valid operations: ${OPERATIONS.joinToString(", ")}."+ )+ }+ return try {+ when (op) {+ "info" -> info(input ?: return missing("input", op), password)+ "merge" -> merge(inputs, output ?: return missing("output", op), password, overwrite, confirmed)+ "split" -> split(input ?: return missing("input", op), output, password, overwrite, confirmed)+ "extract_pages" -> extract(+ input ?: return missing("input", op),+ output ?: return missing("output", op),+ pages ?: return missing("pages", op),+ password,+ overwrite,+ confirmed+ )+ "delete_pages" -> delete(+ input ?: return missing("input", op),+ output ?: return missing("output", op),+ pages ?: return missing("pages", op),+ password,+ overwrite,+ confirmed+ )+ else -> rotate(+ input ?: return missing("input", op),+ output ?: return missing("output", op),+ pages,+ degrees ?: return missing("degrees", op),+ password,+ overwrite,+ confirmed+ )+ }+ } catch (e: Exception) {+ ToolResult.error(describeFailure(e, password != null))+ }+ }++ // ---- operations ----++ private fun info(input: String, password: String?): ToolResult {+ val file = resolveInput(input).unwrap { return it }+ return openDocument(file, password).use { doc ->+ val sizes = (0 until doc.numberOfPages).take(MAX_SPLIT_FILES).map { i ->+ val box = doc.getPage(i).mediaBox+ "%.0f×%.0f".format(box.width, box.height)+ }+ val distinct = sizes.distinct()+ val geometry = if (distinct.size == 1) {+ "all pages ${distinct.first()} pt"+ } else {+ "mixed page sizes: ${distinct.take(4).joinToString(", ")}"+ }+ ToolResult.ok(+ "'${file.canonicalPath}': ${doc.numberOfPages} page(s), ${resolver.formatSize(file.length())}, $geometry." ++ if (doc.isEncrypted) {+ " The file is password-protected (opened with the supplied password); any edit writes an " ++ "UNPROTECTED copy, so tell the user that before editing it."+ } else {+ ""+ }+ )+ }+ }++ @Suppress("LongParameterList")+ private fun merge(+ inputs: List<String>?,+ output: String,+ password: String?,+ overwrite: Boolean,+ confirmed: Boolean+ ): ToolResult {+ if (inputs.isNullOrEmpty()) {+ return ToolResult.error(+ "merge needs an 'inputs' array of at least two PDF paths, in the order they should be joined."+ )+ }+ if (inputs.size < 2) {+ return ToolResult.error(+ "merge needs at least two input files — got ${inputs.size}. Use extract_pages to copy a single file."+ )+ }+ if (inputs.size > MAX_MERGE_INPUTS) {+ return ToolResult.error(+ "Too many inputs (${inputs.size}). Merge at most $MAX_MERGE_INPUTS files at a time."+ )+ }+ val files = inputs.map { path -> resolveInput(path).unwrap { return it } }+ val target = resolveOutput(output, overwrite).unwrap { return it }++ val sources = mutableListOf<PDDocument>()+ return try {+ val merger = PDFMergerUtility()+ PDDocument().use { dest ->+ files.forEach { file ->+ val src = openDocument(file, password)+ sources.add(src)+ decryptionConsent(src, confirmed, file.name)?.let { return it }+ merger.appendDocument(dest, src)+ }+ val wasEncrypted = sources.any { it.isEncrypted }+ val pageCount = dest.numberOfPages+ writeDocument(dest, target)+ ToolResult.ok(+ "Merged ${files.size} PDFs into '${target.canonicalPath}' — $pageCount page(s), " ++ "${resolver.formatSize(target.length())}. Source order: " ++ files.joinToString(", ") { it.name } + "." + unprotectedNote(wasEncrypted)+ )+ }+ } finally {+ sources.forEach { runCatching { it.close() } }+ }+ }++ @Suppress("LongParameterList")+ private fun split(+ input: String,+ output: String?,+ password: String?,+ overwrite: Boolean,+ confirmed: Boolean+ ): ToolResult {+ val file = resolveInput(input).unwrap { return it }+ return openDocument(file, password).use { doc ->+ decryptionConsent(doc, confirmed, file.name)?.let { return it }+ val wasEncrypted = doc.isEncrypted+ val count = doc.numberOfPages+ if (count > MAX_SPLIT_FILES) {+ return ToolResult.error(+ "'${file.name}' has $count pages, which would create $count files (limit $MAX_SPLIT_FILES). " ++ "Use extract_pages with a range instead."+ )+ }+ val dir = resolveOutputDir(output ?: file.parent.orEmpty()).unwrap { return it }+ val stem = file.nameWithoutExtension+ val written = mutableListOf<File>()+ for (i in 0 until count) {+ val part = File(dir, "$stem-p${i + 1}.pdf")+ if (part.exists() && !overwrite) {+ return ToolResult.error(+ "'${part.canonicalPath}' already exists. Pass overwrite=true to replace the split output, " ++ "or choose a different output directory."+ )+ }+ PDDocument().use { single ->+ single.importPage(doc.getPage(i))+ writeDocument(single, part)+ }+ written.add(part)+ }+ ToolResult.ok(+ "Split '${file.name}' into ${written.size} file(s) in '${dir.canonicalPath}': " ++ written.joinToString(", ") { it.name } + "." + unprotectedNote(wasEncrypted)+ )+ }+ }++ @Suppress("LongParameterList")+ private fun extract(+ input: String,+ output: String,+ pages: String,+ password: String?,+ overwrite: Boolean,+ confirmed: Boolean+ ): ToolResult {+ val file = resolveInput(input).unwrap { return it }+ val target = resolveOutput(output, overwrite).unwrap { return it }+ return openDocument(file, password).use { doc ->+ decryptionConsent(doc, confirmed, file.name)?.let { return it }+ val wasEncrypted = doc.isEncrypted+ val selected = PdfPageSpec.parse(pages, doc.numberOfPages).unwrapSpec { return ToolResult.error(it) }+ PDDocument().use { out ->+ selected.forEach { pageNumber -> out.importPage(doc.getPage(pageNumber - 1)) }+ writeDocument(out, target)+ }+ ToolResult.ok(+ "Extracted ${selected.size} page(s) (${PdfPageSpec.describe(selected)}) from '${file.name}' " ++ "into '${target.canonicalPath}'." + unprotectedNote(wasEncrypted)+ )+ }+ }++ @Suppress("LongParameterList")+ private fun delete(+ input: String,+ output: String,+ pages: String,+ password: String?,+ overwrite: Boolean,+ confirmed: Boolean+ ): ToolResult {+ val file = resolveInput(input).unwrap { return it }+ val target = resolveOutput(output, overwrite).unwrap { return it }+ return openDocument(file, password).use { doc ->+ decryptionConsent(doc, confirmed, file.name)?.let { return it }+ val wasEncrypted = doc.isEncrypted+ val total = doc.numberOfPages+ val doomed = PdfPageSpec.parse(pages, total).unwrapSpec { return ToolResult.error(it) }+ val keep = (1..total).filterNot { it in doomed }+ if (keep.isEmpty()) {+ return ToolResult.error(+ "That would delete all $total page(s), leaving an empty PDF. Keep at least one page."+ )+ }+ PDDocument().use { out ->+ keep.forEach { pageNumber -> out.importPage(doc.getPage(pageNumber - 1)) }+ writeDocument(out, target)+ }+ ToolResult.ok(+ "Deleted ${doomed.size} page(s) (${PdfPageSpec.describe(doomed)}) from '${file.name}' — " ++ "${keep.size} of $total page(s) remain in '${target.canonicalPath}'." ++ unprotectedNote(wasEncrypted)+ )+ }+ }++ @Suppress("LongParameterList")+ private fun rotate(+ input: String,+ output: String,+ pages: String?,+ degrees: Int,+ password: String?,+ overwrite: Boolean,+ confirmed: Boolean+ ): ToolResult {+ if (degrees !in VALID_ROTATIONS) {+ return ToolResult.error(+ "degrees must be one of ${VALID_ROTATIONS.sorted().joinToString(", ")} (clockwise). Got $degrees."+ )+ }+ val file = resolveInput(input).unwrap { return it }+ val target = resolveOutput(output, overwrite).unwrap { return it }+ return openDocument(file, password).use { doc ->+ decryptionConsent(doc, confirmed, file.name)?.let { return it }+ val wasEncrypted = doc.isEncrypted+ val selected = PdfPageSpec.parse(pages ?: PdfPageSpec.ALL, doc.numberOfPages)+ .unwrapSpec { return ToolResult.error(it) }+ selected.forEach { pageNumber ->+ val page = doc.getPage(pageNumber - 1)+ page.rotation = Math.floorMod(page.rotation + degrees, 360)+ }+ writeDocument(doc, target)+ ToolResult.ok(+ "Rotated ${selected.size} page(s) (${PdfPageSpec.describe(selected)}) by $degrees° clockwise in " ++ "'${target.canonicalPath}'." + unprotectedNote(wasEncrypted)+ )+ }+ }++ // ---- shared plumbing ----++ /**+ * Opens with security stripped, so a document unlocked by [password] is+ * saved as a readable file rather than one pdfbox refuses to write.+ */+ private fun openDocument(file: File, password: String?): PDDocument {+ val memory = MemoryUsageSetting.setupMixed(MAX_MAIN_MEMORY_BYTES).setTempDir(context.cacheDir)+ val doc = PDDocument.load(file, password.orEmpty(), memory)+ if (doc.isEncrypted) doc.setAllSecurityToBeRemoved(true)+ return doc+ }++ /**+ * Refuses to write an unprotected copy of a protected document until the user+ * has been told. pdfbox cannot preserve the source's encryption on save, so+ * every edit of a locked PDF silently strips its password — the file is a+ * bank statement or a payslip often enough that the user has to agree to that+ * first, not discover it afterwards. Mirrors `open_setting`'s confirm-first+ * gate: refuse once with the consequence spelled out, proceed on the re-call.+ *+ * Null when there is nothing to warn about (an unencrypted source, or consent+ * already given).+ */+ /**+ * Appended to a success message when the source was locked, so the stripped+ * protection is stated in the result the user hears, not only in the gate+ * they already clicked past.+ */+ private fun unprotectedNote(wasEncrypted: Boolean): String =+ if (wasEncrypted) " NOTE: the source was password-protected; this copy is NOT — it opens without a password." else ""++ private fun decryptionConsent(doc: PDDocument, confirmed: Boolean, name: String): ToolResult? {+ if (!doc.isEncrypted || confirmed) return null+ return ToolResult.error(+ "'$name' is password-protected, and the edited copy CANNOT keep that protection — it will be " ++ "written so that anyone can open it without the password. Tell the user this in plain words " ++ "with the 'question' tool, and only if they agree, call pdf_edit again with confirmed=true. " ++ "Do not set confirmed=true on your own."+ )+ }++ /**+ * Saves via a sibling temp file, so writing back over an input path cannot+ * truncate the document pdfbox is still reading from.+ */+ private fun writeDocument(doc: PDDocument, target: File) {+ val temp = File(target.parentFile, ".${target.name}.gotcha-tmp")+ try {+ doc.save(temp)+ if (target.exists() && !target.delete()) {+ throw java.io.IOException("could not replace the existing file at ${target.canonicalPath}")+ }+ if (!temp.renameTo(target)) {+ temp.copyTo(target, overwrite = true)+ }+ } finally {+ if (temp.exists()) temp.delete()+ }+ }++ private fun resolveInput(path: String): Result<File> {+ val file = when (val resolved = resolver.resolveForRead(path)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Result.failure(ResultCarrier(resolved.result))+ is FileResolver.ResolveResult.Error -> return fail(resolved.message)+ is FileResolver.ResolveResult.Ok -> resolved.file+ }+ resolver.checkReadPermission(file)?.let { return Result.failure(ResultCarrier(it)) }+ if (!file.exists()) {+ return fail(+ "PDF '$path' does not exist (resolved: ${file.canonicalPath}). You may use list_files or glob to find it."+ )+ }+ if (!file.isFile) return fail("'$path' is not a regular file.")+ if (file.length() > MAX_PDF_BYTES) {+ return fail(+ "'${file.name}' is ${resolver.formatSize(file.length())}; " ++ "the limit is ${resolver.formatSize(MAX_PDF_BYTES)}."+ )+ }+ if (!looksLikePdf(file)) {+ return fail("'${file.name}' is not a PDF — it does not start with the %PDF- signature.")+ }+ return Result.success(file)+ }++ private fun resolveOutput(path: String, overwrite: Boolean): Result<File> {+ val file = when (val resolved = resolver.resolveForWrite(path)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Result.failure(ResultCarrier(resolved.result))+ is FileResolver.ResolveResult.Error -> return fail(resolved.message)+ is FileResolver.ResolveResult.Ok -> resolved.file+ }+ resolver.checkWritePermission(file)?.let { return Result.failure(ResultCarrier(it)) }+ if (file.isDirectory) return fail("Output '$path' is a directory. Give the full path of the PDF to write.")+ if (file.exists() && !overwrite) {+ return fail(+ "'${file.canonicalPath}' already exists. Pass overwrite=true to replace it, or choose a different output path."+ )+ }+ file.parentFile?.let { parent ->+ if (!parent.exists() && !parent.mkdirs()) {+ return fail("Could not create the output directory '${parent.canonicalPath}'.")+ }+ }+ return Result.success(file)+ }++ private fun resolveOutputDir(path: String): Result<File> {+ val dir = when (val resolved = resolver.resolveForWrite(path)) {+ is FileResolver.ResolveResult.PermissionNeeded -> return Result.failure(ResultCarrier(resolved.result))+ is FileResolver.ResolveResult.Error -> return fail(resolved.message)+ is FileResolver.ResolveResult.Ok -> resolved.file+ }+ resolver.checkWritePermission(dir)?.let { return Result.failure(ResultCarrier(it)) }+ if (dir.exists() && !dir.isDirectory) return fail("Split output '$path' exists but is not a directory.")+ if (!dir.exists() && !dir.mkdirs()) return fail("Could not create the output directory '${dir.canonicalPath}'.")+ return Result.success(dir)+ }++ private fun looksLikePdf(file: File): Boolean {+ val header = ByteArray(5)+ val read = file.inputStream().use { it.read(header) }+ return read == header.size && resolver.detectMime(header) == "application/pdf"+ }++ /**+ * pdfbox reports a wrong or absent password as a generic+ * `InvalidPasswordException`; without translation the model sees a stack-trace+ * message and retries the same call.+ */+ private fun describeFailure(e: Exception, hadPassword: Boolean): String {+ val name = e.javaClass.simpleName+ return when {+ name == "InvalidPasswordException" && hadPassword ->+ "The supplied password did not open this PDF. Ask the user for the correct one."+ name == "InvalidPasswordException" ->+ "This PDF is password-protected. Ask the user for the password and pass it as 'password'."+ else -> "PDF operation failed: ${e.message ?: name}"+ }+ }++ private fun missing(param: String, operation: String) =+ ToolResult.error("Missing required parameter '$param' for operation '$operation'.")++ /** Carries an already-formed [ToolResult] (permission or validation) out of a helper. */+ private class ResultCarrier(val result: ToolResult) : Exception(result.message)++ private fun fail(message: String): Result<File> = Result.failure(ResultCarrier(ToolResult.error(message)))++ /** Unwraps a page-spec failure into its model-facing message. */+ private inline fun Result<List<Int>>.unwrapSpec(onFailure: (String) -> Nothing): List<Int> =+ fold(onSuccess = { it }, onFailure = { e -> onFailure(e.message.orEmpty()) })++ /** Unwraps a [ResultCarrier] failure back into the [ToolResult] the caller returns. */+ private inline fun Result<File>.unwrap(onFailure: (ToolResult) -> Nothing): File =+ fold(+ onSuccess = { it },+ onFailure = { e -> onFailure((e as? ResultCarrier)?.result ?: ToolResult.error(e.message.orEmpty())) }+ )+}++/**+ * Parsing of the 1-based page specifications the model writes ("1-3,7,10-").+ *+ * Kept apart from [PdfTool] and free of Android APIs so the range arithmetic —+ * the part most likely to be wrong — is unit-testable without Robolectric.+ */+object PdfPageSpec {++ /** Accepted spellings for "every page". */+ const val ALL = "all"++ /**+ * Returns the selected page numbers, sorted and de-duplicated, or a failure+ * whose message is written for the model to act on.+ */+ @Suppress("ReturnCount")+ fun parse(spec: String, pageCount: Int): Result<List<Int>> {+ if (pageCount <= 0) return Result.failure(IllegalArgumentException("The document has no pages."))+ val trimmed = spec.trim()+ if (trimmed.isEmpty() || trimmed.equals(ALL, ignoreCase = true)) return Result.success((1..pageCount).toList())++ val selected = sortedSetOf<Int>()+ for (part in trimmed.split(",")) {+ val token = part.trim()+ if (token.isEmpty()) continue+ val range = parseToken(token, pageCount) ?: return Result.failure(+ IllegalArgumentException(+ "Could not read the page range '$token'. Use 1-based page numbers like '1-3,7' or '9-' " ++ "(9 to the end), or 'all'. The document has $pageCount page(s)."+ )+ )+ if (range.first > pageCount || range.last > pageCount) {+ return Result.failure(+ IllegalArgumentException(+ "Page range '$token' is out of bounds — the document has $pageCount page(s)."+ )+ )+ }+ if (range.first > range.last) {+ return Result.failure(+ IllegalArgumentException("Page range '$token' runs backwards; write it low-to-high.")+ )+ }+ selected.addAll(range)+ }+ if (selected.isEmpty()) {+ return Result.failure(IllegalArgumentException("No pages selected by '$spec'. Use e.g. '1-3,7' or 'all'."))+ }+ return Result.success(selected.toList())+ }++ /** One comma-separated token: "5", "2-6", or "4-" (open-ended). Null when malformed. */+ private fun parseToken(token: String, pageCount: Int): IntRange? {+ if (!token.contains('-')) {+ val single = token.toIntOrNull() ?: return null+ return if (single < 1) null else single..single+ }+ val halves = token.split("-")+ if (halves.size != 2) return null+ val start = halves[0].trim().toIntOrNull() ?: return null+ val endText = halves[1].trim()+ val end = if (endText.isEmpty()) pageCount else endText.toIntOrNull() ?: return null+ return if (start < 1 || end < 1) null else start..end+ }++ /** Collapses a page list back to a compact human description ("1-3, 7"). */+ fun describe(pages: List<Int>): String {+ if (pages.isEmpty()) return "none"+ val parts = mutableListOf<String>()+ var start = pages.first()+ var previous = start+ for (page in pages.drop(1)) {+ if (page == previous + 1) {+ previous = page+ continue+ }+ parts.add(if (start == previous) "$start" else "$start-$previous")+ start = page+ previous = page+ }+ parts.add(if (start == previous) "$start" else "$start-$previous")+ return parts.joinToString(", ")+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex 67df16b..696eec1 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -18,7 +18,7 @@ object ToolCategories {)private val backgroundTools = setOf(- "edit", "write_file", "make_directory", "delete_file",+ "edit", "write_file", "make_directory", "delete_file", "pdf_edit","uninstall_app", "delete_calendar_event", "delete_alarm","delete_timer", "edit_alarm","toggle_wifi", "toggle_torch",diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 3de904d..7ab46cb 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1193,6 +1193,101 @@ object ToolDefinitions {})+ val pdfEdit = tool(+ "pdf_edit",+ "Edit a PDF's page structure on-device: merge several PDFs into one, split one into " ++ "single-page files, extract a page range into a new PDF, delete pages, or rotate pages. " ++ "Also reports page count and page size with operation='info' — call that first when you " ++ "need to know how many pages a file has before choosing a range. Every operation writes a " ++ "NEW file and never modifies the input unless you point 'output' at the same path with " ++ "overwrite=true. It CANNOT edit the text or images inside a page: PDF stores glyphs at " ++ "fixed coordinates, so there is nothing to reflow — to read a PDF's text use read_file " ++ "instead, and tell the user plainly that rewriting page content is not possible. Editing a " ++ "password-protected PDF strips the protection from the copy, so it is refused until you have " ++ "warned the user and pass confirmed=true.",+ schema {+ putJsonObject("properties") {+ putJsonObject("operation") {+ put("type", "string")+ putJsonArray("enum") { PdfTool.OPERATIONS.forEach { add(it) } }+ put(+ "description",+ "info = page count and size; merge = join 'inputs' in order; split = one file per " ++ "page; extract_pages = keep 'pages'; delete_pages = drop 'pages'; " ++ "rotate_pages = turn 'pages' by 'degrees'."+ )+ }+ putJsonObject("input") {+ put("type", "string")+ put(+ "description",+ "Path of the source PDF. Required by every operation except merge, e.g. " ++ "'/sdcard/Download/statement.pdf'."+ )+ }+ putJsonObject("inputs") {+ put("type", "array")+ putJsonObject("items") { put("type", "string") }+ put(+ "description",+ "merge only: two or more PDF paths, in the order they should be joined."+ )+ }+ putJsonObject("output") {+ put("type", "string")+ put(+ "description",+ "Path of the PDF to write. Required by every operation except info and split; " ++ "for split it is the output DIRECTORY and defaults to the input's folder."+ )+ }+ putJsonObject("pages") {+ put("type", "string")+ put(+ "description",+ "1-based page selection: '3', '1-3,7', '9-' (9 to the end) or 'all'. Required by " ++ "extract_pages and delete_pages; optional for rotate_pages (defaults to all)."+ )+ }+ putJsonObject("degrees") {+ put("type", "integer")+ putJsonArray("enum") {+ add(90)+ add(180)+ add(270)+ }+ put("description", "rotate_pages only: clockwise rotation to add, 90, 180 or 270.")+ }+ putJsonObject("password") {+ put("type", "string")+ put(+ "description",+ "Password for an encrypted PDF. Ask the user for it — never guess. The output is " ++ "written unencrypted."+ )+ }+ putJsonObject("confirmed") {+ put("type", "boolean")+ put(+ "description",+ "Set to true ONLY after telling the user that editing their password-protected PDF " ++ "writes an unprotected copy, and they agreed. Editing an encrypted PDF fails " ++ "without it. Never set it pre-emptively."+ )+ }+ putJsonObject("overwrite") {+ put("type", "boolean")+ put(+ "description",+ "Allow replacing an existing output file. Default false, which fails instead of " ++ "destroying a file the user may still need."+ )+ }+ }+ putJsonArray("required") { add("operation") }+ }+ )+val edit = tool("edit","Replace exact text in a file, for surgical edits without rewriting it. oldString " +@@ -2420,6 +2515,8 @@ object ToolDefinitions {todowrite,// Surgical file editing (Operator only)edit,+ // PDF page-structure editing (Operator only)+ pdfEdit,// Content search and file discoveryglob, grep,// Web search + fetchdiff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 3a0372b..8f173e6 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -61,6 +61,7 @@ class ToolExecutor(private val questionTool = QuestionTool()private val todoTool = TodoTool()private val editTool = EditTool(appContext)+ private val pdfTool = PdfTool(appContext)private val globTool = GlobTool(appContext)private val grepTool = GrepTool(appContext)private val accessibilityTool = AccessibilityTool(appContext)@@ -220,6 +221,17 @@ class ToolExecutor(append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false,binary = args["binary"]?.jsonPrimitive?.booleanOrNull ?: false)+ "pdf_edit" -> pdfTool.edit(+ operation = args.requireString("operation") ?: return missing("operation"),+ input = args.requireString("input"),+ inputs = args.requireStringList("inputs"),+ output = args.requireString("output"),+ pages = args.requireString("pages"),+ degrees = args.requireInt("degrees"),+ password = args.requireString("password"),+ overwrite = args.requireBoolean("overwrite") ?: false,+ confirmed = args.requireBoolean("confirmed") ?: false+ )"open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))"set_brightness" -> systemTool.setBrightness(args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")diff --git a/app/src/test/java/com/gotcha/tools/PdfEncryptionTest.kt b/app/src/test/java/com/gotcha/tools/PdfEncryptionTest.ktnew file mode 100644index 0000000..3d9f555--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/PdfEncryptionTest.kt@@ -0,0 +1,205 @@+package com.gotcha.tools++import androidx.test.core.app.ApplicationProvider+import com.tom_roush.pdfbox.pdmodel.PDDocument+import com.tom_roush.pdfbox.pdmodel.PDPage+import com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission+import com.tom_roush.pdfbox.pdmodel.encryption.StandardProtectionPolicy+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File++/**+ * Password-protected PDFs. These are the reason pdfbox's bouncycastle dependency+ * is no longer excluded, so this test is what justifies that APK cost: if it can+ * pass without the provider, the exclusion should come back.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PdfEncryptionTest {++ private lateinit var tool: PdfTool+ private lateinit var dir: File++ @Before+ fun setUp() {+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ DocumentParser.init(context)+ tool = PdfTool(context)+ dir = File(context.filesDir, "pdfcrypt").apply {+ deleteRecursively()+ mkdirs()+ }+ }++ /** A 2-page PDF locked with [password] at the given key length (40/128/256 bit). */+ private fun encryptedPdf(name: String, password: String, keyLength: Int): File {+ val file = File(dir, name)+ PDDocument().use { doc ->+ doc.addPage(PDPage())+ doc.addPage(PDPage())+ val policy = StandardProtectionPolicy(password, password, AccessPermission()).apply {+ encryptionKeyLength = keyLength+ }+ doc.protect(policy)+ doc.save(file)+ }+ return file+ }++ private fun assertReadable(keyLength: Int) {+ val file = encryptedPdf("locked$keyLength.pdf", "s3cret", keyLength)+ val result = tool.edit(operation = "info", input = file.path, password = "s3cret")+ assertTrue("$keyLength-bit encrypted PDF should open, got: ${result.message}", result.success)+ assertTrue(result.message.contains("2 page"))+ assertTrue("should report that it was encrypted, got: ${result.message}", result.message.contains("encrypted"))+ }++ @Test+ fun `40 bit encrypted pdf opens with the password`() = assertReadable(40)++ @Test+ fun `128 bit encrypted pdf opens with the password`() = assertReadable(128)++ @Test+ fun `256 bit AES encrypted pdf opens with the password`() = assertReadable(256)++ @Test+ fun `output of an edited encrypted pdf is written unencrypted`() {+ val file = encryptedPdf("locked.pdf", "s3cret", 128)+ val out = File(dir, "page1.pdf")+ val result = tool.edit(+ operation = "extract_pages",+ input = file.path,+ output = out.path,+ pages = "1",+ password = "s3cret",+ confirmed = true+ )+ assertTrue("got: ${result.message}", result.success)+ PDDocument.load(out).use { doc -> assertFalse("output must not stay encrypted", doc.isEncrypted) }+ }++ @Test+ fun `a wrong password is reported as such, not as a crash`() {+ val file = encryptedPdf("locked.pdf", "s3cret", 128)+ val result = tool.edit(operation = "info", input = file.path, password = "wrong")+ assertFalse(result.success)+ assertTrue("got: ${result.message}", result.message.contains("password"))+ }++ @Test+ fun `a missing password tells the model to ask the user`() {+ val file = encryptedPdf("locked.pdf", "s3cret", 128)+ val result = tool.edit(operation = "info", input = file.path)+ assertFalse(result.success)+ assertTrue("got: ${result.message}", result.message.contains("password-protected"))+ }++ // ---- the consent gate ----++ @Test+ fun `editing a protected pdf is refused until the user has been warned`() {+ val file = encryptedPdf("locked.pdf", "s3cret", 128)+ val out = File(dir, "page1.pdf")++ val refused = tool.edit(+ operation = "extract_pages",+ input = file.path,+ output = out.path,+ pages = "1",+ password = "s3cret"+ )+ assertFalse("an unconfirmed edit of a locked PDF must be refused", refused.success)+ assertTrue("got: ${refused.message}", refused.message.contains("confirmed=true"))+ assertTrue(+ "the refusal must state the consequence, got: ${refused.message}",+ refused.message.contains("without the password")+ )+ assertFalse("nothing may be written before consent", out.exists())+ }++ @Test+ fun `every write operation is gated, not just extract`() {+ val a = encryptedPdf("a.pdf", "s3cret", 128)+ val b = encryptedPdf("b.pdf", "s3cret", 128)+ val gated = listOf(+ tool.edit(operation = "split", input = a.path, output = File(dir, "out").path, password = "s3cret"),+ tool.edit(+ operation = "delete_pages",+ input = a.path,+ output = File(dir, "d.pdf").path,+ pages = "1",+ password = "s3cret"+ ),+ tool.edit(+ operation = "rotate_pages",+ input = a.path,+ output = File(dir, "r.pdf").path,+ degrees = 90,+ password = "s3cret"+ ),+ tool.edit(+ operation = "merge",+ inputs = listOf(a.path, b.path),+ output = File(dir, "m.pdf").path,+ password = "s3cret"+ )+ )+ gated.forEach { result ->+ assertFalse("expected a refusal, got: ${result.message}", result.success)+ assertTrue("got: ${result.message}", result.message.contains("confirmed=true"))+ }+ assertFalse("the split must not have written anything", File(dir, "out/a-p1.pdf").exists())+ assertFalse(File(dir, "m.pdf").exists())+ }++ @Test+ fun `info is not gated because it writes nothing`() {+ val file = encryptedPdf("locked.pdf", "s3cret", 128)+ val result = tool.edit(operation = "info", input = file.path, password = "s3cret")+ assertTrue("reading a locked PDF needs no consent, got: ${result.message}", result.success)+ assertTrue(+ "info should still flag the consequence, got: ${result.message}",+ result.message.contains("UNPROTECTED")+ )+ }++ @Test+ fun `the success message states that protection was lost`() {+ val file = encryptedPdf("locked.pdf", "s3cret", 128)+ val result = tool.edit(+ operation = "extract_pages",+ input = file.path,+ output = File(dir, "page1.pdf").path,+ pages = "1",+ password = "s3cret",+ confirmed = true+ )+ assertTrue(result.success)+ assertTrue("got: ${result.message}", result.message.contains("NOT"))+ }++ @Test+ fun `an unprotected pdf is never gated and gets no warning`() {+ val plain = File(dir, "plain.pdf")+ PDDocument().use { doc ->+ doc.addPage(PDPage())+ doc.addPage(PDPage())+ doc.save(plain)+ }+ val result = tool.edit(+ operation = "extract_pages",+ input = plain.path,+ output = File(dir, "p1.pdf").path,+ pages = "1"+ )+ assertTrue("got: ${result.message}", result.success)+ assertFalse("no protection was lost, so say nothing", result.message.contains("NOT"))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/PdfPageSpecTest.kt b/app/src/test/java/com/gotcha/tools/PdfPageSpecTest.ktnew file mode 100644index 0000000..73effbb--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/PdfPageSpecTest.kt@@ -0,0 +1,98 @@+package com.gotcha.tools++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Page-range arithmetic for `pdf_edit`. Pure JVM: [PdfPageSpec] deliberately+ * touches no Android or pdfbox API, because an off-by-one here silently deletes+ * the wrong page rather than failing loudly.+ */+class PdfPageSpecTest {++ private fun parsed(spec: String, pageCount: Int = 10): List<Int> =+ PdfPageSpec.parse(spec, pageCount).getOrThrow()++ private fun error(spec: String, pageCount: Int = 10): String {+ val result = PdfPageSpec.parse(spec, pageCount)+ assertTrue("expected '$spec' to be rejected, got ${result.getOrNull()}", result.isFailure)+ return result.exceptionOrNull()!!.message.orEmpty()+ }++ @Test+ fun `single page is one-based`() {+ assertEquals(listOf(1), parsed("1"))+ assertEquals(listOf(10), parsed("10"))+ }++ @Test+ fun `closed range is inclusive at both ends`() {+ assertEquals(listOf(2, 3, 4), parsed("2-4"))+ }++ @Test+ fun `open ended range runs to the last page`() {+ assertEquals(listOf(8, 9, 10), parsed("8-"))+ }++ @Test+ fun `mixed list is sorted and de-duplicated`() {+ assertEquals(listOf(1, 2, 3, 7), parsed("7,1-3,2"))+ }++ @Test+ fun `all and blank select every page`() {+ assertEquals((1..10).toList(), parsed("all"))+ assertEquals((1..10).toList(), parsed("ALL"))+ assertEquals((1..10).toList(), parsed(" "))+ }++ @Test+ fun `whitespace around tokens is tolerated`() {+ assertEquals(listOf(1, 2, 5), parsed(" 1 - 2 , 5 "))+ }++ @Test+ fun `page beyond the end is rejected with the real page count`() {+ val message = error("11", pageCount = 10)+ assertTrue("message should state the page count, got: $message", message.contains("10 page"))+ }++ @Test+ fun `range beyond the end is rejected`() {+ assertTrue(error("5-99").contains("out of bounds"))+ }++ @Test+ fun `page zero is rejected rather than silently clamped`() {+ assertTrue(error("0").isNotBlank())+ assertTrue(error("0-3").isNotBlank())+ }++ @Test+ fun `backwards range is rejected`() {+ assertTrue(error("7-3").contains("backwards"))+ }++ @Test+ fun `non numeric input is rejected`() {+ assertTrue(error("two").isNotBlank())+ assertTrue(error("1-x").isNotBlank())+ assertTrue(error("1-2-3").isNotBlank())+ }++ @Test+ fun `empty document is rejected`() {+ assertTrue(PdfPageSpec.parse("1", 0).isFailure)+ }++ @Test+ fun `describe collapses consecutive runs`() {+ assertEquals("1-3, 7", PdfPageSpec.describe(listOf(1, 2, 3, 7)))+ assertEquals("5", PdfPageSpec.describe(listOf(5)))+ assertEquals("1, 3, 5", PdfPageSpec.describe(listOf(1, 3, 5)))+ assertEquals("1-4", PdfPageSpec.describe(listOf(1, 2, 3, 4)))+ assertEquals("none", PdfPageSpec.describe(emptyList()))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/PdfToolTest.kt b/app/src/test/java/com/gotcha/tools/PdfToolTest.ktnew file mode 100644index 0000000..31d44c2--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/PdfToolTest.kt@@ -0,0 +1,282 @@+package com.gotcha.tools++import androidx.test.core.app.ApplicationProvider+import com.tom_roush.pdfbox.pdmodel.PDDocument+import com.tom_roush.pdfbox.pdmodel.PDPage+import com.tom_roush.pdfbox.pdmodel.PDPageContentStream+import com.tom_roush.pdfbox.pdmodel.common.PDRectangle+import com.tom_roush.pdfbox.pdmodel.font.PDType1Font+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File++/**+ * `pdf_edit` end to end. Like [DocumentParserPdfTest] this runs under Robolectric+ * because pdfbox-android needs `android.util.Log` and its asset-backed glyph+ * tables; everything is kept inside the app sandbox so [FileResolver] grants+ * access without a permission stub.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PdfToolTest {++ private lateinit var tool: PdfTool+ private lateinit var dir: File++ @Before+ fun setUp() {+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ DocumentParser.init(context)+ tool = PdfTool(context)+ dir = File(context.filesDir, "pdftest").apply {+ deleteRecursively()+ mkdirs()+ }+ }++ // ---- helpers ----++ /** Writes a PDF whose page N carries the text "Page N", so page identity survives a round trip. */+ private fun makePdf(name: String, pageCount: Int, label: String = "Page"): File {+ val file = File(dir, name)+ PDDocument().use { doc ->+ repeat(pageCount) { i ->+ val page = PDPage(PDRectangle.A4)+ doc.addPage(page)+ PDPageContentStream(doc, page).use { stream ->+ stream.beginText()+ stream.setFont(PDType1Font.HELVETICA, 24f)+ stream.newLineAtOffset(72f, 700f)+ stream.showText("$label ${i + 1}")+ stream.endText()+ }+ }+ doc.save(file)+ }+ return file+ }++ private fun textOf(file: File): String =+ DocumentParser.extract(file.readBytes(), file.name, "application/pdf").text++ private fun pageCountOf(file: File): Int =+ DocumentParser.extract(file.readBytes(), file.name, "application/pdf").pageCount ?: -1++ private fun ok(result: ToolResult): ToolResult {+ assertTrue("expected success, got: ${result.message}", result.success)+ return result+ }++ // ---- info ----++ @Test+ fun `info reports the page count`() {+ val src = makePdf("in.pdf", 3)+ val result = ok(tool.edit(operation = "info", input = src.path))+ assertTrue("got: ${result.message}", result.message.contains("3 page"))+ }++ // ---- merge ----++ @Test+ fun `merge joins documents in the given order`() {+ val a = makePdf("a.pdf", 2, label = "Alpha")+ val b = makePdf("b.pdf", 1, label = "Beta")+ val out = File(dir, "merged.pdf")++ ok(tool.edit(operation = "merge", inputs = listOf(a.path, b.path), output = out.path))++ assertEquals(3, pageCountOf(out))+ val text = textOf(out)+ assertTrue(+ "merged text should hold both sources, got: $text",+ text.contains("Alpha 1") && text.contains("Beta 1")+ )+ assertTrue("Alpha must precede Beta", text.indexOf("Alpha 1") < text.indexOf("Beta 1"))+ }++ @Test+ fun `merge of a single file is refused`() {+ val a = makePdf("a.pdf", 1)+ val result = tool.edit(operation = "merge", inputs = listOf(a.path), output = File(dir, "m.pdf").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("at least two"))+ }++ // ---- split ----++ @Test+ fun `split writes one file per page`() {+ val src = makePdf("doc.pdf", 3)+ ok(tool.edit(operation = "split", input = src.path))++ val parts = (1..3).map { File(dir, "doc-p$it.pdf") }+ parts.forEach { assertTrue("${it.name} should exist", it.exists()) }+ assertEquals(1, pageCountOf(parts[0]))+ assertTrue(textOf(parts[2]).contains("Page 3"))+ }++ // ---- extract ----++ @Test+ fun `extract keeps exactly the selected pages in order`() {+ val src = makePdf("doc.pdf", 5)+ val out = File(dir, "slice.pdf")+ ok(tool.edit(operation = "extract_pages", input = src.path, output = out.path, pages = "2-3,5"))++ assertEquals(3, pageCountOf(out))+ val text = textOf(out)+ assertTrue(text.contains("Page 2") && text.contains("Page 3") && text.contains("Page 5"))+ assertFalse("page 1 should be gone, got: $text", text.contains("Page 1"))+ assertFalse("page 4 should be gone, got: $text", text.contains("Page 4"))+ }++ @Test+ fun `extract leaves the input untouched`() {+ val src = makePdf("doc.pdf", 4)+ val before = src.readBytes()+ ok(tool.edit(operation = "extract_pages", input = src.path, output = File(dir, "o.pdf").path, pages = "1"))+ org.junit.Assert.assertArrayEquals("the source PDF must not be modified", before, src.readBytes())+ }++ // ---- delete ----++ @Test+ fun `delete drops the selected pages`() {+ val src = makePdf("doc.pdf", 4)+ val out = File(dir, "trimmed.pdf")+ ok(tool.edit(operation = "delete_pages", input = src.path, output = out.path, pages = "2"))++ assertEquals(3, pageCountOf(out))+ val text = textOf(out)+ assertFalse("page 2 should be gone, got: $text", text.contains("Page 2"))+ assertTrue(text.contains("Page 1") && text.contains("Page 3") && text.contains("Page 4"))+ }++ @Test+ fun `deleting every page is refused`() {+ val src = makePdf("doc.pdf", 2)+ val result = tool.edit(+ operation = "delete_pages",+ input = src.path,+ output = File(dir, "e.pdf").path,+ pages = "all"+ )+ assertFalse(result.success)+ assertTrue(result.message.contains("empty PDF"))+ }++ // ---- rotate ----++ @Test+ fun `rotate turns only the selected pages and accumulates`() {+ val src = makePdf("doc.pdf", 3)+ val out = File(dir, "rot.pdf")+ ok(tool.edit(operation = "rotate_pages", input = src.path, output = out.path, pages = "2", degrees = 90))++ PDDocument.load(out).use { doc ->+ assertEquals(0, doc.getPage(0).rotation)+ assertEquals(90, doc.getPage(1).rotation)+ assertEquals(0, doc.getPage(2).rotation)+ }++ val twice = File(dir, "rot2.pdf")+ ok(tool.edit(operation = "rotate_pages", input = out.path, output = twice.path, pages = "2", degrees = 90))+ PDDocument.load(twice).use { doc -> assertEquals(180, doc.getPage(1).rotation) }+ }++ @Test+ fun `rotate defaults to every page`() {+ val src = makePdf("doc.pdf", 2)+ val out = File(dir, "rot.pdf")+ ok(tool.edit(operation = "rotate_pages", input = src.path, output = out.path, degrees = 180))+ PDDocument.load(out).use { doc ->+ assertEquals(180, doc.getPage(0).rotation)+ assertEquals(180, doc.getPage(1).rotation)+ }+ }++ @Test+ fun `rotate rejects an angle that is not a quarter turn`() {+ val src = makePdf("doc.pdf", 1)+ val result = tool.edit(+ operation = "rotate_pages",+ input = src.path,+ output = File(dir, "r.pdf").path,+ degrees = 45+ )+ assertFalse(result.success)+ assertTrue(result.message.contains("90"))+ }++ // ---- guards ----++ @Test+ fun `existing output is not clobbered without overwrite`() {+ val src = makePdf("doc.pdf", 2)+ val out = makePdf("taken.pdf", 1, label = "Existing")++ val refused = tool.edit(operation = "extract_pages", input = src.path, output = out.path, pages = "1")+ assertFalse(refused.success)+ assertTrue(refused.message.contains("overwrite=true"))+ assertTrue("the existing file must survive", textOf(out).contains("Existing 1"))++ ok(tool.edit(operation = "extract_pages", input = src.path, output = out.path, pages = "1", overwrite = true))+ assertTrue(textOf(out).contains("Page 1"))+ }++ @Test+ fun `writing back over the input succeeds with overwrite`() {+ val src = makePdf("doc.pdf", 4)+ ok(tool.edit(operation = "delete_pages", input = src.path, output = src.path, pages = "1", overwrite = true))+ assertEquals(3, pageCountOf(src))+ assertFalse(textOf(src).contains("Page 1"))+ }++ @Test+ fun `a non-PDF input is rejected by signature`() {+ val fake = File(dir, "notes.pdf").apply { writeText("I am plainly not a PDF") }+ val result = tool.edit(operation = "info", input = fake.path)+ assertFalse(result.success)+ assertTrue(result.message.contains("%PDF-"))+ }++ @Test+ fun `a missing input is reported with the resolved path`() {+ val result = tool.edit(operation = "info", input = File(dir, "ghost.pdf").path)+ assertFalse(result.success)+ assertTrue(result.message.contains("does not exist"))+ }++ @Test+ fun `an unknown operation lists the valid ones`() {+ val result = tool.edit(operation = "flatten")+ assertFalse(result.success)+ assertTrue(result.message.contains("merge"))+ }++ @Test+ fun `a missing required parameter names the parameter`() {+ val result = tool.edit(+ operation = "extract_pages",+ input = makePdf("doc.pdf", 1).path,+ output = File(dir, "o.pdf").path+ )+ assertFalse(result.success)+ assertTrue(result.message.contains("pages"))+ }++ @Test+ fun `no temporary files are left behind`() {+ val src = makePdf("doc.pdf", 3)+ ok(tool.edit(operation = "extract_pages", input = src.path, output = File(dir, "o.pdf").path, pages = "1"))+ val leftovers = dir.listFiles()!!.filter { it.name.contains("gotcha-tmp") }+ assertTrue("temp files left behind: ${leftovers.map { it.name }}", leftovers.isEmpty())+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex cc04ebd..61be20f 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -406,6 +406,16 @@],"notes": "unique match, replaceAll, no-match and blank-argument rejection"},+ {+ "tool": "pdf_edit",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.PdfToolTest",+ "com.gotcha.tools.PdfPageSpecTest",+ "com.gotcha.tools.PdfEncryptionTest"+ ],+ "notes": "every operation round-tripped through pdfbox (merge order, split naming, extract/delete page identity, cumulative rotation), password-protected files at 40/128/256-bit, and the guards: overwrite refusal, safe write-back over the input, delete-all refusal, non-PDF signature rejection and page-range arithmetic"+ },{"tool": "glob","tier": "ROBOLECTRIC",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 2a78209..4eef1b7 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. |-| `ROBOLECTRIC` | 19 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 20 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **107** | |+| **Total** | **108** | |-**43 of 107** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**44 of 108** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -68,6 +68,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `notion_append_to_page` | `UNIT` | `NotionToolsTest` — block append request shape || `notion_create_page` | `UNIT` | `NotionToolsTest` — parent/title handling and request shape || `pause_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |+| `pdf_edit` | `ROBOLECTRIC` | `PdfToolTest`, `PdfPageSpecTest`, `PdfEncryptionTest` — every operation round-tripped through pdfbox (merge order, split naming, extract/delete page identity, cumulative rotation), password-protected files at 40/128/256-bit, and the guards: overwrite refusal, safe write-back over the input, delete-all refusal, non-PDF signature rejection and page-range arithmetic || `resume_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `run_command` | `UNIT` | `TerminalToolTest` — argument splitting, timeout, exit codes, output truncation || `run_root_command` | `MANUAL_ONLY` | Requires a rooted device and an interactive superuser grant. |